From 0774c093dd889e43a4777378083642514ccffb98 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Wed, 20 Dec 2023 20:30:32 +0000 Subject: [PATCH] Deployed c5e4180f1 to 0.3 with MkDocs 1.5.3 and mike 2.0.0 --- 0.3/release/index.html | 12 ++++++------ 0.3/search/search_index.json | 2 +- 0.3/sitemap.xml.gz | Bin 5276 -> 5276 bytes latest/release/index.html | 12 ++++++------ latest/search/search_index.json | 2 +- latest/sitemap.xml.gz | Bin 5276 -> 5276 bytes 6 files changed, 14 insertions(+), 14 deletions(-) diff --git a/0.3/release/index.html b/0.3/release/index.html index 4426df72cc..a1b3f09c95 100644 --- a/0.3/release/index.html +++ b/0.3/release/index.html @@ -9,7 +9,7 @@ body[data-md-color-scheme="slate"] .gdesc-inner { background: var(--md-default-bg-color);} body[data-md-color-scheme="slate"] .gslide-title { color: var(--md-default-fg-color);} body[data-md-color-scheme="slate"] .gslide-desc { color: var(--md-default-fg-color);} -
Skip to content

Release Notes#

0.3.8#

What's Changed#

Full Changelog: #0.3.7...0.3.8

0.3.7#

What's Changed#

Support regular FastStream Context with FastAPI plugin

from fastapi import FastAPI
+                  

Release Notes#

0.3.9#

What's Changed#

Bug fixes:#

  • fix (#1082): correct NatsTestClient stream publisher by @Lancetnik in #1083

Chore:#

Full Changelog: #0.3.8...0.3.9

0.3.8#

What's Changed#

Full Changelog: #0.3.7...0.3.8

0.3.7#

What's Changed#

Support regular FastStream Context with FastAPI plugin

from fastapi import FastAPI
 from faststream.redis.fastapi import RedisRouter, Logger
 
 router = RedisRouter()
@@ -20,7 +20,7 @@
 
 app = FastAPI(lifespan=router.lifespan_context)
 app.include_router(router)
-

Full Changelog: #0.3.6...0.3.7

0.3.6#

What's Changed#

  • chore: correct update release CI by @Lancetnik in #1050
  • Update Release Notes for main by @faststream-release-notes-updater in #1051
  • chore: fix building docs script by @davorrunje in #1055
  • 0.3.6 by @Lancetnik in #1056
  • bug: remove packaging dependency
  • bug: correct FastAPI batch consuming
  • docs: add search meta to all pages
  • docs: polish all pages styles, fix typos
  • chore: add ruff rule to check print

Full Changelog: #0.3.5...0.3.6

0.3.5#

What's Changed#

A large update by @Lancetnik in #1048

Provides with the ability to setup graceful_timeout to wait for consumed messages processed correctly before apllication shutdown - Broker(graceful_timeout=30.0) (waits up to 30 seconds)

  • allows to get acces to context.get_local("message") from FastAPI plugin
  • docs: fix Avro custom serialization example
  • docs: add KafkaBroker publish_batch notice
  • docs: add RabbitMQ security page
  • fix: respect retry attempts with NackMessage exception
  • test Kafka nack and reject behavior
  • bug: fix import error with anyio version 4.x by @davorrunje in #1049

Full Changelog: #0.3.4...0.3.5

0.3.4#

What's Changed#

Features:#

Documentation#

Chore#

Full Changelog: #0.3.3...0.3.4

0.3.3#

What's Changed#

Features:

Chores:

Full Changelog: #0.3.2...0.3.3

0.3.2#

What's Changed#

New features:#

Chore:#

Full Changelog: #0.3.1...0.3.2

0.3.1#

What's Changed#

Features:

Bug fixes:

  • fix: non-payload information injected included in AsyncAPI docs by @Lancetnik in #1015

Documentation:

New Contributors#

Full Changelog: #0.3.0...0.3.1

0.3.0#

What's Changed#

The main feature of the 0.3.0 release is added Redis support by @Lancetnik in #1003

You can install it by the following command:

pip install "faststream[redis]"
+

Full Changelog: #0.3.6...0.3.7

0.3.6#

What's Changed#

  • chore: correct update release CI by @Lancetnik in #1050
  • Update Release Notes for main by @faststream-release-notes-updater in #1051
  • chore: fix building docs script by @davorrunje in #1055
  • 0.3.6 by @Lancetnik in #1056
  • bug: remove packaging dependency
  • bug: correct FastAPI batch consuming
  • docs: add search meta to all pages
  • docs: polish all pages styles, fix typos
  • chore: add ruff rule to check print

Full Changelog: #0.3.5...0.3.6

0.3.5#

What's Changed#

A large update by @Lancetnik in #1048

Provides with the ability to setup graceful_timeout to wait for consumed messages processed correctly before apllication shutdown - Broker(graceful_timeout=30.0) (waits up to 30 seconds)

  • allows to get acces to context.get_local("message") from FastAPI plugin
  • docs: fix Avro custom serialization example
  • docs: add KafkaBroker publish_batch notice
  • docs: add RabbitMQ security page
  • fix: respect retry attempts with NackMessage exception
  • test Kafka nack and reject behavior
  • bug: fix import error with anyio version 4.x by @davorrunje in #1049

Full Changelog: #0.3.4...0.3.5

0.3.4#

What's Changed#

Features:#

Documentation#

Chore#

Full Changelog: #0.3.3...0.3.4

0.3.3#

What's Changed#

Features:

Chores:

Full Changelog: #0.3.2...0.3.3

0.3.2#

What's Changed#

New features:#

Chore:#

Full Changelog: #0.3.1...0.3.2

0.3.1#

What's Changed#

Features:

Bug fixes:

  • fix: non-payload information injected included in AsyncAPI docs by @Lancetnik in #1015

Documentation:

New Contributors#

Full Changelog: #0.3.0...0.3.1

0.3.0#

What's Changed#

The main feature of the 0.3.0 release is added Redis support by @Lancetnik in #1003

You can install it by the following command:

pip install "faststream[redis]"
 

Here is a little code example

from faststream import FastStream, Logger
 from faststream.redis import RedisBroker
 
@@ -34,8 +34,8 @@
 )
 async def handle(msg: str, logger: Logger):
     logger.info(msg)
-

Other features#

  • feat: show reload directories with --reload flag by @Lancetnik in #981
  • feat: implement validate and no_ack subscriber options (#926) by @mihail8531 in #988
  • other features by @Lancetnik in #1003
    • Improve error logs (missing CLI arguments, undefined starting)
    • Add faststream docs serve --reload ... option for documentation hotreload
    • Add faststream run --reload-extension .env option to watch by changes in such files
    • Support faststream run -k 1 -k 2 ... as k=["1", "2"] extra options
    • Add subscriber, publisher and router include_in_schema: bool argument to disable AsyncAPI render
    • remove watchfiles from default distribution
    • Allow create broker.publisher(...) with already running broker
    • FastAPI-like lifespan FastStream application context manager
    • automatic TestBroker(connect_only=...) argument based on AST
    • add NatsMessage.in_progress() method

Testing#

Documentation#

Chore#

New Contributors#

Full Changelog: #0.2.15...0.3.0

0.3.0rc0#

What's Changed#

The main feature of the 0.3.x release is added Redis support by @Lancetnik in #1003

You can install it manually:

pip install faststream==0.3.0rc0 && pip install "faststream[redis]"
-

Other features#

  • feat: show reload directories with --reload flag by @Lancetnik in #981
  • Improve error logs (missing CLI arguments, undefined starting)
  • Add faststream docs serve --reload ... option for documentation hotreload
  • Add faststream run --reload-extension .env option to watch by changes in such files
  • Support faststream run -k 1 -k 2 ... as k=["1", "2"] extra options
  • Add subscriber, publisher and router include_in_schema: bool argument to disable AsyncAPI render
  • remove watchfiles from default distribution
  • Allow create @broker.publisher(...) with already running broker
  • FastAPI-like lifespan FastStream application context manager
  • automatic TestBroker(connect_only=...) argument based on AST
  • add NatsMessage.in_progress() method

Testing#

Documentation#

Chore#

New Contributors#

Full Changelog: #0.2.15...0.3.0rc0

0.2.15#

What's Changed#

Bug fixes#

Documentation#

Misc#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.14...0.2.15

0.2.14#

What's Changed#

Bug fixes#

Documentation#

Misc#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.13...0.2.14

0.2.13#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.12...0.2.13

0.2.12#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.11...0.2.12

0.2.11#

What's Changed#

Bug fixes#

Documentation#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.10...0.2.11

Documentation#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.10...0.2.11

0.2.10#

What's Changed#

Now, you can hide your connection secrets in the AsyncAPI schema by manually setting up the server URL:

broker = RabbitBroker(
+

Other features#

  • feat: show reload directories with --reload flag by @Lancetnik in #981
  • feat: implement validate and no_ack subscriber options (#926) by @mihail8531 in #988
  • other features by @Lancetnik in #1003
    • Improve error logs (missing CLI arguments, undefined starting)
    • Add faststream docs serve --reload ... option for documentation hotreload
    • Add faststream run --reload-extension .env option to watch by changes in such files
    • Support faststream run -k 1 -k 2 ... as k=["1", "2"] extra options
    • Add subscriber, publisher and router include_in_schema: bool argument to disable AsyncAPI render
    • remove watchfiles from default distribution
    • Allow create broker.publisher(...) with already running broker
    • FastAPI-like lifespan FastStream application context manager
    • automatic TestBroker(connect_only=...) argument based on AST
    • add NatsMessage.in_progress() method

Testing#

Documentation#

Chore#

New Contributors#

Full Changelog: #0.2.15...0.3.0

0.3.0rc0#

What's Changed#

The main feature of the 0.3.x release is added Redis support by @Lancetnik in #1003

You can install it manually:

pip install faststream==0.3.0rc0 && pip install "faststream[redis]"
+

Other features#

  • feat: show reload directories with --reload flag by @Lancetnik in #981
  • Improve error logs (missing CLI arguments, undefined starting)
  • Add faststream docs serve --reload ... option for documentation hotreload
  • Add faststream run --reload-extension .env option to watch by changes in such files
  • Support faststream run -k 1 -k 2 ... as k=["1", "2"] extra options
  • Add subscriber, publisher and router include_in_schema: bool argument to disable AsyncAPI render
  • remove watchfiles from default distribution
  • Allow create @broker.publisher(...) with already running broker
  • FastAPI-like lifespan FastStream application context manager
  • automatic TestBroker(connect_only=...) argument based on AST
  • add NatsMessage.in_progress() method

Testing#

Documentation#

Chore#

New Contributors#

Full Changelog: #0.2.15...0.3.0rc0

0.2.15#

What's Changed#

Bug fixes#

Documentation#

Misc#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.14...0.2.15

0.2.14#

What's Changed#

Bug fixes#

Documentation#

Misc#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.13...0.2.14

0.2.13#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.12...0.2.13

0.2.12#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.11...0.2.12

0.2.11#

What's Changed#

Bug fixes#

Documentation#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.10...0.2.11

Documentation#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.10...0.2.11

0.2.10#

What's Changed#

Now, you can hide your connection secrets in the AsyncAPI schema by manually setting up the server URL:

broker = RabbitBroker(
     "amqp://guest:guest@localhost:5672/",  # Connection URL
     asyncapi_url="amqp://****:****@localhost:5672/",  # Public schema URL
 )
@@ -45,7 +45,7 @@
 )
 
 # amqp://guest:guest@127.0.0.1:5672/ - The final URL
-
* A more suitable faststream.security import instead of faststream.broker.security * chore: add release notes for 0.2.9 by @kumaranvpl in https://github.com/airtai/faststream/pull/894 * chore: upgrade packages by @davorrunje in https://github.com/airtai/faststream/pull/901 * chore: use js redirect and redirect to version by @kumaranvpl in https://github.com/airtai/faststream/pull/902 * feat: add asyncapi_url broker arg by @Lancetnik in https://github.com/airtai/faststream/pull/903

Full Changelog: https://github.com/airtai/faststream/compare/0.2.9...0.2.10

0.2.9#

What's Changed#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.8...0.2.9

0.2.8#

What's Changed#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.7...0.2.8

0.2.7#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.6...0.2.7

0.2.6#

What's Changed#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.5...0.2.6

0.2.5#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.4...0.2.5

0.2.4#

New Functionalities#

Now, Context provides access to inner dict keys too:

# headers is a `dict`
+
* A more suitable faststream.security import instead of faststream.broker.security * chore: add release notes for 0.2.9 by @kumaranvpl in https://github.com/airtai/faststream/pull/894 * chore: upgrade packages by @davorrunje in https://github.com/airtai/faststream/pull/901 * chore: use js redirect and redirect to version by @kumaranvpl in https://github.com/airtai/faststream/pull/902 * feat: add asyncapi_url broker arg by @Lancetnik in https://github.com/airtai/faststream/pull/903

Full Changelog: https://github.com/airtai/faststream/compare/0.2.9...0.2.10

0.2.9#

What's Changed#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.8...0.2.9

0.2.8#

What's Changed#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.7...0.2.8

0.2.7#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.6...0.2.7

0.2.6#

What's Changed#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.5...0.2.6

0.2.5#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.4...0.2.5

0.2.4#

New Functionalities#

Now, Context provides access to inner dict keys too:

# headers is a `dict`
 async def handler(
   user_id: int = Context("message.headers.user_id", cast=True),
 ): ...
@@ -58,4 +58,4 @@
 async def handler(
   level: str = Path(),
 )
-

Also, the original message Context annotation was copied from faststream.[broker].annotations.[Broker]Message to faststream.[broker].[Broker]Message to provide you with faster access to the most commonly used object (NATS example).

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.3...0.2.4

0.2.3#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.2...0.2.3

0.2.2#

What's Changed#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.1...0.2.2

0.2.1#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.0...0.2.1

0.2.0#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.1.6...0.2.0

0.1.6#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.1.5...0.1.6

0.1.4#

What's Changed#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.1.3...0.1.4

0.1.3#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.1.1...0.1.3

0.1.1#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/commits/0.1.1

0.1.0#

FastStream is a new package based on the ideas and experiences gained from FastKafka and Propan. By joining our forces, we picked up the best from both packages and created the unified way to write services capable of processing streamed data regardless of the underlying protocol. We'll continue to maintain both packages, but new development will be in this project. If you are starting a new service, this package is the recommended way to do it.

Features#

FastStream simplifies the process of writing producers and consumers for message queues, handling all the parsing, networking and documentation generation automatically.

Making streaming microservices has never been easier. Designed with junior developers in mind, FastStream simplifies your work while keeping the door open for more advanced use-cases. Here's a look at the core features that make FastStream a go-to framework for modern, data-centric microservices.

  • Multiple Brokers: FastStream provides a unified API to work across multiple message brokers (Kafka, RabbitMQ support)

  • Pydantic Validation: Leverage Pydantic's validation capabilities to serialize and validates incoming messages

  • Automatic Docs: Stay ahead with automatic AsyncAPI documentation.

  • Intuitive: full typed editor support makes your development experience smooth, catching errors before they reach runtime

  • Powerful Dependency Injection System: Manage your service dependencies efficiently with FastStream's built-in DI system.

  • Testable: supports in-memory tests, making your CI/CD pipeline faster and more reliable

  • Extendable: use extensions for lifespans, custom serialization and middlewares

  • Integrations: FastStream is fully compatible with any HTTP framework you want (FastAPI especially)

  • Built for Automatic Code Generation: FastStream is optimized for automatic code generation using advanced models like GPT and Llama

That's FastStream in a nutshell—easy, efficient, and powerful. Whether you're just starting with streaming microservices or looking to scale, FastStream has got you covered.

\ No newline at end of file +

Also, the original message Context annotation was copied from faststream.[broker].annotations.[Broker]Message to faststream.[broker].[Broker]Message to provide you with faster access to the most commonly used object (NATS example).

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.3...0.2.4

0.2.3#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.2...0.2.3

0.2.2#

What's Changed#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.1...0.2.2

0.2.1#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.0...0.2.1

0.2.0#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.1.6...0.2.0

0.1.6#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.1.5...0.1.6

0.1.4#

What's Changed#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.1.3...0.1.4

0.1.3#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.1.1...0.1.3

0.1.1#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/commits/0.1.1

0.1.0#

FastStream is a new package based on the ideas and experiences gained from FastKafka and Propan. By joining our forces, we picked up the best from both packages and created the unified way to write services capable of processing streamed data regardless of the underlying protocol. We'll continue to maintain both packages, but new development will be in this project. If you are starting a new service, this package is the recommended way to do it.

Features#

FastStream simplifies the process of writing producers and consumers for message queues, handling all the parsing, networking and documentation generation automatically.

Making streaming microservices has never been easier. Designed with junior developers in mind, FastStream simplifies your work while keeping the door open for more advanced use-cases. Here's a look at the core features that make FastStream a go-to framework for modern, data-centric microservices.

  • Multiple Brokers: FastStream provides a unified API to work across multiple message brokers (Kafka, RabbitMQ support)

  • Pydantic Validation: Leverage Pydantic's validation capabilities to serialize and validates incoming messages

  • Automatic Docs: Stay ahead with automatic AsyncAPI documentation.

  • Intuitive: full typed editor support makes your development experience smooth, catching errors before they reach runtime

  • Powerful Dependency Injection System: Manage your service dependencies efficiently with FastStream's built-in DI system.

  • Testable: supports in-memory tests, making your CI/CD pipeline faster and more reliable

  • Extendable: use extensions for lifespans, custom serialization and middlewares

  • Integrations: FastStream is fully compatible with any HTTP framework you want (FastAPI especially)

  • Built for Automatic Code Generation: FastStream is optimized for automatic code generation using advanced models like GPT and Llama

That's FastStream in a nutshell—easy, efficient, and powerful. Whether you're just starting with streaming microservices or looking to scale, FastStream has got you covered.

\ No newline at end of file diff --git a/0.3/search/search_index.json b/0.3/search/search_index.json index 7060df4656..f336ed3ebc 100644 --- a/0.3/search/search_index.json +++ b/0.3/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"separator":"[\\s\\-,:!=\\[\\]()\"`/]+|\\.(?!\\d)|&[lg]t;|(?!\\b)(?=[A-Z][a-z])","pipeline":["stopWordFilter"]},"docs":[{"location":"release/","title":"Release Notes","text":"","boost":2},{"location":"release/#038","title":"0.3.8","text":"","boost":2},{"location":"release/#whats-changed","title":"What's Changed","text":"

Full Changelog: #0.3.7...0.3.8

","boost":2},{"location":"release/#037","title":"0.3.7","text":"","boost":2},{"location":"release/#whats-changed_1","title":"What's Changed","text":"

Support regular FastStream Context with FastAPI plugin

from fastapi import FastAPI\nfrom faststream.redis.fastapi import RedisRouter, Logger\n\nrouter = RedisRouter()\n\n@router.subscriber(\"test\")\nasync def handler(msg, logger: Logger):\n    logger.info(msg)\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n

Full Changelog: #0.3.6...0.3.7

","boost":2},{"location":"release/#036","title":"0.3.6","text":"","boost":2},{"location":"release/#whats-changed_2","title":"What's Changed","text":"

Full Changelog: #0.3.5...0.3.6

","boost":2},{"location":"release/#035","title":"0.3.5","text":"","boost":2},{"location":"release/#whats-changed_3","title":"What's Changed","text":"

A large update by @Lancetnik in #1048

Provides with the ability to setup graceful_timeout to wait for consumed messages processed correctly before apllication shutdown - Broker(graceful_timeout=30.0) (waits up to 30 seconds)

Full Changelog: #0.3.4...0.3.5

","boost":2},{"location":"release/#034","title":"0.3.4","text":"","boost":2},{"location":"release/#whats-changed_4","title":"What's Changed","text":"","boost":2},{"location":"release/#features","title":"Features:","text":"","boost":2},{"location":"release/#documentation","title":"Documentation","text":"","boost":2},{"location":"release/#chore","title":"Chore","text":"

Full Changelog: #0.3.3...0.3.4

","boost":2},{"location":"release/#033","title":"0.3.3","text":"","boost":2},{"location":"release/#whats-changed_5","title":"What's Changed","text":"

Features:

Chores:

Full Changelog: #0.3.2...0.3.3

","boost":2},{"location":"release/#032","title":"0.3.2","text":"","boost":2},{"location":"release/#whats-changed_6","title":"What's Changed","text":"","boost":2},{"location":"release/#new-features","title":"New features:","text":"","boost":2},{"location":"release/#chore_1","title":"Chore:","text":"

Full Changelog: #0.3.1...0.3.2

","boost":2},{"location":"release/#031","title":"0.3.1","text":"","boost":2},{"location":"release/#whats-changed_7","title":"What's Changed","text":"

Features:

Bug fixes:

Documentation:

","boost":2},{"location":"release/#new-contributors","title":"New Contributors","text":"

Full Changelog: #0.3.0...0.3.1

","boost":2},{"location":"release/#030","title":"0.3.0","text":"","boost":2},{"location":"release/#whats-changed_8","title":"What's Changed","text":"

The main feature of the 0.3.0 release is added Redis support by @Lancetnik in #1003

You can install it by the following command:

pip install \"faststream[redis]\"\n

Here is a little code example

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n@broker.subscriber(\n    channel=\"test\",  # or\n    # list=\"test\",     or\n    # stream=\"test\",\n)\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":2},{"location":"release/#other-features","title":"Other features","text":"","boost":2},{"location":"release/#testing","title":"Testing","text":"","boost":2},{"location":"release/#documentation_1","title":"Documentation","text":"","boost":2},{"location":"release/#chore_2","title":"Chore","text":"","boost":2},{"location":"release/#new-contributors_1","title":"New Contributors","text":"

Full Changelog: #0.2.15...0.3.0

","boost":2},{"location":"release/#030rc0","title":"0.3.0rc0","text":"","boost":2},{"location":"release/#whats-changed_9","title":"What's Changed","text":"

The main feature of the 0.3.x release is added Redis support by @Lancetnik in #1003

You can install it manually:

pip install faststream==0.3.0rc0 && pip install \"faststream[redis]\"\n
","boost":2},{"location":"release/#other-features_1","title":"Other features","text":"","boost":2},{"location":"release/#testing_1","title":"Testing","text":"","boost":2},{"location":"release/#documentation_2","title":"Documentation","text":"","boost":2},{"location":"release/#chore_3","title":"Chore","text":"","boost":2},{"location":"release/#new-contributors_2","title":"New Contributors","text":"

Full Changelog: #0.2.15...0.3.0rc0

","boost":2},{"location":"release/#0215","title":"0.2.15","text":"","boost":2},{"location":"release/#whats-changed_10","title":"What's Changed","text":"","boost":2},{"location":"release/#bug-fixes","title":"Bug fixes","text":"","boost":2},{"location":"release/#documentation_3","title":"Documentation","text":"","boost":2},{"location":"release/#misc","title":"Misc","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.14...0.2.15

","boost":2},{"location":"release/#0214","title":"0.2.14","text":"","boost":2},{"location":"release/#whats-changed_11","title":"What's Changed","text":"","boost":2},{"location":"release/#bug-fixes_1","title":"Bug fixes","text":"","boost":2},{"location":"release/#documentation_4","title":"Documentation","text":"","boost":2},{"location":"release/#misc_1","title":"Misc","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.13...0.2.14

","boost":2},{"location":"release/#0213","title":"0.2.13","text":"","boost":2},{"location":"release/#whats-changed_12","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.12...0.2.13

","boost":2},{"location":"release/#0212","title":"0.2.12","text":"","boost":2},{"location":"release/#whats-changed_13","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.11...0.2.12

","boost":2},{"location":"release/#0211","title":"0.2.11","text":"","boost":2},{"location":"release/#whats-changed_14","title":"What's Changed","text":"","boost":2},{"location":"release/#bug-fixes_2","title":"Bug fixes","text":"","boost":2},{"location":"release/#documentation_5","title":"Documentation","text":"","boost":2},{"location":"release/#new-contributors_3","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.10...0.2.11

","boost":2},{"location":"release/#documentation_6","title":"Documentation","text":"","boost":2},{"location":"release/#new-contributors_4","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.10...0.2.11

","boost":2},{"location":"release/#0210","title":"0.2.10","text":"","boost":2},{"location":"release/#whats-changed_15","title":"What's Changed","text":"

Now, you can hide your connection secrets in the AsyncAPI schema by manually setting up the server URL:

broker = RabbitBroker(\n    \"amqp://guest:guest@localhost:5672/\",  # Connection URL\n    asyncapi_url=\"amqp://****:****@localhost:5672/\",  # Public schema URL\n)\n

Additionally, the RabbitMQ AsyncAPI schema has been improved, adding support for faststream.security, and the connection scheme is now defined automatically.

RabbitMQ connection parameters are now merged, allowing you to define the main connection data as a URL string and customize it using kwargs:

broker = RabbitBroker(\n    \"amqp://guest:guest@localhost:5672/\",\n    host=\"127.0.0.1\",\n)\n\n# amqp://guest:guest@127.0.0.1:5672/ - The final URL\n
* A more suitable faststream.security import instead of faststream.broker.security * chore: add release notes for 0.2.9 by @kumaranvpl in https://github.com/airtai/faststream/pull/894 * chore: upgrade packages by @davorrunje in https://github.com/airtai/faststream/pull/901 * chore: use js redirect and redirect to version by @kumaranvpl in https://github.com/airtai/faststream/pull/902 * feat: add asyncapi_url broker arg by @Lancetnik in https://github.com/airtai/faststream/pull/903

Full Changelog: https://github.com/airtai/faststream/compare/0.2.9...0.2.10

","boost":2},{"location":"release/#029","title":"0.2.9","text":"","boost":2},{"location":"release/#whats-changed_16","title":"What's Changed","text":"","boost":2},{"location":"release/#new-contributors_5","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.8...0.2.9

","boost":2},{"location":"release/#028","title":"0.2.8","text":"","boost":2},{"location":"release/#whats-changed_17","title":"What's Changed","text":"","boost":2},{"location":"release/#new-contributors_6","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.7...0.2.8

","boost":2},{"location":"release/#027","title":"0.2.7","text":"","boost":2},{"location":"release/#whats-changed_18","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.6...0.2.7

","boost":2},{"location":"release/#026","title":"0.2.6","text":"","boost":2},{"location":"release/#whats-changed_19","title":"What's Changed","text":"","boost":2},{"location":"release/#new-contributors_7","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.5...0.2.6

","boost":2},{"location":"release/#025","title":"0.2.5","text":"","boost":2},{"location":"release/#whats-changed_20","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.4...0.2.5

","boost":2},{"location":"release/#024","title":"0.2.4","text":"","boost":2},{"location":"release/#new-functionalities","title":"New Functionalities","text":"

Now, Context provides access to inner dict keys too:

# headers is a `dict`\nasync def handler(\n  user_id: int = Context(\"message.headers.user_id\", cast=True),\n): ...\n

Added Header object as a shortcut to Context(\"message.headers.\") inner fields (NATS example):

# the same with the previous example\nasync def handler(\n  user_id: int = Header(),\n  u_id: int = Header(\"user_id\"),  # with custom name\n): ...\n

Added Path object to get access to NATS wildcard subject or RabbitMQ topic routing key (a shortcut to access Context(\"message.path.\") as well):

@nats_broker.subscriber(\"logs.{level}\")\nasync def handler(\n  level: str = Path(),\n)\n

Also, the original message Context annotation was copied from faststream.[broker].annotations.[Broker]Message to faststream.[broker].[Broker]Message to provide you with faster access to the most commonly used object (NATS example).

","boost":2},{"location":"release/#whats-changed_21","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.3...0.2.4

","boost":2},{"location":"release/#023","title":"0.2.3","text":"","boost":2},{"location":"release/#whats-changed_22","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.2...0.2.3

","boost":2},{"location":"release/#022","title":"0.2.2","text":"","boost":2},{"location":"release/#whats-changed_23","title":"What's Changed","text":"","boost":2},{"location":"release/#new-contributors_8","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.1...0.2.2

","boost":2},{"location":"release/#021","title":"0.2.1","text":"","boost":2},{"location":"release/#whats-changed_24","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.0...0.2.1

","boost":2},{"location":"release/#020","title":"0.2.0","text":"","boost":2},{"location":"release/#whats-changed_25","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.1.6...0.2.0

","boost":2},{"location":"release/#016","title":"0.1.6","text":"","boost":2},{"location":"release/#whats-changed_26","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.1.5...0.1.6

","boost":2},{"location":"release/#014","title":"0.1.4","text":"","boost":2},{"location":"release/#whats-changed_27","title":"What's Changed","text":"","boost":2},{"location":"release/#new-contributors_9","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.1.3...0.1.4

","boost":2},{"location":"release/#013","title":"0.1.3","text":"","boost":2},{"location":"release/#whats-changed_28","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.1.1...0.1.3

","boost":2},{"location":"release/#011","title":"0.1.1","text":"","boost":2},{"location":"release/#whats-changed_29","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/commits/0.1.1

","boost":2},{"location":"release/#010","title":"0.1.0","text":"

FastStream is a new package based on the ideas and experiences gained from FastKafka and Propan. By joining our forces, we picked up the best from both packages and created the unified way to write services capable of processing streamed data regardless of the underlying protocol. We'll continue to maintain both packages, but new development will be in this project. If you are starting a new service, this package is the recommended way to do it.

","boost":2},{"location":"release/#features_1","title":"Features","text":"

FastStream simplifies the process of writing producers and consumers for message queues, handling all the parsing, networking and documentation generation automatically.

Making streaming microservices has never been easier. Designed with junior developers in mind, FastStream simplifies your work while keeping the door open for more advanced use-cases. Here's a look at the core features that make FastStream a go-to framework for modern, data-centric microservices.

That's FastStream in a nutshell\u2014easy, efficient, and powerful. Whether you're just starting with streaming microservices or looking to scale, FastStream has got you covered.

","boost":2},{"location":"scheduling/","title":"Tasks Scheduling","text":"

FastStream is a framework for asynchronous service development. It allows you to build disturbed event-based systems in an easy way. Tasks scheduling is a pretty often usecase in such systems.

Unfortunatelly, this functional conflicts with the original FastStream ideology and can't be implemented as a part of the framework. But, you can integrate scheduling in your FastStream application by using some extra dependencies. And we have some reciepts how to make it.

","boost":10},{"location":"scheduling/#taskiq-faststream","title":"Taskiq-FastStream","text":"

Taskiq is an asynchronous distributed task queue for python. This project takes inspiration from big projects such as Celery and Dramatiq.

As a Celery replacement, Taskiq should support tasks sheduling and delayied publishing, of course. And it does!

By the way, you can easely integrate FastStream with the Taskiq. It allows you to create cron or delayied tasks to publish messages and trigger some functions this way.

We have a helpful project to provide you with this feature - Taskiq-FastStream.

You can install it by the following command

pip install taskiq-faststream\n

It has two hepfull classes BrokerWrapper and AppWrapper to make your FastStream App and Broker objects taskiq-compatible.

Let's take a look at the code example.

At first, we should create a regular FastStream application.

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-topic\")\n@broker.publisher(\"out-topic\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-queue\")\n@broker.publisher(\"out-queue\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-subject\")\n@broker.publisher(\"out-subject\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-channel\")\n@broker.publisher(\"out-channel\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n
","boost":10},{"location":"scheduling/#broker-wrapper","title":"Broker Wrapper","text":"

Now, if you want to make it just working, we should wrap our Broker to special BrokerWrapper object:

from taskiq_faststream import BrokerWrapper\n\ntaskiq_broker = BrokerWrapper(broker)\n

It creates a taskiq-compatible object, that can be used as an object to create a regular taskiq scheduler.

KafkaRabbitMQNATSRedis
from taskiq_faststream import StreamScheduler\nfrom taskiq.schedule_sources import LabelScheduleSource\n\ntaskiq_broker.task(\n    message={\"user\": \"John\", \"user_id\": 1},\n    topic=\"in-topic\",\n    schedule=[{\n        \"cron\": \"* * * * *\",\n    }],\n)\n\nscheduler = StreamScheduler(\n    broker=taskiq_broker,\n    sources=[LabelScheduleSource(taskiq_broker)],\n)\n
from taskiq_faststream import StreamScheduler\nfrom taskiq.schedule_sources import LabelScheduleSource\n\ntaskiq_broker.task(\n    message={\"user\": \"John\", \"user_id\": 1},\n    queue=\"in-queue\",\n    schedule=[{\n        \"cron\": \"* * * * *\",\n    }],\n)\n\nscheduler = StreamScheduler(\n    broker=taskiq_broker,\n    sources=[LabelScheduleSource(taskiq_broker)],\n)\n
from taskiq_faststream import StreamScheduler\nfrom taskiq.schedule_sources import LabelScheduleSource\n\ntaskiq_broker.task(\n    message={\"user\": \"John\", \"user_id\": 1},\n    subject=\"in-subject\",\n    schedule=[{\n        \"cron\": \"* * * * *\",\n    }],\n)\n\nscheduler = StreamScheduler(\n    broker=taskiq_broker,\n    sources=[LabelScheduleSource(taskiq_broker)],\n)\n
from taskiq_faststream import StreamScheduler\nfrom taskiq.schedule_sources import LabelScheduleSource\n\ntaskiq_broker.task(\n    message={\"user\": \"John\", \"user_id\": 1},\n    channel=\"in-channel\",\n    schedule=[{\n        \"cron\": \"* * * * *\",\n    }],\n)\n\nscheduler = StreamScheduler(\n    broker=taskiq_broker,\n    sources=[LabelScheduleSource(taskiq_broker)],\n)\n

We patched the original TaskiqScheduler to support message generation callbacks, but its signature remains the same.

broker.task(...) has the same with the original broker.publish(...) signature and allows you to plan your publishing tasks usign the great taskiq schedule option (you can learn more about it here).

Finally, to run the scheduler, please use the taskiq CLI command:

taskiq scheduler module:scheduler\n
","boost":10},{"location":"scheduling/#application-wrapper","title":"Application Wrapper","text":"

If you don't wont to lost application AsyncAPI schema or/and lifespans, you can wrap not the broker, but application by itself using AppWrapper class.

from taskiq_faststream import AppWrapper\n\ntaskiq_broker = AppWrapper(app)\n

It allows you to use taskiq_broker the same way with the previous example, but saves all original FastStream features.

Tip

Creating a separated Scheduler service is a best way to make really disturbed and susteinable system. In this case, you can just create an empty FastStream broker and use Taskiq-FastStream integration to publish your messages (consuming by another services).

","boost":10},{"location":"scheduling/#generate-message-payload","title":"Generate message payload","text":"

Also, you able to determine message payload right before sending and do not use the final one. To make it, just replace message option from the final value to function (sync or async), that returns data to send:

async def collect_information_to_send():\n    return \"Message to send\"\n\ntaskiq_broker.task(\n    message=collect_information_to_send,\n    ...\n)\n

It allows you to collect some data from database, request an outer API, or use another ways to generate data to send right before sending.

More than, you can send not one, but multiple messages per one task using this feature. Just turn your message callback function to generator (sync or async) - and Taskiq-FastStream will iterates over your payload and publishes all of your messages!

async def collect_information_to_send():\n    \"\"\"Publish 10 messages per task call.\"\"\"\n    for i in range(10):\n        yield i\n\ntaskiq_broker.task(\n    message=collect_information_to_send,\n    ...\n)\n
","boost":10},{"location":"scheduling/#rocketry","title":"Rocketry","text":"

Also, you can integrate your FastStream application with any other libraries provides you with a scheduling functional.

As an example, you can use Rocketry:

import asyncio\n\nfrom rocketry import Rocketry\nfrom rocketry.args import Arg\n\nfrom faststream.nats import NatsBroker\n\napp = Rocketry(execution=\"async\")\n\nbroker = NatsBroker()      # regular broker\napp.params(broker=broker)\n\nasync def start_app():\n    async with broker:     # connect broker\n        await app.serve()  # run rocketry\n\n@app.task(\"every 1 second\", execution=\"async\")\nasync def publish(br: NatsBroker = Arg(\"broker\")):\n    await br.publish(\"Hi, Rocketry!\", \"test\")\n\nif __name__ == \"__main__\":\n    asyncio.run(start_app())\n
","boost":10},{"location":"api/","title":"Reference - Code API","text":"

Here's the reference or code API, the classes, functions, parameters, attributes, and all the FastAPI parts you can use in your applications.

If you want to learn FastStream you are much better off reading the FastStream Tutorial.

"},{"location":"api/faststream/BaseMiddleware/","title":"BaseMiddleware","text":"","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware","title":"faststream.BaseMiddleware","text":"
BaseMiddleware(msg: Any)\n

A base middleware class.

METHOD DESCRIPTION on_receive

Called when a message is received.

after_processed

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) -> Optional[bool]: Called after processing a message.

__aenter__

Called when entering a context.

__aexit__

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) -> Optional[bool]: Called when exiting a context.

on_consume

DecodedMessage) -> DecodedMessage: Called before consuming a message.

after_consume

Optional[Exception]) -> None: Called after consuming a message.

consume_scope

DecodedMessage) -> AsyncIterator[DecodedMessage]: Context manager for consuming a message.

on_publish

SendableMessage) -> SendableMessage: Called before publishing a message.

after_publish

Optional[Exception]) -> None: Asynchronous function to handle the after publish event.

Initialize the class.

PARAMETER DESCRIPTION msg

Any message to be stored.

TYPE: Any

Source code in faststream/broker/middlewares.py
def __init__(self, msg: Any) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        msg: Any message to be stored.\n    \"\"\"\n    self.msg = msg\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.msg","title":"msg instance-attribute","text":"
msg = msg\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.after_consume","title":"after_consume async","text":"
after_consume(err: Optional[Exception]) -> None\n

A function to handle the result of consuming a resource asynchronously.

PARAMETER DESCRIPTION err

Optional exception that occurred during consumption

RAISES DESCRIPTION err

If an exception occurred during consumption

Source code in faststream/broker/middlewares.py
async def after_consume(self, err: Optional[Exception]) -> None:\n    \"\"\"A function to handle the result of consuming a resource asynchronously.\n\n    Args:\n        err : Optional exception that occurred during consumption\n\n    Raises:\n        err : If an exception occurred during consumption\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.after_processed","title":"after_processed async","text":"
after_processed(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> Optional[bool]\n

Asynchronously called after processing.

PARAMETER DESCRIPTION exc_type

Optional exception type

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

Optional exception value

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

Optional traceback

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION Optional[bool]

Optional boolean value indicating whether the processing was successful or not.

Source code in faststream/broker/middlewares.py
async def after_processed(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> Optional[bool]:\n    \"\"\"Asynchronously called after processing.\n\n    Args:\n        exc_type: Optional exception type\n        exc_val: Optional exception value\n        exec_tb: Optional traceback\n\n    Returns:\n        Optional boolean value indicating whether the processing was successful or not.\n    \"\"\"\n    return False\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.after_publish","title":"after_publish async","text":"
after_publish(err: Optional[Exception]) -> None\n

Asynchronous function to handle the after publish event.

PARAMETER DESCRIPTION err

Optional exception that occurred during the publish

TYPE: Optional[Exception]

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION Exception

If an error occurred during the publish

Source code in faststream/broker/middlewares.py
async def after_publish(self, err: Optional[Exception]) -> None:\n    \"\"\"Asynchronous function to handle the after publish event.\n\n    Args:\n        err: Optional exception that occurred during the publish\n\n    Returns:\n        None\n\n    Raises:\n        Exception: If an error occurred during the publish\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.consume_scope","title":"consume_scope async","text":"
consume_scope(\n    msg: DecodedMessage,\n) -> AsyncIterator[DecodedMessage]\n

Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.

PARAMETER DESCRIPTION msg

The decoded message to consume.

TYPE: DecodedMessage

YIELDS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RETURNS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RAISES DESCRIPTION Exception

If an error occurs while consuming the message.

AsyncIterator

An asynchronous iterator that yields decoded messages.

Note

This function is an async function.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def consume_scope(self, msg: DecodedMessage) -> AsyncIterator[DecodedMessage]:\n    \"\"\"Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.\n\n    Args:\n        msg: The decoded message to consume.\n\n    Yields:\n        An asynchronous iterator of decoded messages.\n\n    Returns:\n        An asynchronous iterator of decoded messages.\n\n    Raises:\n        Exception: If an error occurs while consuming the message.\n\n    AsyncIterator:\n        An asynchronous iterator that yields decoded messages.\n\n    Note:\n        This function is an async function.\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_consume(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_consume(err)\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.on_consume","title":"on_consume async","text":"
on_consume(msg: DecodedMessage) -> DecodedMessage\n

Asynchronously consumes a message.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: DecodedMessage

RETURNS DESCRIPTION DecodedMessage

The consumed message.

Source code in faststream/broker/middlewares.py
async def on_consume(self, msg: DecodedMessage) -> DecodedMessage:\n    \"\"\"Asynchronously consumes a message.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The consumed message.\n    \"\"\"\n    return msg\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.on_publish","title":"on_publish async","text":"
on_publish(msg: SendableMessage) -> SendableMessage\n

Asynchronously handle a publish event.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

RETURNS DESCRIPTION SendableMessage

The published message.

Source code in faststream/broker/middlewares.py
async def on_publish(self, msg: SendableMessage) -> SendableMessage:\n    \"\"\"Asynchronously handle a publish event.\n\n    Args:\n        msg: The message to be published.\n\n    Returns:\n        The published message.\n    \"\"\"\n    return msg\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.on_receive","title":"on_receive async","text":"
on_receive() -> None\n
Source code in faststream/broker/middlewares.py
async def on_receive(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.publish_scope","title":"publish_scope async","text":"
publish_scope(\n    msg: SendableMessage,\n) -> AsyncIterator[SendableMessage]\n

Publish a message and return an async iterator.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

YIELDS DESCRIPTION AsyncIterator[SendableMessage]

A sendable message.

RETURNS DESCRIPTION AsyncIterator[SendableMessage]

An async iterator of sendable messages.

RAISES DESCRIPTION Exception

If an error occurs during publishing.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def publish_scope(\n    self, msg: SendableMessage\n) -> AsyncIterator[SendableMessage]:\n    \"\"\"Publish a message and return an async iterator.\n\n    Args:\n        msg: The message to be published.\n\n    Yields:\n        A sendable message.\n\n    Returns:\n        An async iterator of sendable messages.\n\n    Raises:\n        Exception: If an error occurs during publishing.\n\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_publish(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_publish(err)\n
","boost":0.5},{"location":"api/faststream/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/Context/#faststream.Context","title":"faststream.Context","text":"
Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n    )\n
","boost":0.5},{"location":"api/faststream/Depends/","title":"Depends","text":"","boost":0.5},{"location":"api/faststream/Depends/#fast_depends.use.Depends","title":"fast_depends.use.Depends","text":"
Depends(\n    dependency: Callable[P, T],\n    *,\n    use_cache: bool = True,\n    cast: bool = True\n) -> Any\n
Source code in fast_depends/use.py
def Depends(\n    dependency: Callable[P, T],\n    *,\n    use_cache: bool = True,\n    cast: bool = True,\n) -> Any:\n    return model.Depends(\n        dependency=dependency,\n        use_cache=use_cache,\n        cast=cast,\n    )\n
","boost":0.5},{"location":"api/faststream/FastStream/","title":"FastStream","text":"","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream","title":"faststream.FastStream","text":"
FastStream(\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    lifespan: Optional[Lifespan] = None,\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[\n        Union[License, LicenseDict, AnyDict]\n    ] = None,\n    contact: Optional[\n        Union[Contact, ContactDict, AnyDict]\n    ] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[\n        Sequence[Union[Tag, TagDict, AnyDict]]\n    ] = None,\n    external_docs: Optional[\n        Union[ExternalDocs, ExternalDocsDict, AnyDict]\n    ] = None,\n)\n

Bases: ABCApp

A class representing a FastStream application.

METHOD DESCRIPTION __init__

initializes the FastStream application

on_startup

adds a hook to run before the broker is connected

on_shutdown

adds a hook to run before the broker is disconnected

after_startup

adds a hook to run after the broker is connected

after_shutdown

adds a hook to run after the broker is disconnected

run

runs the FastStream application

_init_async_cycle

initializes the async cycle

_start

starts the FastStream application

_stop

stops the FastStream application

_startup

runs the startup hooks

_shutdown

runs the shutdown hooks

__exit

exits the FastStream application

Asyncronous FastStream Application class

stores and run broker, control hooks

PARAMETER DESCRIPTION broker

async broker to run (may be None, then specify by set_broker)

TYPE: Optional[BrokerAsyncUsecase[Any, Any]] DEFAULT: None

logger

logger object to log startup/shutdown messages (None to disable)

TYPE: Optional[Logger] DEFAULT: logger

title

application title - for AsyncAPI docs

TYPE: str DEFAULT: 'FastStream'

version

application version - for AsyncAPI docs

TYPE: str DEFAULT: '0.1.0'

description

application description - for AsyncAPI docs

TYPE: str DEFAULT: ''

Source code in faststream/app.py
def __init__(\n    self,\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    lifespan: Optional[Lifespan] = None,\n    # AsyncAPI args,\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[Union[License, LicenseDict, AnyDict]] = None,\n    contact: Optional[Union[Contact, ContactDict, AnyDict]] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[Sequence[Union[Tag, TagDict, AnyDict]]] = None,\n    external_docs: Optional[Union[ExternalDocs, ExternalDocsDict, AnyDict]] = None,\n) -> None:\n    \"\"\"Asyncronous FastStream Application class\n\n    stores and run broker, control hooks\n\n    Args:\n        broker: async broker to run (may be `None`, then specify by `set_broker`)\n        logger: logger object to log startup/shutdown messages (`None` to disable)\n        title: application title - for AsyncAPI docs\n        version: application version - for AsyncAPI docs\n        description: application description - for AsyncAPI docs\n    \"\"\"\n    super().__init__(\n        broker=broker,\n        logger=logger,\n        title=title,\n        version=version,\n        description=description,\n        terms_of_service=terms_of_service,\n        license=license,\n        contact=contact,\n        identifier=identifier,\n        tags=tags,\n        external_docs=external_docs,\n    )\n\n    self._stop_event = None\n\n    self.lifespan_context = (\n        apply_types(\n            func=lifespan,\n            wrap_model=drop_response_type,\n        )\n        if lifespan is not None\n        else fake_context\n    )\n\n    set_exit(lambda *_: self.__exit())\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = tags\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.contact","title":"contact instance-attribute","text":"
contact = contact\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.context","title":"context instance-attribute","text":"
context = context\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.external_docs","title":"external_docs instance-attribute","text":"
external_docs = external_docs\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.identifier","title":"identifier instance-attribute","text":"
identifier = identifier\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.license","title":"license instance-attribute","text":"
license = license\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context = (\n    apply_types(\n        func=lifespan, wrap_model=drop_response_type\n    )\n    if lifespan is not None\n    else fake_context\n)\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = terms_of_service\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.title","title":"title instance-attribute","text":"
title = title\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.version","title":"version instance-attribute","text":"
version = version\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.after_shutdown","title":"after_shutdown","text":"
after_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker disconnected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def after_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker disconnected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().after_shutdown(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.after_startup","title":"after_startup","text":"
after_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker connected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def after_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker connected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().after_startup(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.on_shutdown","title":"on_shutdown","text":"
on_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker disconnected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def on_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker disconnected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().on_shutdown(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.on_startup","title":"on_startup","text":"
on_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker connected

This hook also takes an extra CLI options as a kwargs

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def on_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker connected\n\n    This hook also takes an extra CLI options as a kwargs\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().on_startup(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.run","title":"run async","text":"
run(\n    log_level: int = logging.INFO,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n) -> None\n

Run FastStream Application

PARAMETER DESCRIPTION log_level

force application log level

TYPE: int DEFAULT: INFO

RETURNS DESCRIPTION None

Block an event loop until stopped

Source code in faststream/app.py
async def run(\n    self,\n    log_level: int = logging.INFO,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Run FastStream Application\n\n    Args:\n        log_level: force application log level\n\n    Returns:\n        Block an event loop until stopped\n    \"\"\"\n    assert self.broker, \"You should setup a broker\"  # nosec B101\n\n    self._init_async_cycle()\n    async with self.lifespan_context(**(run_extra_options or {})):\n        try:\n            async with anyio.create_task_group() as tg:\n                tg.start_soon(self._start, log_level, run_extra_options)\n                await self._stop(log_level)\n                tg.cancel_scope.cancel()\n        except ExceptionGroup as e:\n            for ex in e.exceptions:\n                raise ex from None\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.set_broker","title":"set_broker","text":"
set_broker(broker: BrokerAsyncUsecase[Any, Any]) -> None\n

Set already existed App object broker Usefull then you create/init broker in on_startup hook

Source code in faststream/app.py
def set_broker(self, broker: BrokerAsyncUsecase[Any, Any]) -> None:\n    \"\"\"Set already existed App object broker\n    Usefull then you create/init broker in `on_startup` hook\"\"\"\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/Header/","title":"Header","text":"","boost":0.5},{"location":"api/faststream/Header/#faststream.Header","title":"faststream.Header","text":"
Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.headers.\",\n    )\n
","boost":0.5},{"location":"api/faststream/Path/","title":"Path","text":"","boost":0.5},{"location":"api/faststream/Path/#faststream.Path","title":"faststream.Path","text":"
Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.path.\",\n    )\n
","boost":0.5},{"location":"api/faststream/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/TestApp/#faststream.TestApp","title":"faststream.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/TestApp/#faststream.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/apply_types/","title":"apply_types","text":"","boost":0.5},{"location":"api/faststream/apply_types/#fast_depends.use.inject","title":"fast_depends.use.inject","text":"
inject(\n    func: Optional[Callable[P, T]] = None,\n    *,\n    cast: bool = True,\n    extra_dependencies: Sequence[model.Depends] = (),\n    pydantic_config: Optional[ConfigDict] = None,\n    dependency_overrides_provider: Optional[\n        Any\n    ] = dependency_provider,\n    wrap_model: Callable[\n        [CallModel[P, T]], CallModel[P, T]\n    ] = lambda: x\n) -> Union[Callable[P, T], _InjectWrapper[P, T]]\n
Source code in fast_depends/use.py
def inject(\n    func: Optional[Callable[P, T]] = None,\n    *,\n    cast: bool = True,\n    extra_dependencies: Sequence[model.Depends] = (),\n    pydantic_config: Optional[ConfigDict] = None,\n    dependency_overrides_provider: Optional[Any] = dependency_provider,\n    wrap_model: Callable[[CallModel[P, T]], CallModel[P, T]] = lambda x: x,\n) -> Union[Callable[P, T], _InjectWrapper[P, T],]:\n    decorator = _wrap_inject(\n        dependency_overrides_provider=dependency_overrides_provider,\n        wrap_model=wrap_model,\n        extra_dependencies=extra_dependencies,\n        cast=cast,\n        pydantic_config=pydantic_config,\n    )\n\n    if func is None:\n        return decorator\n\n    else:\n        return decorator(func)\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/","title":"ABCApp","text":"","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp","title":"faststream.app.ABCApp","text":"
ABCApp(\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[\n        Union[License, LicenseDict, AnyDict]\n    ] = None,\n    contact: Optional[\n        Union[Contact, ContactDict, AnyDict]\n    ] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[\n        Sequence[Union[Tag, TagDict, AnyDict]]\n    ] = None,\n    external_docs: Optional[\n        Union[ExternalDocs, ExternalDocsDict, AnyDict]\n    ] = None,\n)\n

Bases: ABC

A class representing an ABC App.

METHOD DESCRIPTION set_broker

Set the broker object

on_startup

Add a hook to be run before the broker is connected

on_shutdown

Add a hook to be run before the broker is disconnected

after_startup

Add a hook to be run after the broker is connected

after_shutdown

Add a hook to be run after the broker is disconnected

_log

Log a message at a specified

Initialize an instance of the class.

PARAMETER DESCRIPTION broker

An optional instance of the BrokerAsyncUsecase class.

TYPE: Optional[BrokerAsyncUsecase[Any, Any]] DEFAULT: None

logger

An optional instance of the logging.Logger class.

TYPE: Optional[Logger] DEFAULT: logger

title

A string representing the title of the AsyncAPI.

TYPE: str DEFAULT: 'FastStream'

version

A string representing the version of the AsyncAPI.

TYPE: str DEFAULT: '0.1.0'

description

A string representing the description of the AsyncAPI.

TYPE: str DEFAULT: ''

terms_of_service

An optional URL representing the terms of service of the AsyncAPI.

TYPE: Optional[AnyHttpUrl] DEFAULT: None

license

An optional instance of the License class.

TYPE: Optional[Union[License, LicenseDict, AnyDict]] DEFAULT: None

contact

An optional instance of the Contact class.

TYPE: Optional[Union[Contact, ContactDict, AnyDict]] DEFAULT: None

identifier

An optional string representing the identifier of the AsyncAPI.

TYPE: Optional[str] DEFAULT: None

tags

An optional sequence of Tag instances.

TYPE: Optional[Sequence[Union[Tag, TagDict, AnyDict]]] DEFAULT: None

external_docs

An optional instance of the ExternalDocs class.

TYPE: Optional[Union[ExternalDocs, ExternalDocsDict, AnyDict]] DEFAULT: None

Source code in faststream/app.py
def __init__(\n    self,\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    # AsyncAPI information\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[Union[License, LicenseDict, AnyDict]] = None,\n    contact: Optional[Union[Contact, ContactDict, AnyDict]] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[Sequence[Union[Tag, TagDict, AnyDict]]] = None,\n    external_docs: Optional[Union[ExternalDocs, ExternalDocsDict, AnyDict]] = None,\n) -> None:\n    \"\"\"Initialize an instance of the class.\n\n    Args:\n        broker: An optional instance of the BrokerAsyncUsecase class.\n        logger: An optional instance of the logging.Logger class.\n        title: A string representing the title of the AsyncAPI.\n        version: A string representing the version of the AsyncAPI.\n        description: A string representing the description of the AsyncAPI.\n        terms_of_service: An optional URL representing the terms of service of the AsyncAPI.\n        license: An optional instance of the License class.\n        contact: An optional instance of the Contact class.\n        identifier: An optional string representing the identifier of the AsyncAPI.\n        tags: An optional sequence of Tag instances.\n        external_docs: An optional instance of the ExternalDocs class.\n    \"\"\"\n    self.broker = broker\n    self.logger = logger\n    self.context = context\n    context.set_global(\"app\", self)\n\n    self._on_startup_calling = []\n    self._after_startup_calling = []\n    self._on_shutdown_calling = []\n    self._after_shutdown_calling = []\n\n    # AsyncAPI information\n    self.title = title\n    self.version = version\n    self.description = description\n    self.terms_of_service = terms_of_service\n    self.license = license\n    self.contact = contact\n    self.identifier = identifier\n    self.asyncapi_tags = tags\n    self.external_docs = external_docs\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = tags\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.contact","title":"contact instance-attribute","text":"
contact = contact\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.context","title":"context instance-attribute","text":"
context = context\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.external_docs","title":"external_docs instance-attribute","text":"
external_docs = external_docs\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.identifier","title":"identifier instance-attribute","text":"
identifier = identifier\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.license","title":"license instance-attribute","text":"
license = license\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = terms_of_service\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.title","title":"title instance-attribute","text":"
title = title\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.version","title":"version instance-attribute","text":"
version = version\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.after_shutdown","title":"after_shutdown","text":"
after_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker disconnected

Source code in faststream/app.py
def after_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker disconnected\"\"\"\n    self._after_shutdown_calling.append(apply_types(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.after_startup","title":"after_startup","text":"
after_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker connected

Source code in faststream/app.py
def after_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker connected\"\"\"\n    self._after_startup_calling.append(apply_types(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.on_shutdown","title":"on_shutdown","text":"
on_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker disconnected

Source code in faststream/app.py
def on_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker disconnected\"\"\"\n    self._on_shutdown_calling.append(apply_types(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.on_startup","title":"on_startup","text":"
on_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker connected This hook also takes an extra CLI options as a kwargs

Source code in faststream/app.py
def on_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker connected\n    This hook also takes an extra CLI options as a kwargs\"\"\"\n    self._on_startup_calling.append(apply_types(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.set_broker","title":"set_broker","text":"
set_broker(broker: BrokerAsyncUsecase[Any, Any]) -> None\n

Set already existed App object broker Usefull then you create/init broker in on_startup hook

Source code in faststream/app.py
def set_broker(self, broker: BrokerAsyncUsecase[Any, Any]) -> None:\n    \"\"\"Set already existed App object broker\n    Usefull then you create/init broker in `on_startup` hook\"\"\"\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/app/FastStream/","title":"FastStream","text":"","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream","title":"faststream.app.FastStream","text":"
FastStream(\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    lifespan: Optional[Lifespan] = None,\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[\n        Union[License, LicenseDict, AnyDict]\n    ] = None,\n    contact: Optional[\n        Union[Contact, ContactDict, AnyDict]\n    ] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[\n        Sequence[Union[Tag, TagDict, AnyDict]]\n    ] = None,\n    external_docs: Optional[\n        Union[ExternalDocs, ExternalDocsDict, AnyDict]\n    ] = None,\n)\n

Bases: ABCApp

A class representing a FastStream application.

METHOD DESCRIPTION __init__

initializes the FastStream application

on_startup

adds a hook to run before the broker is connected

on_shutdown

adds a hook to run before the broker is disconnected

after_startup

adds a hook to run after the broker is connected

after_shutdown

adds a hook to run after the broker is disconnected

run

runs the FastStream application

_init_async_cycle

initializes the async cycle

_start

starts the FastStream application

_stop

stops the FastStream application

_startup

runs the startup hooks

_shutdown

runs the shutdown hooks

__exit

exits the FastStream application

Asyncronous FastStream Application class

stores and run broker, control hooks

PARAMETER DESCRIPTION broker

async broker to run (may be None, then specify by set_broker)

TYPE: Optional[BrokerAsyncUsecase[Any, Any]] DEFAULT: None

logger

logger object to log startup/shutdown messages (None to disable)

TYPE: Optional[Logger] DEFAULT: logger

title

application title - for AsyncAPI docs

TYPE: str DEFAULT: 'FastStream'

version

application version - for AsyncAPI docs

TYPE: str DEFAULT: '0.1.0'

description

application description - for AsyncAPI docs

TYPE: str DEFAULT: ''

Source code in faststream/app.py
def __init__(\n    self,\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    lifespan: Optional[Lifespan] = None,\n    # AsyncAPI args,\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[Union[License, LicenseDict, AnyDict]] = None,\n    contact: Optional[Union[Contact, ContactDict, AnyDict]] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[Sequence[Union[Tag, TagDict, AnyDict]]] = None,\n    external_docs: Optional[Union[ExternalDocs, ExternalDocsDict, AnyDict]] = None,\n) -> None:\n    \"\"\"Asyncronous FastStream Application class\n\n    stores and run broker, control hooks\n\n    Args:\n        broker: async broker to run (may be `None`, then specify by `set_broker`)\n        logger: logger object to log startup/shutdown messages (`None` to disable)\n        title: application title - for AsyncAPI docs\n        version: application version - for AsyncAPI docs\n        description: application description - for AsyncAPI docs\n    \"\"\"\n    super().__init__(\n        broker=broker,\n        logger=logger,\n        title=title,\n        version=version,\n        description=description,\n        terms_of_service=terms_of_service,\n        license=license,\n        contact=contact,\n        identifier=identifier,\n        tags=tags,\n        external_docs=external_docs,\n    )\n\n    self._stop_event = None\n\n    self.lifespan_context = (\n        apply_types(\n            func=lifespan,\n            wrap_model=drop_response_type,\n        )\n        if lifespan is not None\n        else fake_context\n    )\n\n    set_exit(lambda *_: self.__exit())\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = tags\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.contact","title":"contact instance-attribute","text":"
contact = contact\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.context","title":"context instance-attribute","text":"
context = context\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.external_docs","title":"external_docs instance-attribute","text":"
external_docs = external_docs\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.identifier","title":"identifier instance-attribute","text":"
identifier = identifier\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.license","title":"license instance-attribute","text":"
license = license\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context = (\n    apply_types(\n        func=lifespan, wrap_model=drop_response_type\n    )\n    if lifespan is not None\n    else fake_context\n)\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = terms_of_service\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.title","title":"title instance-attribute","text":"
title = title\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.version","title":"version instance-attribute","text":"
version = version\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.after_shutdown","title":"after_shutdown","text":"
after_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker disconnected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def after_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker disconnected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().after_shutdown(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.after_startup","title":"after_startup","text":"
after_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker connected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def after_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker connected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().after_startup(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.on_shutdown","title":"on_shutdown","text":"
on_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker disconnected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def on_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker disconnected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().on_shutdown(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.on_startup","title":"on_startup","text":"
on_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker connected

This hook also takes an extra CLI options as a kwargs

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def on_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker connected\n\n    This hook also takes an extra CLI options as a kwargs\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().on_startup(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.run","title":"run async","text":"
run(\n    log_level: int = logging.INFO,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n) -> None\n

Run FastStream Application

PARAMETER DESCRIPTION log_level

force application log level

TYPE: int DEFAULT: INFO

RETURNS DESCRIPTION None

Block an event loop until stopped

Source code in faststream/app.py
async def run(\n    self,\n    log_level: int = logging.INFO,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Run FastStream Application\n\n    Args:\n        log_level: force application log level\n\n    Returns:\n        Block an event loop until stopped\n    \"\"\"\n    assert self.broker, \"You should setup a broker\"  # nosec B101\n\n    self._init_async_cycle()\n    async with self.lifespan_context(**(run_extra_options or {})):\n        try:\n            async with anyio.create_task_group() as tg:\n                tg.start_soon(self._start, log_level, run_extra_options)\n                await self._stop(log_level)\n                tg.cancel_scope.cancel()\n        except ExceptionGroup as e:\n            for ex in e.exceptions:\n                raise ex from None\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.set_broker","title":"set_broker","text":"
set_broker(broker: BrokerAsyncUsecase[Any, Any]) -> None\n

Set already existed App object broker Usefull then you create/init broker in on_startup hook

Source code in faststream/app.py
def set_broker(self, broker: BrokerAsyncUsecase[Any, Any]) -> None:\n    \"\"\"Set already existed App object broker\n    Usefull then you create/init broker in `on_startup` hook\"\"\"\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/asyncapi/get_asyncapi_html/","title":"get_asyncapi_html","text":"","boost":0.5},{"location":"api/faststream/asyncapi/get_asyncapi_html/#faststream.asyncapi.get_asyncapi_html","title":"faststream.asyncapi.get_asyncapi_html","text":"
get_asyncapi_html(\n    schema: Schema,\n    sidebar: bool = True,\n    info: bool = True,\n    servers: bool = True,\n    operations: bool = True,\n    messages: bool = True,\n    schemas: bool = True,\n    errors: bool = True,\n    expand_message_examples: bool = True,\n    title: str = \"FastStream\",\n) -> str\n

Generate HTML for displaying an AsyncAPI document.

PARAMETER DESCRIPTION schema

The AsyncAPI schema object.

TYPE: Schema

sidebar

Whether to show the sidebar. Defaults to True.

TYPE: bool DEFAULT: True

info

Whether to show the info section. Defaults to True.

TYPE: bool DEFAULT: True

servers

Whether to show the servers section. Defaults to True.

TYPE: bool DEFAULT: True

operations

Whether to show the operations section. Defaults to True.

TYPE: bool DEFAULT: True

messages

Whether to show the messages section. Defaults to True.

TYPE: bool DEFAULT: True

schemas

Whether to show the schemas section. Defaults to True.

TYPE: bool DEFAULT: True

errors

Whether to show the errors section. Defaults to True.

TYPE: bool DEFAULT: True

expand_message_examples

Whether to expand message examples. Defaults to True.

TYPE: bool DEFAULT: True

title

The title of the HTML document. Defaults to \"FastStream\".

TYPE: str DEFAULT: 'FastStream'

RETURNS DESCRIPTION str

The generated HTML document.

TYPE: str

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/asyncapi/site.py
def get_asyncapi_html(\n    schema: \"Schema\",\n    sidebar: bool = True,\n    info: bool = True,\n    servers: bool = True,\n    operations: bool = True,\n    messages: bool = True,\n    schemas: bool = True,\n    errors: bool = True,\n    expand_message_examples: bool = True,\n    title: str = \"FastStream\",\n) -> str:\n    \"\"\"Generate HTML for displaying an AsyncAPI document.\n\n    Args:\n        schema (Schema): The AsyncAPI schema object.\n        sidebar (bool, optional): Whether to show the sidebar. Defaults to True.\n        info (bool, optional): Whether to show the info section. Defaults to True.\n        servers (bool, optional): Whether to show the servers section. Defaults to True.\n        operations (bool, optional): Whether to show the operations section. Defaults to True.\n        messages (bool, optional): Whether to show the messages section. Defaults to True.\n        schemas (bool, optional): Whether to show the schemas section. Defaults to True.\n        errors (bool, optional): Whether to show the errors section. Defaults to True.\n        expand_message_examples (bool, optional): Whether to expand message examples. Defaults to True.\n        title (str, optional): The title of the HTML document. Defaults to \"FastStream\".\n\n    Returns:\n        str: The generated HTML document.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    schema_json = schema.to_json()\n\n    config = {\n        \"schema\": schema_json,\n        \"config\": {\n            \"show\": {\n                \"sidebar\": sidebar,\n                \"info\": info,\n                \"servers\": servers,\n                \"operations\": operations,\n                \"messages\": messages,\n                \"schemas\": schemas,\n                \"errors\": errors,\n            },\n            \"expand\": {\n                \"messageExamples\": expand_message_examples,\n            },\n            \"sidebar\": {\n                \"showServers\": \"byDefault\",\n                \"showOperations\": \"byDefault\",\n            },\n        },\n    }\n\n    return (\n        \"\"\"\n    <!DOCTYPE html>\n    <html>\n        <head>\n    \"\"\"\n        f\"\"\"\n        <title>{title} AsyncAPI</title>\n    \"\"\"\n        \"\"\"\n        <link rel=\"icon\" href=\"https://www.asyncapi.com/favicon.ico\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"https://www.asyncapi.com/favicon-16x16.png\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"https://www.asyncapi.com/favicon-32x32.png\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"194x194\" href=\"https://www.asyncapi.com/favicon-194x194.png\">\n        <link rel=\"stylesheet\" href=\"https://unpkg.com/@asyncapi/react-component@1.0.0-next.46/styles/default.min.css\">\n        </head>\n\n        <style>\n        html {\n            font-family: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;\n            line-height: 1.5;\n        }\n        </style>\n\n        <body>\n        <div id=\"asyncapi\"></div>\n\n        <script src=\"https://unpkg.com/@asyncapi/react-component@1.0.0-next.47/browser/standalone/index.js\"></script>\n        <script>\n    \"\"\"\n        f\"\"\"\n            AsyncApiStandalone.render({json.dumps(config)}, document.getElementById('asyncapi'));\n    \"\"\"\n        \"\"\"\n        </script>\n        </body>\n    </html>\n    \"\"\"\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/base/AsyncAPIOperation/","title":"AsyncAPIOperation","text":"","boost":0.5},{"location":"api/faststream/asyncapi/base/AsyncAPIOperation/#faststream.asyncapi.base.AsyncAPIOperation","title":"faststream.asyncapi.base.AsyncAPIOperation dataclass","text":"

A class representing an asynchronous API operation.

METHOD DESCRIPTION schema

returns the schema of the API operation as a dictionary of channel names and channel objects

","boost":0.5},{"location":"api/faststream/asyncapi/base/AsyncAPIOperation/#faststream.asyncapi.base.AsyncAPIOperation.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/asyncapi/base/AsyncAPIOperation/#faststream.asyncapi.base.AsyncAPIOperation.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/asyncapi/base/AsyncAPIOperation/#faststream.asyncapi.base.AsyncAPIOperation.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_broker_channels/","title":"get_app_broker_channels","text":"","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_broker_channels/#faststream.asyncapi.generate.get_app_broker_channels","title":"faststream.asyncapi.generate.get_app_broker_channels","text":"
get_app_broker_channels(\n    app: Union[FastStream, StreamRouter[Any]]\n) -> Dict[str, Channel]\n

Get the broker channels for an application.

PARAMETER DESCRIPTION app

An instance of FastStream or StreamRouter.

TYPE: Union[FastStream, StreamRouter[Any]]

RETURNS DESCRIPTION Dict[str, Channel]

A dictionary of channel names and their corresponding Channel objects.

RAISES DESCRIPTION AssertionError

If the app does not have a broker.

Source code in faststream/asyncapi/generate.py
def get_app_broker_channels(\n    app: Union[FastStream, \"StreamRouter[Any]\"]\n) -> Dict[str, Channel]:\n    \"\"\"Get the broker channels for an application.\n\n    Args:\n        app: An instance of FastStream or StreamRouter.\n\n    Returns:\n        A dictionary of channel names and their corresponding Channel objects.\n\n    Raises:\n        AssertionError: If the app does not have a broker.\n\n    \"\"\"\n    channels = {}\n    assert app.broker  # nosec B101\n\n    for h in app.broker.handlers.values():\n        channels.update(h.schema())\n\n    for p in app.broker._publishers.values():\n        channels.update(p.schema())\n\n    return channels\n
","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_broker_server/","title":"get_app_broker_server","text":"","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_broker_server/#faststream.asyncapi.generate.get_app_broker_server","title":"faststream.asyncapi.generate.get_app_broker_server","text":"
get_app_broker_server(\n    app: Union[FastStream, StreamRouter[Any]]\n) -> Dict[str, Server]\n

Get the broker server for an application.

PARAMETER DESCRIPTION app

An instance of FastStream or StreamRouter representing the application.

TYPE: Union[FastStream, StreamRouter[Any]]

RETURNS DESCRIPTION Dict[str, Server]

A dictionary containing the broker servers. The keys are the server names and the values are instances of Server class.

RAISES DESCRIPTION AssertionError

If the broker attribute of the app is not present.

Note

This function is currently incomplete and the following fields in the broker_meta dictionary are not populated: \"security\", \"variables\", \"bindings\".

Source code in faststream/asyncapi/generate.py
def get_app_broker_server(\n    app: Union[FastStream, \"StreamRouter[Any]\"]\n) -> Dict[str, Server]:\n    \"\"\"Get the broker server for an application.\n\n    Args:\n        app: An instance of `FastStream` or `StreamRouter` representing the application.\n\n    Returns:\n        A dictionary containing the broker servers. The keys are the server names and the values are instances of `Server` class.\n\n    Raises:\n        AssertionError: If the `broker` attribute of the app is not present.\n\n    Note:\n        This function is currently incomplete and the following fields in the `broker_meta` dictionary are not populated: \"security\", \"variables\", \"bindings\".\n\n    \"\"\"\n    servers = {}\n\n    broker = app.broker\n    assert broker  # nosec B101\n\n    broker_meta: Dict[str, Any] = {\n        \"protocol\": broker.protocol,\n        \"protocolVersion\": broker.protocol_version,\n        \"description\": broker.description,\n        \"tags\": broker.tags,\n        # TODO\n        # \"variables\": \"\",\n        # \"bindings\": \"\",\n    }\n\n    if broker.security is not None:\n        broker_meta[\"security\"] = broker.security.get_requirement()\n\n    if isinstance(broker.url, str):\n        servers[\"development\"] = Server(\n            url=broker.url,\n            **broker_meta,\n        )\n\n    elif len(broker.url) == 1:\n        servers[\"development\"] = Server(\n            url=broker.url[0],\n            **broker_meta,\n        )\n\n    else:\n        for i, url in enumerate(broker.url, 1):\n            servers[f\"Server{i}\"] = Server(\n                url=url,\n                **broker_meta,\n            )\n\n    return servers\n
","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_schema/","title":"get_app_schema","text":"","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_schema/#faststream.asyncapi.generate.get_app_schema","title":"faststream.asyncapi.generate.get_app_schema","text":"
get_app_schema(\n    app: Union[FastStream, StreamRouter[Any]]\n) -> Schema\n

Get the application schema.

PARAMETER DESCRIPTION app

An instance of FastStream or StreamRouter.

TYPE: Union[FastStream, StreamRouter[Any]]

RETURNS DESCRIPTION Schema

The schema object.

Source code in faststream/asyncapi/generate.py
def get_app_schema(app: Union[FastStream, \"StreamRouter[Any]\"]) -> Schema:\n    \"\"\"Get the application schema.\n\n    Args:\n        app: An instance of FastStream or StreamRouter.\n\n    Returns:\n        The schema object.\n\n    \"\"\"\n    servers = get_app_broker_server(app)\n    channels = get_app_broker_channels(app)\n\n    messages: Dict[str, Message] = {}\n    payloads: Dict[str, Dict[str, Any]] = {}\n    for channel_name, ch in channels.items():\n        ch.servers = list(servers.keys())\n\n        if ch.subscribe is not None:\n            m = ch.subscribe.message\n\n            if isinstance(m, Message):  # pragma: no branch\n                ch.subscribe.message = _resolve_msg_payloads(\n                    m,\n                    channel_name,\n                    payloads,\n                    messages,\n                )\n\n        if ch.publish is not None:\n            m = ch.publish.message\n\n            if isinstance(m, Message):  # pragma: no branch\n                ch.publish.message = _resolve_msg_payloads(\n                    m,\n                    channel_name,\n                    payloads,\n                    messages,\n                )\n\n    broker = app.broker\n    if broker is None:  # pragma: no cover\n        raise RuntimeError()\n\n    schema = Schema(\n        info=Info(\n            title=app.title,\n            version=app.version,\n            description=app.description,\n            termsOfService=app.terms_of_service,\n            contact=app.contact,\n            license=app.license,\n        ),\n        defaultContentType=ContentTypes.json.value,\n        id=app.identifier,\n        tags=list(app.asyncapi_tags) if app.asyncapi_tags else None,\n        externalDocs=app.external_docs,\n        servers=servers,\n        channels=channels,\n        components=Components(\n            messages=messages,\n            schemas=payloads,\n            securitySchemes=None\n            if broker.security is None\n            else broker.security.get_schema(),\n        ),\n    )\n    return schema\n
","boost":0.5},{"location":"api/faststream/asyncapi/message/get_model_schema/","title":"get_model_schema","text":"","boost":0.5},{"location":"api/faststream/asyncapi/message/get_model_schema/#faststream.asyncapi.message.get_model_schema","title":"faststream.asyncapi.message.get_model_schema","text":"
get_model_schema(\n    call: Optional[Type[BaseModel]],\n    prefix: str = \"\",\n    exclude: Sequence[str] = (),\n) -> Optional[Dict[str, Any]]\n

Get the schema of a model.

PARAMETER DESCRIPTION call

The model class to get the schema for.

TYPE: Optional[Type[BaseModel]]

prefix

A prefix to add to the schema title.

TYPE: str DEFAULT: ''

exclude

A sequence of field names to exclude from the schema.

TYPE: Sequence[str] DEFAULT: ()

RETURNS DESCRIPTION Optional[Dict[str, Any]]

The schema of the model as a dictionary, or None if the model has no fields.

RAISES DESCRIPTION NotImplementedError

If the model is a silent animal.

Source code in faststream/asyncapi/message.py
def get_model_schema(\n    call: Optional[Type[BaseModel]],\n    prefix: str = \"\",\n    exclude: Sequence[str] = (),\n) -> Optional[Dict[str, Any]]:\n    \"\"\"Get the schema of a model.\n\n    Args:\n        call: The model class to get the schema for.\n        prefix: A prefix to add to the schema title.\n        exclude: A sequence of field names to exclude from the schema.\n\n    Returns:\n        The schema of the model as a dictionary, or None if the model has no fields.\n\n    Raises:\n        NotImplementedError: If the model is a silent animal.\n\n    \"\"\"\n    if call is None:\n        return None\n\n    params = {k: v for k, v in get_model_fields(call).items() if k not in exclude}\n    params_number = len(params)\n\n    if params_number == 0:\n        return None\n\n    model = None\n    use_original_model = False\n    if params_number == 1:\n        name, param = tuple(params.items())[0]\n\n        if (\n            param.annotation\n            and isclass(param.annotation)\n            and issubclass(param.annotation, BaseModel)  # NOTE: 3.7-3.10 compatibility\n        ):\n            model = param.annotation\n            use_original_model = True\n\n    if model is None:\n        model = call\n\n    body: Dict[str, Any] = model_schema(model)\n    body[\"properties\"] = body.get(\"properties\", {})\n    for i in exclude:\n        body[\"properties\"].pop(i, None)\n    if required := body.get(\"required\"):\n        body[\"required\"] = list(filter(lambda x: x not in exclude, required))\n\n    if params_number == 1 and not use_original_model:\n        param_body: Dict[str, Any] = body.get(\"properties\", {})\n        param_body = param_body[name]\n\n        if PYDANTIC_V2:\n            original_title = param.title\n        else:\n            original_title = param.field_info.title  # type: ignore[attr-defined]\n\n        if original_title:\n            use_original_model = True\n            param_body[\"title\"] = original_title\n        else:\n            param_body[\"title\"] = name\n\n        body = param_body\n\n    if not use_original_model:\n        body[\"title\"] = f\"{prefix}:Payload\"\n\n    return body\n
","boost":0.5},{"location":"api/faststream/asyncapi/message/get_response_schema/","title":"get_response_schema","text":"","boost":0.5},{"location":"api/faststream/asyncapi/message/get_response_schema/#faststream.asyncapi.message.get_response_schema","title":"faststream.asyncapi.message.get_response_schema","text":"
get_response_schema(\n    call: Optional[CallModel[Any, Any]], prefix: str = \"\"\n) -> Optional[Dict[str, Any]]\n

Get the response schema for a given call.

PARAMETER DESCRIPTION call

The call model.

TYPE: Optional[CallModel[Any, Any]]

prefix

A prefix to add to the schema keys.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION Optional[Dict[str, Any]]

The response schema as a dictionary.

Source code in faststream/asyncapi/message.py
def get_response_schema(\n    call: Optional[CallModel[Any, Any]],\n    prefix: str = \"\",\n) -> Optional[Dict[str, Any]]:\n    \"\"\"Get the response schema for a given call.\n\n    Args:\n        call: The call model.\n        prefix: A prefix to add to the schema keys.\n\n    Returns:\n        The response schema as a dictionary.\n\n    \"\"\"\n    return get_model_schema(\n        getattr(\n            call, \"response_model\", None\n        ),  # NOTE: FastAPI Dependant object compatibility\n        prefix=prefix,\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/message/parse_handler_params/","title":"parse_handler_params","text":"","boost":0.5},{"location":"api/faststream/asyncapi/message/parse_handler_params/#faststream.asyncapi.message.parse_handler_params","title":"faststream.asyncapi.message.parse_handler_params","text":"
parse_handler_params(\n    call: CallModel[Any, Any], prefix: str = \"\"\n) -> Dict[str, Any]\n

Parses the handler parameters.

PARAMETER DESCRIPTION call

The call model.

TYPE: CallModel[Any, Any]

prefix

The prefix for the model schema.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION Dict[str, Any]

A dictionary containing the parsed parameters.

Source code in faststream/asyncapi/message.py
def parse_handler_params(call: CallModel[Any, Any], prefix: str = \"\") -> Dict[str, Any]:\n    \"\"\"Parses the handler parameters.\n\n    Args:\n        call: The call model.\n        prefix: The prefix for the model schema.\n\n    Returns:\n        A dictionary containing the parsed parameters.\n\n    \"\"\"\n    body = get_model_schema(\n        call.model,\n        prefix=prefix,\n        exclude=tuple(call.custom_fields.keys()),\n    )\n\n    if body is None:\n        return {\"title\": \"EmptyPayload\", \"type\": \"null\"}\n\n    return body\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/","title":"Channel","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel","title":"faststream.asyncapi.schema.Channel","text":"

Bases: BaseModel

A class to represent a channel.

Configurations

model_config : configuration for the model (only applicable for Pydantic version 2) Config : configuration for the class (only applicable for Pydantic version 1)

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.parameters","title":"parameters class-attribute instance-attribute","text":"
parameters: Optional[Parameter] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.publish","title":"publish class-attribute instance-attribute","text":"
publish: Optional[Operation] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.servers","title":"servers class-attribute instance-attribute","text":"
servers: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.subscribe","title":"subscribe class-attribute instance-attribute","text":"
subscribe: Optional[Operation] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding","title":"faststream.asyncapi.schema.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/","title":"Components","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components","title":"faststream.asyncapi.schema.Components","text":"

Bases: BaseModel

A class to represent components in a system.

Note

The following attributes are not implemented yet: - servers - serverVariables - channels - securitySchemes - parameters - correlationIds - operationTraits - messageTraits - serverBindings - channelBindings - operationBindings - messageBindings

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.messages","title":"messages class-attribute instance-attribute","text":"
messages: Optional[Dict[str, Message]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.schemas","title":"schemas class-attribute instance-attribute","text":"
schemas: Optional[Dict[str, Dict[str, Any]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.securitySchemes","title":"securitySchemes class-attribute instance-attribute","text":"
securitySchemes: Optional[Dict[str, Dict[str, Any]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/","title":"Contact","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact","title":"faststream.asyncapi.schema.Contact","text":"

Bases: BaseModel

A class to represent a contact.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.email","title":"email class-attribute instance-attribute","text":"
email: Optional[EmailStr] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.url","title":"url class-attribute instance-attribute","text":"
url: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ContactDict/","title":"ContactDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ContactDict/#faststream.asyncapi.schema.ContactDict","title":"faststream.asyncapi.schema.ContactDict","text":"

Bases: TypedDict

A class to represent a dictionary of contact information.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/ContactDict/#faststream.asyncapi.schema.ContactDict.email","title":"email instance-attribute","text":"
email: EmailStr\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ContactDict/#faststream.asyncapi.schema.ContactDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ContactDict/#faststream.asyncapi.schema.ContactDict.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/","title":"CorrelationId","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId","title":"faststream.asyncapi.schema.CorrelationId","text":"

Bases: BaseModel

A class to represent a correlation ID.

Configurations

extra : allows extra fields in the correlation ID model

","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId.location","title":"location instance-attribute","text":"
location: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/","title":"ExternalDocs","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs","title":"faststream.asyncapi.schema.ExternalDocs","text":"

Bases: BaseModel

A class to represent external documentation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocsDict/","title":"ExternalDocsDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocsDict/#faststream.asyncapi.schema.ExternalDocsDict","title":"faststream.asyncapi.schema.ExternalDocsDict","text":"

Bases: TypedDict

A dictionary type for representing external documentation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocsDict/#faststream.asyncapi.schema.ExternalDocsDict.description","title":"description instance-attribute","text":"
description: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocsDict/#faststream.asyncapi.schema.ExternalDocsDict.url","title":"url instance-attribute","text":"
url: Required[AnyHttpUrl]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/","title":"Info","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info","title":"faststream.asyncapi.schema.Info","text":"

Bases: BaseModel

A class to represent information.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.contact","title":"contact class-attribute instance-attribute","text":"
contact: Optional[\n    Union[Contact, ContactDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.description","title":"description class-attribute instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.license","title":"license class-attribute instance-attribute","text":"
license: Optional[\n    Union[License, LicenseDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.termsOfService","title":"termsOfService class-attribute instance-attribute","text":"
termsOfService: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.title","title":"title instance-attribute","text":"
title: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.version","title":"version class-attribute instance-attribute","text":"
version: str = '1.0.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/","title":"License","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License","title":"faststream.asyncapi.schema.License","text":"

Bases: BaseModel

A class to represent a license.

Config

extra : allow additional attributes in the model (PYDANTIC_V2)

","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License.url","title":"url class-attribute instance-attribute","text":"
url: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/LicenseDict/","title":"LicenseDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/LicenseDict/#faststream.asyncapi.schema.LicenseDict","title":"faststream.asyncapi.schema.LicenseDict","text":"

Bases: TypedDict

A dictionary-like class to represent a license.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/LicenseDict/#faststream.asyncapi.schema.LicenseDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/LicenseDict/#faststream.asyncapi.schema.LicenseDict.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/","title":"Message","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message","title":"faststream.asyncapi.schema.Message","text":"

Bases: BaseModel

A class to represent a message.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.contentType","title":"contentType class-attribute instance-attribute","text":"
contentType: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.correlationId","title":"correlationId class-attribute instance-attribute","text":"
correlationId: Optional[CorrelationId] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.messageId","title":"messageId class-attribute instance-attribute","text":"
messageId: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.payload","title":"payload instance-attribute","text":"
payload: Dict[str, Any]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.summary","title":"summary class-attribute instance-attribute","text":"
summary: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[List[Union[Tag, Dict[str, Any]]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/","title":"Operation","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation","title":"faststream.asyncapi.schema.Operation","text":"

Bases: BaseModel

A class to represent an operation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.message","title":"message instance-attribute","text":"
message: Union[Message, Reference]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.operationId","title":"operationId class-attribute instance-attribute","text":"
operationId: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.security","title":"security class-attribute instance-attribute","text":"
security: Optional[Dict[str, List[str]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.summary","title":"summary class-attribute instance-attribute","text":"
summary: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding","title":"faststream.asyncapi.schema.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Reference/","title":"Reference","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Reference/#faststream.asyncapi.schema.Reference","title":"faststream.asyncapi.schema.Reference","text":"

Bases: BaseModel

A class to represent a reference.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Reference/#faststream.asyncapi.schema.Reference.ref","title":"ref class-attribute instance-attribute","text":"
ref: str = Field(..., alias='$ref')\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/","title":"Schema","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema","title":"faststream.asyncapi.schema.Schema","text":"

Bases: BaseModel

A class to represent a schema.

METHOD DESCRIPTION to_jsonable

Convert the schema to a JSON-serializable object.

to_json

Convert the schema to a JSON string.

to_yaml

Convert the schema to a YAML string.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.asyncapi","title":"asyncapi class-attribute instance-attribute","text":"
asyncapi: str = ASYNC_API_VERSION\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.channels","title":"channels instance-attribute","text":"
channels: Dict[str, Channel]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.components","title":"components class-attribute instance-attribute","text":"
components: Optional[Components] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.defaultContentType","title":"defaultContentType class-attribute instance-attribute","text":"
defaultContentType: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.id","title":"id class-attribute instance-attribute","text":"
id: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.info","title":"info instance-attribute","text":"
info: Info\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.servers","title":"servers class-attribute instance-attribute","text":"
servers: Optional[Dict[str, Server]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.to_json","title":"to_json","text":"
to_json() -> str\n
Source code in faststream/asyncapi/schema/main.py
def to_json(self) -> str:\n    return model_to_json(\n        self,\n        by_alias=True,\n        exclude_none=True,\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.to_jsonable","title":"to_jsonable","text":"
to_jsonable() -> Any\n
Source code in faststream/asyncapi/schema/main.py
def to_jsonable(self) -> Any:\n    return model_to_jsonable(\n        self,\n        by_alias=True,\n        exclude_none=True,\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.to_yaml","title":"to_yaml","text":"
to_yaml() -> str\n
Source code in faststream/asyncapi/schema/main.py
def to_yaml(self) -> str:\n    from io import StringIO\n\n    import yaml\n\n    io = StringIO(initial_value=\"\", newline=\"\\n\")\n    yaml.dump(self.to_jsonable(), io, sort_keys=False)\n    return io.getvalue()\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/","title":"SecuritySchemaComponent","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent","title":"faststream.asyncapi.schema.SecuritySchemaComponent","text":"

Bases: BaseModel

A class to represent a security schema component.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.bearerFormat","title":"bearerFormat class-attribute instance-attribute","text":"
bearerFormat: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.flows","title":"flows class-attribute instance-attribute","text":"
flows: Optional[OauthFlows] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.in_","title":"in_ class-attribute instance-attribute","text":"
in_: Optional[str] = Field(default=None, alias='in')\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.openIdConnectUrl","title":"openIdConnectUrl class-attribute instance-attribute","text":"
openIdConnectUrl: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.schema_","title":"schema_ class-attribute instance-attribute","text":"
schema_: Optional[str] = Field(default=None, alias=\"schema\")\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.type","title":"type instance-attribute","text":"
type: Literal[\n    \"userPassword\",\n    \"apikey\",\n    \"X509\",\n    \"symmetricEncryption\",\n    \"asymmetricEncryption\",\n    \"httpApiKey\",\n    \"http\",\n    \"oauth2\",\n    \"openIdConnect\",\n    \"plain\",\n    \"scramSha256\",\n    \"scramSha512\",\n    \"gssapi\",\n]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/","title":"Server","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server","title":"faststream.asyncapi.schema.Server","text":"

Bases: BaseModel

A class to represent a server.

Note

The attributes description, protocolVersion, tags, security, variables, and bindings are all optional.

Configurations

If PYDANTIC_V2 is True, the model configuration is set to allow extra attributes. Otherwise, the Config class is defined with the extra attribute set to \"allow\".

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[Union[ServerBinding, Reference]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.protocol","title":"protocol instance-attribute","text":"
protocol: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.protocolVersion","title":"protocolVersion class-attribute instance-attribute","text":"
protocolVersion: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.security","title":"security class-attribute instance-attribute","text":"
security: Optional[SecurityRequirement] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.variables","title":"variables class-attribute instance-attribute","text":"
variables: Optional[\n    Dict[str, Union[ServerVariable, Reference]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding","title":"faststream.asyncapi.schema.ServerBinding","text":"

Bases: BaseModel

A class to represent server bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/","title":"Tag","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag","title":"faststream.asyncapi.schema.Tag","text":"

Bases: BaseModel

A class to represent a tag.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/TagDict/","title":"TagDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/TagDict/#faststream.asyncapi.schema.TagDict","title":"faststream.asyncapi.schema.TagDict","text":"

Bases: TypedDict

A dictionary-like class for storing tags.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/TagDict/#faststream.asyncapi.schema.TagDict.description","title":"description instance-attribute","text":"
description: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/TagDict/#faststream.asyncapi.schema.TagDict.externalDocs","title":"externalDocs instance-attribute","text":"
externalDocs: Union[ExternalDocs, ExternalDocsDict]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/TagDict/#faststream.asyncapi.schema.TagDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding","title":"faststream.asyncapi.schema.bindings.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding","title":"faststream.asyncapi.schema.bindings.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding","title":"faststream.asyncapi.schema.bindings.ServerBinding","text":"

Bases: BaseModel

A class to represent server bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/#faststream.asyncapi.schema.bindings.amqp.ChannelBinding","title":"faststream.asyncapi.schema.bindings.amqp.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/#faststream.asyncapi.schema.bindings.amqp.ChannelBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.2.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/#faststream.asyncapi.schema.bindings.amqp.ChannelBinding.exchange","title":"exchange class-attribute instance-attribute","text":"
exchange: Optional[Exchange] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/#faststream.asyncapi.schema.bindings.amqp.ChannelBinding.is_","title":"is_ class-attribute instance-attribute","text":"
is_: Literal[\"queue\", \"routingKey\"] = Field(..., alias=\"is\")\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/#faststream.asyncapi.schema.bindings.amqp.ChannelBinding.queue","title":"queue class-attribute instance-attribute","text":"
queue: Optional[Queue] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/","title":"Exchange","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange","title":"faststream.asyncapi.schema.bindings.amqp.Exchange","text":"

Bases: BaseModel

A class to represent an exchange.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange.autoDelete","title":"autoDelete class-attribute instance-attribute","text":"
autoDelete: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange.durable","title":"durable class-attribute instance-attribute","text":"
durable: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange.type","title":"type instance-attribute","text":"
type: Literal[\n    \"default\", \"direct\", \"topic\", \"fanout\", \"headers\"\n]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange.vhost","title":"vhost class-attribute instance-attribute","text":"
vhost: str = '/'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding","title":"faststream.asyncapi.schema.bindings.amqp.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.ack","title":"ack class-attribute instance-attribute","text":"
ack: bool = True\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.2.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.cc","title":"cc class-attribute instance-attribute","text":"
cc: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.deliveryMode","title":"deliveryMode class-attribute instance-attribute","text":"
deliveryMode: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.priority","title":"priority class-attribute instance-attribute","text":"
priority: Optional[PositiveInt] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.replyTo","title":"replyTo class-attribute instance-attribute","text":"
replyTo: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/","title":"Queue","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue","title":"faststream.asyncapi.schema.bindings.amqp.Queue","text":"

Bases: BaseModel

A class to represent a queue.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue.autoDelete","title":"autoDelete instance-attribute","text":"
autoDelete: bool\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue.durable","title":"durable instance-attribute","text":"
durable: bool\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue.exclusive","title":"exclusive instance-attribute","text":"
exclusive: bool\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue.vhost","title":"vhost class-attribute instance-attribute","text":"
vhost: str = '/'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ServerBinding/#faststream.asyncapi.schema.bindings.amqp.ServerBinding","title":"faststream.asyncapi.schema.bindings.amqp.ServerBinding","text":"

Bases: BaseModel

A class to represent a server binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ServerBinding/#faststream.asyncapi.schema.bindings.amqp.ServerBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.2.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/#faststream.asyncapi.schema.bindings.kafka.ChannelBinding","title":"faststream.asyncapi.schema.bindings.kafka.ChannelBinding","text":"

Bases: BaseModel

A class to represent a channel binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/#faststream.asyncapi.schema.bindings.kafka.ChannelBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.4.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/#faststream.asyncapi.schema.bindings.kafka.ChannelBinding.partitions","title":"partitions class-attribute instance-attribute","text":"
partitions: Optional[PositiveInt] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/#faststream.asyncapi.schema.bindings.kafka.ChannelBinding.replicas","title":"replicas class-attribute instance-attribute","text":"
replicas: Optional[PositiveInt] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/#faststream.asyncapi.schema.bindings.kafka.ChannelBinding.topic","title":"topic class-attribute instance-attribute","text":"
topic: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/#faststream.asyncapi.schema.bindings.kafka.OperationBinding","title":"faststream.asyncapi.schema.bindings.kafka.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/#faststream.asyncapi.schema.bindings.kafka.OperationBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.4.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/#faststream.asyncapi.schema.bindings.kafka.OperationBinding.clientId","title":"clientId class-attribute instance-attribute","text":"
clientId: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/#faststream.asyncapi.schema.bindings.kafka.OperationBinding.groupId","title":"groupId class-attribute instance-attribute","text":"
groupId: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/#faststream.asyncapi.schema.bindings.kafka.OperationBinding.replyTo","title":"replyTo class-attribute instance-attribute","text":"
replyTo: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ServerBinding/#faststream.asyncapi.schema.bindings.kafka.ServerBinding","title":"faststream.asyncapi.schema.bindings.kafka.ServerBinding","text":"

Bases: BaseModel

A class to represent a server binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ServerBinding/#faststream.asyncapi.schema.bindings.kafka.ServerBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.4.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding","title":"faststream.asyncapi.schema.bindings.main.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding","title":"faststream.asyncapi.schema.bindings.main.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding","title":"faststream.asyncapi.schema.bindings.main.ServerBinding","text":"

Bases: BaseModel

A class to represent server bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ChannelBinding/#faststream.asyncapi.schema.bindings.nats.ChannelBinding","title":"faststream.asyncapi.schema.bindings.nats.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ChannelBinding/#faststream.asyncapi.schema.bindings.nats.ChannelBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ChannelBinding/#faststream.asyncapi.schema.bindings.nats.ChannelBinding.queue","title":"queue class-attribute instance-attribute","text":"
queue: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ChannelBinding/#faststream.asyncapi.schema.bindings.nats.ChannelBinding.subject","title":"subject instance-attribute","text":"
subject: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/OperationBinding/#faststream.asyncapi.schema.bindings.nats.OperationBinding","title":"faststream.asyncapi.schema.bindings.nats.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/OperationBinding/#faststream.asyncapi.schema.bindings.nats.OperationBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/OperationBinding/#faststream.asyncapi.schema.bindings.nats.OperationBinding.replyTo","title":"replyTo class-attribute instance-attribute","text":"
replyTo: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ServerBinding/#faststream.asyncapi.schema.bindings.nats.ServerBinding","title":"faststream.asyncapi.schema.bindings.nats.ServerBinding","text":"

Bases: BaseModel

A class to represent a server binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ServerBinding/#faststream.asyncapi.schema.bindings.nats.ServerBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding","title":"faststream.asyncapi.schema.bindings.redis.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding.channel","title":"channel instance-attribute","text":"
channel: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding.consumer_name","title":"consumer_name class-attribute instance-attribute","text":"
consumer_name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding.group_name","title":"group_name class-attribute instance-attribute","text":"
group_name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding.method","title":"method class-attribute instance-attribute","text":"
method: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/OperationBinding/#faststream.asyncapi.schema.bindings.redis.OperationBinding","title":"faststream.asyncapi.schema.bindings.redis.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/OperationBinding/#faststream.asyncapi.schema.bindings.redis.OperationBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/OperationBinding/#faststream.asyncapi.schema.bindings.redis.OperationBinding.replyTo","title":"replyTo class-attribute instance-attribute","text":"
replyTo: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ServerBinding/#faststream.asyncapi.schema.bindings.redis.ServerBinding","title":"faststream.asyncapi.schema.bindings.redis.ServerBinding","text":"

Bases: BaseModel

A class to represent a server binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ServerBinding/#faststream.asyncapi.schema.bindings.redis.ServerBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ChannelBinding/#faststream.asyncapi.schema.bindings.sqs.ChannelBinding","title":"faststream.asyncapi.schema.bindings.sqs.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ChannelBinding/#faststream.asyncapi.schema.bindings.sqs.ChannelBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ChannelBinding/#faststream.asyncapi.schema.bindings.sqs.ChannelBinding.queue","title":"queue instance-attribute","text":"
queue: Dict[str, Any]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/OperationBinding/#faststream.asyncapi.schema.bindings.sqs.OperationBinding","title":"faststream.asyncapi.schema.bindings.sqs.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/OperationBinding/#faststream.asyncapi.schema.bindings.sqs.OperationBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/OperationBinding/#faststream.asyncapi.schema.bindings.sqs.OperationBinding.replyTo","title":"replyTo class-attribute instance-attribute","text":"
replyTo: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ServerBinding/#faststream.asyncapi.schema.bindings.sqs.ServerBinding","title":"faststream.asyncapi.schema.bindings.sqs.ServerBinding","text":"

Bases: BaseModel

A class to represent a server binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ServerBinding/#faststream.asyncapi.schema.bindings.sqs.ServerBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/","title":"Channel","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel","title":"faststream.asyncapi.schema.channels.Channel","text":"

Bases: BaseModel

A class to represent a channel.

Configurations

model_config : configuration for the model (only applicable for Pydantic version 2) Config : configuration for the class (only applicable for Pydantic version 1)

","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.parameters","title":"parameters class-attribute instance-attribute","text":"
parameters: Optional[Parameter] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.publish","title":"publish class-attribute instance-attribute","text":"
publish: Optional[Operation] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.servers","title":"servers class-attribute instance-attribute","text":"
servers: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.subscribe","title":"subscribe class-attribute instance-attribute","text":"
subscribe: Optional[Operation] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/","title":"Contact","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact","title":"faststream.asyncapi.schema.info.Contact","text":"

Bases: BaseModel

A class to represent a contact.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.email","title":"email class-attribute instance-attribute","text":"
email: Optional[EmailStr] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.url","title":"url class-attribute instance-attribute","text":"
url: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/ContactDict/","title":"ContactDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/ContactDict/#faststream.asyncapi.schema.info.ContactDict","title":"faststream.asyncapi.schema.info.ContactDict","text":"

Bases: TypedDict

A class to represent a dictionary of contact information.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/ContactDict/#faststream.asyncapi.schema.info.ContactDict.email","title":"email instance-attribute","text":"
email: EmailStr\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/ContactDict/#faststream.asyncapi.schema.info.ContactDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/ContactDict/#faststream.asyncapi.schema.info.ContactDict.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/EmailStr/","title":"EmailStr","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/EmailStr/#faststream.asyncapi.schema.info.EmailStr","title":"faststream.asyncapi.schema.info.EmailStr","text":"

Bases: str

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/EmailStr/#faststream.asyncapi.schema.info.EmailStr.validate","title":"validate classmethod","text":"
validate(v: Any) -> str\n
Source code in faststream/asyncapi/schema/info.py
@classmethod\ndef validate(cls, v: Any) -> str:\n    logger.warning(\n        \"email-validator bot installed, email fields will be treated as str.\\n\"\n        \"To install, run: pip install email-validator\"\n    )\n    return str(v)\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/","title":"Info","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info","title":"faststream.asyncapi.schema.info.Info","text":"

Bases: BaseModel

A class to represent information.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.contact","title":"contact class-attribute instance-attribute","text":"
contact: Optional[\n    Union[Contact, ContactDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.description","title":"description class-attribute instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.license","title":"license class-attribute instance-attribute","text":"
license: Optional[\n    Union[License, LicenseDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.termsOfService","title":"termsOfService class-attribute instance-attribute","text":"
termsOfService: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.title","title":"title instance-attribute","text":"
title: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.version","title":"version class-attribute instance-attribute","text":"
version: str = '1.0.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/","title":"License","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License","title":"faststream.asyncapi.schema.info.License","text":"

Bases: BaseModel

A class to represent a license.

Config

extra : allow additional attributes in the model (PYDANTIC_V2)

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License.url","title":"url class-attribute instance-attribute","text":"
url: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/LicenseDict/","title":"LicenseDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/LicenseDict/#faststream.asyncapi.schema.info.LicenseDict","title":"faststream.asyncapi.schema.info.LicenseDict","text":"

Bases: TypedDict

A dictionary-like class to represent a license.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/LicenseDict/#faststream.asyncapi.schema.info.LicenseDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/LicenseDict/#faststream.asyncapi.schema.info.LicenseDict.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/","title":"Components","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components","title":"faststream.asyncapi.schema.main.Components","text":"

Bases: BaseModel

A class to represent components in a system.

Note

The following attributes are not implemented yet: - servers - serverVariables - channels - securitySchemes - parameters - correlationIds - operationTraits - messageTraits - serverBindings - channelBindings - operationBindings - messageBindings

","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.messages","title":"messages class-attribute instance-attribute","text":"
messages: Optional[Dict[str, Message]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.schemas","title":"schemas class-attribute instance-attribute","text":"
schemas: Optional[Dict[str, Dict[str, Any]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.securitySchemes","title":"securitySchemes class-attribute instance-attribute","text":"
securitySchemes: Optional[Dict[str, Dict[str, Any]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/","title":"Schema","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema","title":"faststream.asyncapi.schema.main.Schema","text":"

Bases: BaseModel

A class to represent a schema.

METHOD DESCRIPTION to_jsonable

Convert the schema to a JSON-serializable object.

to_json

Convert the schema to a JSON string.

to_yaml

Convert the schema to a YAML string.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.asyncapi","title":"asyncapi class-attribute instance-attribute","text":"
asyncapi: str = ASYNC_API_VERSION\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.channels","title":"channels instance-attribute","text":"
channels: Dict[str, Channel]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.components","title":"components class-attribute instance-attribute","text":"
components: Optional[Components] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.defaultContentType","title":"defaultContentType class-attribute instance-attribute","text":"
defaultContentType: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.id","title":"id class-attribute instance-attribute","text":"
id: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.info","title":"info instance-attribute","text":"
info: Info\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.servers","title":"servers class-attribute instance-attribute","text":"
servers: Optional[Dict[str, Server]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.to_json","title":"to_json","text":"
to_json() -> str\n
Source code in faststream/asyncapi/schema/main.py
def to_json(self) -> str:\n    return model_to_json(\n        self,\n        by_alias=True,\n        exclude_none=True,\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.to_jsonable","title":"to_jsonable","text":"
to_jsonable() -> Any\n
Source code in faststream/asyncapi/schema/main.py
def to_jsonable(self) -> Any:\n    return model_to_jsonable(\n        self,\n        by_alias=True,\n        exclude_none=True,\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.to_yaml","title":"to_yaml","text":"
to_yaml() -> str\n
Source code in faststream/asyncapi/schema/main.py
def to_yaml(self) -> str:\n    from io import StringIO\n\n    import yaml\n\n    io = StringIO(initial_value=\"\", newline=\"\\n\")\n    yaml.dump(self.to_jsonable(), io, sort_keys=False)\n    return io.getvalue()\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/","title":"CorrelationId","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId","title":"faststream.asyncapi.schema.message.CorrelationId","text":"

Bases: BaseModel

A class to represent a correlation ID.

Configurations

extra : allows extra fields in the correlation ID model

","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId.location","title":"location instance-attribute","text":"
location: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/","title":"Message","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message","title":"faststream.asyncapi.schema.message.Message","text":"

Bases: BaseModel

A class to represent a message.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.contentType","title":"contentType class-attribute instance-attribute","text":"
contentType: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.correlationId","title":"correlationId class-attribute instance-attribute","text":"
correlationId: Optional[CorrelationId] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.messageId","title":"messageId class-attribute instance-attribute","text":"
messageId: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.payload","title":"payload instance-attribute","text":"
payload: Dict[str, Any]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.summary","title":"summary class-attribute instance-attribute","text":"
summary: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[List[Union[Tag, Dict[str, Any]]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/","title":"Operation","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation","title":"faststream.asyncapi.schema.operations.Operation","text":"

Bases: BaseModel

A class to represent an operation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.message","title":"message instance-attribute","text":"
message: Union[Message, Reference]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.operationId","title":"operationId class-attribute instance-attribute","text":"
operationId: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.security","title":"security class-attribute instance-attribute","text":"
security: Optional[Dict[str, List[str]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.summary","title":"summary class-attribute instance-attribute","text":"
summary: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/","title":"OauthFlowObj","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj","title":"faststream.asyncapi.schema.security.OauthFlowObj","text":"

Bases: BaseModel

A class to represent an OAuth flow object.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.authorizationUrl","title":"authorizationUrl class-attribute instance-attribute","text":"
authorizationUrl: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.refreshUrl","title":"refreshUrl class-attribute instance-attribute","text":"
refreshUrl: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.scopes","title":"scopes instance-attribute","text":"
scopes: Dict[str, str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.tokenUrl","title":"tokenUrl class-attribute instance-attribute","text":"
tokenUrl: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/","title":"OauthFlows","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows","title":"faststream.asyncapi.schema.security.OauthFlows","text":"

Bases: BaseModel

A class to represent OAuth flows.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.authorizationCode","title":"authorizationCode class-attribute instance-attribute","text":"
authorizationCode: Optional[OauthFlowObj] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.clientCredentials","title":"clientCredentials class-attribute instance-attribute","text":"
clientCredentials: Optional[OauthFlowObj] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.implicit","title":"implicit class-attribute instance-attribute","text":"
implicit: Optional[OauthFlowObj] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.password","title":"password class-attribute instance-attribute","text":"
password: Optional[OauthFlowObj] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/","title":"SecuritySchemaComponent","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent","title":"faststream.asyncapi.schema.security.SecuritySchemaComponent","text":"

Bases: BaseModel

A class to represent a security schema component.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.bearerFormat","title":"bearerFormat class-attribute instance-attribute","text":"
bearerFormat: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.flows","title":"flows class-attribute instance-attribute","text":"
flows: Optional[OauthFlows] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.in_","title":"in_ class-attribute instance-attribute","text":"
in_: Optional[str] = Field(default=None, alias='in')\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.openIdConnectUrl","title":"openIdConnectUrl class-attribute instance-attribute","text":"
openIdConnectUrl: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.schema_","title":"schema_ class-attribute instance-attribute","text":"
schema_: Optional[str] = Field(default=None, alias=\"schema\")\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.type","title":"type instance-attribute","text":"
type: Literal[\n    \"userPassword\",\n    \"apikey\",\n    \"X509\",\n    \"symmetricEncryption\",\n    \"asymmetricEncryption\",\n    \"httpApiKey\",\n    \"http\",\n    \"oauth2\",\n    \"openIdConnect\",\n    \"plain\",\n    \"scramSha256\",\n    \"scramSha512\",\n    \"gssapi\",\n]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/","title":"Server","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server","title":"faststream.asyncapi.schema.servers.Server","text":"

Bases: BaseModel

A class to represent a server.

Note

The attributes description, protocolVersion, tags, security, variables, and bindings are all optional.

Configurations

If PYDANTIC_V2 is True, the model configuration is set to allow extra attributes. Otherwise, the Config class is defined with the extra attribute set to \"allow\".

","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[Union[ServerBinding, Reference]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.protocol","title":"protocol instance-attribute","text":"
protocol: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.protocolVersion","title":"protocolVersion class-attribute instance-attribute","text":"
protocolVersion: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.security","title":"security class-attribute instance-attribute","text":"
security: Optional[SecurityRequirement] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.variables","title":"variables class-attribute instance-attribute","text":"
variables: Optional[\n    Dict[str, Union[ServerVariable, Reference]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/","title":"ServerVariable","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable","title":"faststream.asyncapi.schema.servers.ServerVariable","text":"

Bases: BaseModel

A class to represent a server variable.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.default","title":"default class-attribute instance-attribute","text":"
default: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.enum","title":"enum class-attribute instance-attribute","text":"
enum: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.examples","title":"examples class-attribute instance-attribute","text":"
examples: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/","title":"ExternalDocs","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs","title":"faststream.asyncapi.schema.utils.ExternalDocs","text":"

Bases: BaseModel

A class to represent external documentation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocsDict/","title":"ExternalDocsDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocsDict/#faststream.asyncapi.schema.utils.ExternalDocsDict","title":"faststream.asyncapi.schema.utils.ExternalDocsDict","text":"

Bases: TypedDict

A dictionary type for representing external documentation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocsDict/#faststream.asyncapi.schema.utils.ExternalDocsDict.description","title":"description instance-attribute","text":"
description: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocsDict/#faststream.asyncapi.schema.utils.ExternalDocsDict.url","title":"url instance-attribute","text":"
url: Required[AnyHttpUrl]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Parameter/","title":"Parameter","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Parameter/#faststream.asyncapi.schema.utils.Parameter","title":"faststream.asyncapi.schema.utils.Parameter","text":"

Bases: BaseModel

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Reference/","title":"Reference","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Reference/#faststream.asyncapi.schema.utils.Reference","title":"faststream.asyncapi.schema.utils.Reference","text":"

Bases: BaseModel

A class to represent a reference.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Reference/#faststream.asyncapi.schema.utils.Reference.ref","title":"ref class-attribute instance-attribute","text":"
ref: str = Field(..., alias='$ref')\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/","title":"Tag","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag","title":"faststream.asyncapi.schema.utils.Tag","text":"

Bases: BaseModel

A class to represent a tag.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/TagDict/","title":"TagDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/TagDict/#faststream.asyncapi.schema.utils.TagDict","title":"faststream.asyncapi.schema.utils.TagDict","text":"

Bases: TypedDict

A dictionary-like class for storing tags.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/TagDict/#faststream.asyncapi.schema.utils.TagDict.description","title":"description instance-attribute","text":"
description: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/TagDict/#faststream.asyncapi.schema.utils.TagDict.externalDocs","title":"externalDocs instance-attribute","text":"
externalDocs: Union[ExternalDocs, ExternalDocsDict]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/TagDict/#faststream.asyncapi.schema.utils.TagDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/site/get_asyncapi_html/","title":"get_asyncapi_html","text":"","boost":0.5},{"location":"api/faststream/asyncapi/site/get_asyncapi_html/#faststream.asyncapi.site.get_asyncapi_html","title":"faststream.asyncapi.site.get_asyncapi_html","text":"
get_asyncapi_html(\n    schema: Schema,\n    sidebar: bool = True,\n    info: bool = True,\n    servers: bool = True,\n    operations: bool = True,\n    messages: bool = True,\n    schemas: bool = True,\n    errors: bool = True,\n    expand_message_examples: bool = True,\n    title: str = \"FastStream\",\n) -> str\n

Generate HTML for displaying an AsyncAPI document.

PARAMETER DESCRIPTION schema

The AsyncAPI schema object.

TYPE: Schema

sidebar

Whether to show the sidebar. Defaults to True.

TYPE: bool DEFAULT: True

info

Whether to show the info section. Defaults to True.

TYPE: bool DEFAULT: True

servers

Whether to show the servers section. Defaults to True.

TYPE: bool DEFAULT: True

operations

Whether to show the operations section. Defaults to True.

TYPE: bool DEFAULT: True

messages

Whether to show the messages section. Defaults to True.

TYPE: bool DEFAULT: True

schemas

Whether to show the schemas section. Defaults to True.

TYPE: bool DEFAULT: True

errors

Whether to show the errors section. Defaults to True.

TYPE: bool DEFAULT: True

expand_message_examples

Whether to expand message examples. Defaults to True.

TYPE: bool DEFAULT: True

title

The title of the HTML document. Defaults to \"FastStream\".

TYPE: str DEFAULT: 'FastStream'

RETURNS DESCRIPTION str

The generated HTML document.

TYPE: str

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/asyncapi/site.py
def get_asyncapi_html(\n    schema: \"Schema\",\n    sidebar: bool = True,\n    info: bool = True,\n    servers: bool = True,\n    operations: bool = True,\n    messages: bool = True,\n    schemas: bool = True,\n    errors: bool = True,\n    expand_message_examples: bool = True,\n    title: str = \"FastStream\",\n) -> str:\n    \"\"\"Generate HTML for displaying an AsyncAPI document.\n\n    Args:\n        schema (Schema): The AsyncAPI schema object.\n        sidebar (bool, optional): Whether to show the sidebar. Defaults to True.\n        info (bool, optional): Whether to show the info section. Defaults to True.\n        servers (bool, optional): Whether to show the servers section. Defaults to True.\n        operations (bool, optional): Whether to show the operations section. Defaults to True.\n        messages (bool, optional): Whether to show the messages section. Defaults to True.\n        schemas (bool, optional): Whether to show the schemas section. Defaults to True.\n        errors (bool, optional): Whether to show the errors section. Defaults to True.\n        expand_message_examples (bool, optional): Whether to expand message examples. Defaults to True.\n        title (str, optional): The title of the HTML document. Defaults to \"FastStream\".\n\n    Returns:\n        str: The generated HTML document.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    schema_json = schema.to_json()\n\n    config = {\n        \"schema\": schema_json,\n        \"config\": {\n            \"show\": {\n                \"sidebar\": sidebar,\n                \"info\": info,\n                \"servers\": servers,\n                \"operations\": operations,\n                \"messages\": messages,\n                \"schemas\": schemas,\n                \"errors\": errors,\n            },\n            \"expand\": {\n                \"messageExamples\": expand_message_examples,\n            },\n            \"sidebar\": {\n                \"showServers\": \"byDefault\",\n                \"showOperations\": \"byDefault\",\n            },\n        },\n    }\n\n    return (\n        \"\"\"\n    <!DOCTYPE html>\n    <html>\n        <head>\n    \"\"\"\n        f\"\"\"\n        <title>{title} AsyncAPI</title>\n    \"\"\"\n        \"\"\"\n        <link rel=\"icon\" href=\"https://www.asyncapi.com/favicon.ico\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"https://www.asyncapi.com/favicon-16x16.png\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"https://www.asyncapi.com/favicon-32x32.png\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"194x194\" href=\"https://www.asyncapi.com/favicon-194x194.png\">\n        <link rel=\"stylesheet\" href=\"https://unpkg.com/@asyncapi/react-component@1.0.0-next.46/styles/default.min.css\">\n        </head>\n\n        <style>\n        html {\n            font-family: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;\n            line-height: 1.5;\n        }\n        </style>\n\n        <body>\n        <div id=\"asyncapi\"></div>\n\n        <script src=\"https://unpkg.com/@asyncapi/react-component@1.0.0-next.47/browser/standalone/index.js\"></script>\n        <script>\n    \"\"\"\n        f\"\"\"\n            AsyncApiStandalone.render({json.dumps(config)}, document.getElementById('asyncapi'));\n    \"\"\"\n        \"\"\"\n        </script>\n        </body>\n    </html>\n    \"\"\"\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/site/serve_app/","title":"serve_app","text":"","boost":0.5},{"location":"api/faststream/asyncapi/site/serve_app/#faststream.asyncapi.site.serve_app","title":"faststream.asyncapi.site.serve_app","text":"
serve_app(schema: Schema, host: str, port: int) -> None\n

Serve the FastAPI application.

PARAMETER DESCRIPTION schema

The schema object representing the API specification.

TYPE: Schema

host

The host address to run the application on.

TYPE: str

port

The port number to run the application on.

TYPE: int

RETURNS DESCRIPTION None

None

Source code in faststream/asyncapi/site.py
def serve_app(\n    schema: \"Schema\",\n    host: str,\n    port: int,\n) -> None:\n    \"\"\"Serve the FastAPI application.\n\n    Args:\n        schema: The schema object representing the API specification.\n        host: The host address to run the application on.\n        port: The port number to run the application on.\n\n    Returns:\n        None\n\n    \"\"\"\n    import uvicorn\n    from fastapi import FastAPI\n    from fastapi.responses import HTMLResponse\n\n    app = FastAPI()\n\n    @app.get(\"/\")\n    def asyncapi(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:  # pragma: no cover\n        \"\"\"Generate an AsyncAPI HTML response.\n\n        Args:\n            sidebar (bool): Whether to include the sidebar. Default is True.\n            info (bool): Whether to include the info section. Default is True.\n            servers (bool): Whether to include the servers section. Default is True.\n            operations (bool): Whether to include the operations section. Default is True.\n            messages (bool): Whether to include the messages section. Default is True.\n            schemas (bool): Whether to include the schemas section. Default is True.\n            errors (bool): Whether to include the errors section. Default is True.\n            expandMessageExamples (bool): Whether to expand message examples. Default is True.\n\n        Returns:\n            HTMLResponse: The generated HTML response.\n\n        \"\"\"\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=schema.info.title,\n            )\n        )\n\n    uvicorn.run(app, host=host, port=port)\n
","boost":0.5},{"location":"api/faststream/asyncapi/utils/resolve_payloads/","title":"resolve_payloads","text":"","boost":0.5},{"location":"api/faststream/asyncapi/utils/resolve_payloads/#faststream.asyncapi.utils.resolve_payloads","title":"faststream.asyncapi.utils.resolve_payloads","text":"
resolve_payloads(\n    payloads: List[Tuple[AnyDict, str]],\n    extra: str = \"\",\n    served_words: int = 1,\n) -> AnyDict\n

Resolve payloads.

PARAMETER DESCRIPTION payloads

A list of dictionaries representing payloads.

TYPE: List[Tuple[AnyDict, str]]

RETURNS DESCRIPTION AnyDict

A dictionary representing the resolved payload.

Source code in faststream/asyncapi/utils.py
def resolve_payloads(\n    payloads: List[Tuple[AnyDict, str]],\n    extra: str = \"\",\n    served_words: int = 1,\n) -> AnyDict:\n    \"\"\"Resolve payloads.\n\n    Args:\n        payloads: A list of dictionaries representing payloads.\n\n    Returns:\n        A dictionary representing the resolved payload.\n\n    \"\"\"\n    ln = len(payloads)\n    payload: AnyDict\n    if ln > 1:\n        one_of_payloads = {}\n\n        for body, handler_name in payloads:\n            title = body[\"title\"]\n            words = title.split(\":\")\n\n            if len(words) > 1:  # not pydantic model case\n                body[\"title\"] = title = \":\".join(\n                    filter(\n                        lambda x: bool(x),\n                        (\n                            handler_name,\n                            extra if extra not in words else \"\",\n                            *words[served_words:],\n                        ),\n                    )\n                )\n\n            one_of_payloads[title] = body\n\n        payload = {\"oneOf\": one_of_payloads}\n\n    elif ln == 1:\n        payload = payloads[0][0]\n\n    else:\n        payload = {}\n\n    return payload\n
","boost":0.5},{"location":"api/faststream/asyncapi/utils/to_camelcase/","title":"to_camelcase","text":"","boost":0.5},{"location":"api/faststream/asyncapi/utils/to_camelcase/#faststream.asyncapi.utils.to_camelcase","title":"faststream.asyncapi.utils.to_camelcase","text":"
to_camelcase(*names: str) -> str\n

Converts a list of names to camel case.

PARAMETER DESCRIPTION *names

Variable length list of names to be converted to camel case.

TYPE: str DEFAULT: ()

RETURNS DESCRIPTION str

The camel case representation of the names.

Example

to_camelcase(\"hello_world\") \"HelloWorld\"

Source code in faststream/asyncapi/utils.py
def to_camelcase(*names: str) -> str:\n    \"\"\"Converts a list of names to camel case.\n\n    Args:\n        *names: Variable length list of names to be converted to camel case.\n\n    Returns:\n        The camel case representation of the names.\n\n    Example:\n        >>> to_camelcase(\"hello_world\")\n        \"HelloWorld\"\n\n    \"\"\"\n    return \" \".join(names).replace(\"_\", \" \").title().replace(\" \", \"\")\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/","title":"BrokerUsecase","text":"","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase","title":"faststream.broker.core.abc.BrokerUsecase","text":"
BrokerUsecase(\n    url: Union[str, List[str]],\n    *args: Any,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = None,\n    description: Optional[str] = None,\n    tags: Optional[\n        Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]\n    ] = None,\n    asyncapi_url: Union[str, List[str], None] = None,\n    apply_types: bool = True,\n    validate: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[\n        str\n    ] = \"%(asctime)s %(levelname)s - %(message)s\",\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[Callable[[MsgType], BaseMiddleware]]\n    ] = None,\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: ABC, Generic[MsgType, ConnectionType], LoggingMixin

A class representing a broker use case.

METHOD DESCRIPTION __init__

constructor method

include_router

include a router in the broker

include_routers

include multiple routers in the broker

_resolve_connection_kwargs

resolve connection kwargs

_wrap_handler

wrap a handler function

_abc_start

start the broker

_abc_close

close the broker

_abc__close

close the broker connection

_process_message

process a message

subscriber

decorator to register a subscriber

publisher

register a publisher

_wrap_decode_message

wrap a message decoding function

Initialize a broker.

PARAMETER DESCRIPTION url

The URL or list of URLs to connect to.

TYPE: Union[str, List[str]]

*args

Additional arguments.

TYPE: Any DEFAULT: ()

protocol

The protocol to use for the connection.

TYPE: Optional[str] DEFAULT: None

protocol_version

The version of the protocol.

TYPE: Optional[str] DEFAULT: None

description

A description of the broker.

TYPE: Optional[str] DEFAULT: None

tags

Tags associated with the broker.

TYPE: Optional[Sequence[Union[Tag, TagDict]]] DEFAULT: None

apply_types

Whether to apply types to messages.

TYPE: bool DEFAULT: True

validate

Whether to cast types using Pydantic validation.

TYPE: bool DEFAULT: True

logger

The logger to use.

TYPE: Optional[Logger] DEFAULT: access_logger

log_level

The log level to use.

TYPE: int DEFAULT: INFO

log_fmt

The log format to use.

TYPE: Optional[str] DEFAULT: '%(asctime)s %(levelname)s - %(message)s'

dependencies

Dependencies of the broker.

TYPE: Sequence[Depends] DEFAULT: ()

middlewares

Middlewares to use.

TYPE: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] DEFAULT: None

decoder

Custom decoder for messages.

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

parser

Custom parser for messages.

TYPE: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/core/abc.py
def __init__(\n    self,\n    url: Union[str, List[str]],\n    *args: Any,\n    # AsyncAPI kwargs\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = None,\n    description: Optional[str] = None,\n    tags: Optional[Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]] = None,\n    asyncapi_url: Union[str, List[str], None] = None,\n    # broker kwargs\n    apply_types: bool = True,\n    validate: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = \"%(asctime)s %(levelname)s - %(message)s\",\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] = None,\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a broker.\n\n    Args:\n        url: The URL or list of URLs to connect to.\n        *args: Additional arguments.\n        protocol: The protocol to use for the connection.\n        protocol_version: The version of the protocol.\n        description: A description of the broker.\n        tags: Tags associated with the broker.\n        apply_types: Whether to apply types to messages.\n        validate: Whether to cast types using Pydantic validation.\n        logger: The logger to use.\n        log_level: The log level to use.\n        log_fmt: The log format to use.\n        dependencies: Dependencies of the broker.\n        middlewares: Middlewares to use.\n        decoder: Custom decoder for messages.\n        parser: Custom parser for messages.\n        **kwargs: Additional keyword arguments.\n\n    \"\"\"\n    super().__init__(\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n    )\n\n    self._connection = None\n    self._is_apply_types = apply_types\n    self._is_validate = validate\n    self.handlers = {}\n    self._publishers = {}\n    empty_middleware: Sequence[Callable[[MsgType], BaseMiddleware]] = ()\n    midd_args: Sequence[Callable[[MsgType], BaseMiddleware]] = (\n        middlewares or empty_middleware\n    )\n    self.middlewares = [CriticalLogMiddleware(logger, log_level), *midd_args]\n    self.dependencies = dependencies\n\n    self._connection_args = (url, *args)\n    self._connection_kwargs = kwargs\n\n    self._global_parser = parser\n    self._global_decoder = decoder\n\n    context.set_global(\"logger\", logger)\n    context.set_global(\"broker\", self)\n\n    self.started = False\n\n    # AsyncAPI information\n    self.url = asyncapi_url or url\n    self.protocol = protocol\n    self.protocol_version = protocol_version\n    self.description = description\n    self.tags = tags\n    self.security = security\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.handlers","title":"handlers instance-attribute","text":"
handlers: Mapping[Any, BaseHandler[MsgType]] = {}\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[Any], BaseMiddleware]] = [\n    CriticalLogMiddleware(logger, log_level),\n    *midd_args,\n]\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.url","title":"url instance-attribute","text":"
url = asyncapi_url or url\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.publisher","title":"publisher abstractmethod","text":"
publisher(\n    key: Any, publisher: BasePublisher[MsgType]\n) -> BasePublisher[MsgType]\n

Publishes a publisher.

PARAMETER DESCRIPTION key

The key associated with the publisher.

TYPE: Any

publisher

The publisher to be published.

TYPE: BasePublisher[MsgType]

RETURNS DESCRIPTION BasePublisher[MsgType]

The published publisher.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/abc.py
@abstractmethod\ndef publisher(\n    self,\n    key: Any,\n    publisher: BasePublisher[MsgType],\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a publisher.\n\n    Args:\n        key: The key associated with the publisher.\n        publisher: The publisher to be published.\n\n    Returns:\n        The published publisher.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    self._publishers = {**self._publishers, key: publisher}\n    return publisher\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.subscriber","title":"subscriber abstractmethod","text":"
subscriber(\n    *broker_args: Any,\n    retry: Union[bool, int] = False,\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Filter[\n        StreamMessage[MsgType]\n    ] = lambda: not m.processed,\n    _raw: bool = False,\n    _get_dependant: Optional[Any] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [\n        Union[\n            Callable[P_HandlerParams, T_HandlerReturn],\n            HandlerCallWrapper[\n                MsgType, P_HandlerParams, T_HandlerReturn\n            ],\n        ]\n    ],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

This is a function decorator for subscribing to a message broker.

PARAMETER DESCRIPTION *broker_args

Positional arguments to be passed to the broker.

TYPE: Any DEFAULT: ()

retry

Whether to retry the subscription if it fails. Can be a boolean or an integer specifying the number of retries.

TYPE: Union[bool, int] DEFAULT: False

dependencies

Sequence of dependencies to be injected into the handler function.

TYPE: Sequence[Depends] DEFAULT: ()

decoder

Custom decoder function to decode the message.

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

parser

Custom parser function to parse the decoded message.

TYPE: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] DEFAULT: None

middlewares

Sequence of middleware functions to be applied to the message.

TYPE: Optional[Sequence[Callable[[StreamMessage[MsgType]], BaseMiddleware]]] DEFAULT: None

filter

Filter function to filter the messages to be processed.

TYPE: Filter[StreamMessage[MsgType]] DEFAULT: lambda : not processed

_raw

Whether to return the raw message instead of the processed message.

TYPE: bool DEFAULT: False

_get_dependant

Optional parameter to get the dependant object.

TYPE: Optional[Any] DEFAULT: None

**broker_kwargs

Keyword arguments to be passed to the broker.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Callable[[Union[Callable[P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable object that can be used as a decorator for a handler function.

RAISES DESCRIPTION RuntimeWarning

If the broker is already running.

Source code in faststream/broker/core/abc.py
@abstractmethod\ndef subscriber(  # type: ignore[return]\n    self,\n    *broker_args: Any,\n    retry: Union[bool, int] = False,\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                BaseMiddleware,\n            ]\n        ]\n    ] = None,\n    filter: Filter[StreamMessage[MsgType]] = lambda m: not m.processed,\n    _raw: bool = False,\n    _get_dependant: Optional[Any] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [\n        Union[\n            Callable[P_HandlerParams, T_HandlerReturn],\n            HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n        ]\n    ],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"This is a function decorator for subscribing to a message broker.\n\n    Args:\n        *broker_args: Positional arguments to be passed to the broker.\n        retry: Whether to retry the subscription if it fails. Can be a boolean or an integer specifying the number of retries.\n        dependencies: Sequence of dependencies to be injected into the handler function.\n        decoder: Custom decoder function to decode the message.\n        parser: Custom parser function to parse the decoded message.\n        middlewares: Sequence of middleware functions to be applied to the message.\n        filter: Filter function to filter the messages to be processed.\n        _raw: Whether to return the raw message instead of the processed message.\n        _get_dependant: Optional parameter to get the dependant object.\n        **broker_kwargs: Keyword arguments to be passed to the broker.\n\n    Returns:\n        A callable object that can be used as a decorator for a handler function.\n\n    Raises:\n        RuntimeWarning: If the broker is already running.\n\n    \"\"\"\n    if self.started and not is_test_env():  # pragma: no cover\n        warnings.warn(\n            \"You are trying to register `handler` with already running broker\\n\"  # noqa: E501\n            \"It has no effect until broker restarting.\",  # noqa: E501\n            category=RuntimeWarning,\n            stacklevel=1,\n        )\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/extend_dependencies/","title":"extend_dependencies","text":"","boost":0.5},{"location":"api/faststream/broker/core/abc/extend_dependencies/#faststream.broker.core.abc.extend_dependencies","title":"faststream.broker.core.abc.extend_dependencies","text":"
extend_dependencies(\n    extra: Sequence[CallModel[Any, Any]],\n    dependant: CallModel[Any, Any],\n) -> CallModel[Any, Any]\n

Extends the dependencies of a function or FastAPI dependency.

PARAMETER DESCRIPTION extra

Additional dependencies to be added.

TYPE: Sequence[CallModel[Any, Any]]

dependant

The function or FastAPI dependency whose dependencies will be extended.

TYPE: CallModel[Any, Any]

RETURNS DESCRIPTION CallModel[Any, Any]

The updated function or FastAPI dependency.

Source code in faststream/broker/core/abc.py
def extend_dependencies(\n    extra: Sequence[CallModel[Any, Any]], dependant: CallModel[Any, Any]\n) -> CallModel[Any, Any]:\n    \"\"\"Extends the dependencies of a function or FastAPI dependency.\n\n    Args:\n        extra: Additional dependencies to be added.\n        dependant: The function or FastAPI dependency whose dependencies will be extended.\n\n    Returns:\n        The updated function or FastAPI dependency.\n\n    \"\"\"\n    if isinstance(dependant, CallModel):\n        dependant.extra_dependencies = (*dependant.extra_dependencies, *extra)\n    else:  # FastAPI dependencies\n        dependant.dependencies.extend(extra)\n    return dependant\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/","title":"BrokerAsyncUsecase","text":"","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase","title":"faststream.broker.core.asyncronous.BrokerAsyncUsecase","text":"
BrokerAsyncUsecase(\n    *args: Any,\n    apply_types: bool = True,\n    validate: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[\n        str\n    ] = \"%(asctime)s %(levelname)s - %(message)s\",\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    middlewares: Optional[\n        Sequence[Callable[[MsgType], BaseMiddleware]]\n    ] = None,\n    graceful_timeout: Optional[float] = None,\n    **kwargs: Any\n)\n

Bases: BrokerUsecase[MsgType, ConnectionType]

A class representing a broker async usecase.

METHOD DESCRIPTION start

Abstract method to start the broker async usecase.

_connect

Any) : Abstract method to connect to the broker.

_close

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) : Abstract method to close the connection to the broker.

close

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) : Close the connection to the broker.

_process_message

Callable[[StreamMessage[MsgType]], Awaitable[T_HandlerReturn]], watcher: BaseWatcher) : Abstract method to process a message.

publish

SendableMessage, *args: Any, reply_to: str = \"\", rpc: bool = False, rpc_timeout: Optional[float]

Initialize the class.

PARAMETER DESCRIPTION *args

Variable length arguments

TYPE: Any DEFAULT: ()

apply_types

Whether to apply types or not

TYPE: bool DEFAULT: True

validate

Whether to cast types using Pydantic validation.

TYPE: bool DEFAULT: True

logger

Logger object for logging

TYPE: Optional[Logger] DEFAULT: access_logger

log_level

Log level for logging

TYPE: int DEFAULT: INFO

log_fmt

Log format for logging

TYPE: Optional[str] DEFAULT: '%(asctime)s %(levelname)s - %(message)s'

dependencies

Sequence of dependencies

TYPE: Sequence[Depends] DEFAULT: ()

decoder

Custom decoder object

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

parser

Custom parser object

TYPE: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] DEFAULT: None

middlewares

Sequence of middlewares

TYPE: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] DEFAULT: None

**kwargs

Keyword arguments

TYPE: Any DEFAULT: {}

Source code in faststream/broker/core/asyncronous.py
def __init__(\n    self,\n    *args: Any,\n    apply_types: bool = True,\n    validate: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = \"%(asctime)s %(levelname)s - %(message)s\",\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    middlewares: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] = None,\n    graceful_timeout: Optional[float] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        *args: Variable length arguments\n        apply_types: Whether to apply types or not\n        validate: Whether to cast types using Pydantic validation.\n        logger: Logger object for logging\n        log_level: Log level for logging\n        log_fmt: Log format for logging\n        dependencies: Sequence of dependencies\n        decoder: Custom decoder object\n        parser: Custom parser object\n        middlewares: Sequence of middlewares\n        **kwargs: Keyword arguments\n\n    \"\"\"\n    super().__init__(\n        *args,\n        apply_types=apply_types,\n        validate=validate,\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n        dependencies=dependencies,\n        decoder=cast(\n            Optional[AsyncCustomDecoder[StreamMessage[MsgType]]],\n            to_async(decoder) if decoder else None,\n        ),\n        parser=cast(\n            Optional[AsyncCustomParser[MsgType, StreamMessage[MsgType]]],\n            to_async(parser) if parser else None,\n        ),\n        middlewares=middlewares,\n        **kwargs,\n    )\n    self.graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.handlers","title":"handlers instance-attribute","text":"
handlers: Mapping[Any, AsyncHandler[MsgType]]\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.url","title":"url instance-attribute","text":"
url = asyncapi_url or url\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.connect","title":"connect async","text":"
connect(*args: Any, **kwargs: Any) -> ConnectionType\n

Connect to a remote server.

PARAMETER DESCRIPTION *args

Variable length argument list.

TYPE: Any DEFAULT: ()

**kwargs

Arbitrary keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION ConnectionType

The connection object.

Source code in faststream/broker/core/asyncronous.py
async def connect(self, *args: Any, **kwargs: Any) -> ConnectionType:\n    \"\"\"Connect to a remote server.\n\n    Args:\n        *args: Variable length argument list.\n        **kwargs: Arbitrary keyword arguments.\n\n    Returns:\n        The connection object.\n\n    \"\"\"\n    if self._connection is None:\n        _kwargs = self._resolve_connection_kwargs(*args, **kwargs)\n        self._connection = await self._connect(**_kwargs)\n    return self._connection\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.publish","title":"publish abstractmethod async","text":"
publish(\n    message: SendableMessage,\n    *args: Any,\n    reply_to: str = \"\",\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

*args

Additional arguments.

TYPE: Any DEFAULT: ()

reply_to

The reply-to address for the message.

TYPE: str DEFAULT: ''

rpc

Whether the message is for RPC.

TYPE: bool DEFAULT: False

rpc_timeout

The timeout for RPC.

TYPE: Optional[float] DEFAULT: None

raise_timeout

Whether to raise an exception on timeout.

TYPE: bool DEFAULT: False

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
@abstractmethod\nasync def publish(\n    self,\n    message: SendableMessage,\n    *args: Any,\n    reply_to: str = \"\",\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        *args: Additional arguments.\n        reply_to: The reply-to address for the message.\n        rpc: Whether the message is for RPC.\n        rpc_timeout: The timeout for RPC.\n        raise_timeout: Whether to raise an exception on timeout.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.publisher","title":"publisher abstractmethod","text":"
publisher(\n    key: Any, publisher: BasePublisher[MsgType]\n) -> BasePublisher[MsgType]\n

Publishes a publisher.

PARAMETER DESCRIPTION key

The key associated with the publisher.

TYPE: Any

publisher

The publisher to be published.

TYPE: BasePublisher[MsgType]

RETURNS DESCRIPTION BasePublisher[MsgType]

The published publisher.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/abc.py
@abstractmethod\ndef publisher(\n    self,\n    key: Any,\n    publisher: BasePublisher[MsgType],\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a publisher.\n\n    Args:\n        key: The key associated with the publisher.\n        publisher: The publisher to be published.\n\n    Returns:\n        The published publisher.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    self._publishers = {**self._publishers, key: publisher}\n    return publisher\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.start","title":"start abstractmethod async","text":"
start() -> None\n
Source code in faststream/broker/core/asyncronous.py
@abstractmethod\nasync def start(self) -> None:\n    super()._abc_start()\n    for h in self.handlers.values():\n        for f, _, _, _, _, _ in h.calls:\n            f.refresh(with_mock=False)\n    await self.connect()\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.subscriber","title":"subscriber abstractmethod","text":"
subscriber(\n    *broker_args: Any,\n    retry: Union[bool, int] = False,\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    middlewares: Optional[\n        Sequence[Callable[[MsgType], BaseMiddleware]]\n    ] = None,\n    filter: Filter[StreamMessage[MsgType]] = default_filter,\n    _raw: bool = False,\n    _get_dependant: Optional[Any] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [\n        Union[\n            Callable[P_HandlerParams, T_HandlerReturn],\n            HandlerCallWrapper[\n                MsgType, P_HandlerParams, T_HandlerReturn\n            ],\n        ]\n    ],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function decorator for subscribing to a message broker.

PARAMETER DESCRIPTION *broker_args

Positional arguments to be passed to the message broker.

TYPE: Any DEFAULT: ()

retry

Whether to retry the subscription if it fails. Can be a boolean or an integer specifying the number of retries.

TYPE: Union[bool, int] DEFAULT: False

dependencies

Sequence of dependencies to be injected into the decorated function.

TYPE: Sequence[Depends] DEFAULT: ()

decoder

Custom decoder function for decoding the message.

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

parser

Custom parser function for parsing the decoded message.

TYPE: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] DEFAULT: None

middlewares

Sequence of middleware functions to be applied to the message.

TYPE: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] DEFAULT: None

filter

Filter function for filtering the messages to be processed.

TYPE: Filter[StreamMessage[MsgType]] DEFAULT: default_filter

_raw

Whether to return the raw message instead of the processed result.

TYPE: bool DEFAULT: False

_get_dependant

Optional argument to get the dependant object.

TYPE: Optional[Any] DEFAULT: None

RETURNS DESCRIPTION Callable[[Union[Callable[P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable decorator that wraps the decorated function and handles the subscription.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/core/asyncronous.py
@override\n@abstractmethod\ndef subscriber(  # type: ignore[override,return]\n    self,\n    *broker_args: Any,\n    retry: Union[bool, int] = False,\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    middlewares: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] = None,\n    filter: Filter[StreamMessage[MsgType]] = default_filter,\n    _raw: bool = False,\n    _get_dependant: Optional[Any] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [\n        Union[\n            Callable[P_HandlerParams, T_HandlerReturn],\n            HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n        ]\n    ],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function decorator for subscribing to a message broker.\n\n    Args:\n        *broker_args: Positional arguments to be passed to the message broker.\n        retry: Whether to retry the subscription if it fails. Can be a boolean or an integer specifying the number of retries.\n        dependencies: Sequence of dependencies to be injected into the decorated function.\n        decoder: Custom decoder function for decoding the message.\n        parser: Custom parser function for parsing the decoded message.\n        middlewares: Sequence of middleware functions to be applied to the message.\n        filter: Filter function for filtering the messages to be processed.\n        _raw: Whether to return the raw message instead of the processed result.\n        _get_dependant: Optional argument to get the dependant object.\n\n    Returns:\n        A callable decorator that wraps the decorated function and handles the subscription.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    super().subscriber()\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/default_filter/","title":"default_filter","text":"","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/default_filter/#faststream.broker.core.asyncronous.default_filter","title":"faststream.broker.core.asyncronous.default_filter async","text":"
default_filter(msg: StreamMessage[Any]) -> bool\n

A function to filter stream messages.

PARAMETER DESCRIPTION msg

A stream message object

RETURNS DESCRIPTION bool

True if the message has not been processed, False otherwise

Source code in faststream/broker/core/asyncronous.py
async def default_filter(msg: StreamMessage[Any]) -> bool:\n    \"\"\"A function to filter stream messages.\n\n    Args:\n        msg : A stream message object\n\n    Returns:\n        True if the message has not been processed, False otherwise\n\n    \"\"\"\n    return not msg.processed\n
","boost":0.5},{"location":"api/faststream/broker/core/mixins/LoggingMixin/","title":"LoggingMixin","text":"","boost":0.5},{"location":"api/faststream/broker/core/mixins/LoggingMixin/#faststream.broker.core.mixins.LoggingMixin","title":"faststream.broker.core.mixins.LoggingMixin","text":"
LoggingMixin(\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[\n        str\n    ] = \"%(asctime)s %(levelname)s - %(message)s\",\n    **kwargs: Any\n)\n

A mixin class for logging.

METHOD DESCRIPTION fmt

getter method for _fmt attribute

_get_log_context

returns a dictionary with log context information

_log

logs a message with optional log level, extra data, and exception info

Initialize the class.

PARAMETER DESCRIPTION *args

Variable length argument list

TYPE: Any DEFAULT: ()

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: access_logger

log_level

Log level (default: logging.INFO)

TYPE: int DEFAULT: INFO

log_fmt

Log format (default: \"%(asctime)s %(levelname)s - %(message)s\")

TYPE: Optional[str] DEFAULT: '%(asctime)s %(levelname)s - %(message)s'

**kwargs

Arbitrary keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/mixins.py
def __init__(\n    self,\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = \"%(asctime)s %(levelname)s - %(message)s\",\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        *args: Variable length argument list\n        logger: Optional logger object\n        log_level: Log level (default: logging.INFO)\n        log_fmt: Log format (default: \"%(asctime)s %(levelname)s - %(message)s\")\n        **kwargs: Arbitrary keyword arguments\n\n    Returns:\n        None\n\n    \"\"\"\n    self.logger = logger\n    self.log_level = log_level\n    self._fmt = log_fmt\n    self._message_id_ln = 10\n
","boost":0.5},{"location":"api/faststream/broker/core/mixins/LoggingMixin/#faststream.broker.core.mixins.LoggingMixin.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/broker/core/mixins/LoggingMixin/#faststream.broker.core.mixins.LoggingMixin.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/broker/core/mixins/LoggingMixin/#faststream.broker.core.mixins.LoggingMixin.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/","title":"StreamMessage","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage","title":"faststream.broker.fastapi.StreamMessage","text":"
StreamMessage(\n    *,\n    body: Union[AnyDict, List[Any]],\n    headers: AnyDict,\n    path: AnyDict\n)\n

Bases: Request

A class to represent a stream message.

METHOD DESCRIPTION __init__

initializes the StreamMessage object

get_session

returns a callable function that handles the session of the message

Initialize a class instance.

PARAMETER DESCRIPTION body

The body of the request as a dictionary.

TYPE: Union[AnyDict, List[Any]]

headers

The headers of the request as a dictionary.

TYPE: AnyDict

Source code in faststream/broker/fastapi/route.py
def __init__(\n    self,\n    *,\n    body: Union[AnyDict, List[Any]],\n    headers: AnyDict,\n    path: AnyDict,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        body: The body of the request as a dictionary.\n        headers: The headers of the request as a dictionary.\n\n    Attributes:\n        scope: A dictionary to store the scope of the request.\n        _cookies: A dictionary to store the cookies of the request.\n        _headers: A dictionary to store the headers of the request.\n        _body: A dictionary to store the body of the request.\n        _query_params: A dictionary to store the query parameters of the request.\n\n    \"\"\"\n    self._headers = headers\n    self._body = body\n    self._query_params = path\n\n    self.scope = {\"path_params\": self._query_params}\n    self._cookies = {}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.app","title":"app property","text":"
app: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.auth","title":"auth property","text":"
auth: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.base_url","title":"base_url property","text":"
base_url: URL\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.client","title":"client property","text":"
client: typing.Optional[Address]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.cookies","title":"cookies property","text":"
cookies: typing.Dict[str, str]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.headers","title":"headers property","text":"
headers: Headers\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.method","title":"method property","text":"
method: str\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.path_params","title":"path_params property","text":"
path_params: typing.Dict[str, typing.Any]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.query_params","title":"query_params property","text":"
query_params: QueryParams\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.receive","title":"receive property","text":"
receive: Receive\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.scope","title":"scope instance-attribute","text":"
scope: AnyDict = {'path_params': self._query_params}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.session","title":"session property","text":"
session: typing.Dict[str, typing.Any]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.state","title":"state property","text":"
state: State\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.url","title":"url property","text":"
url: URL\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.user","title":"user property","text":"
user: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.body","title":"body async","text":"
body() -> bytes\n
Source code in starlette/requests.py
async def body(self) -> bytes:\n    if not hasattr(self, \"_body\"):\n        chunks: \"typing.List[bytes]\" = []\n        async for chunk in self.stream():\n            chunks.append(chunk)\n        self._body = b\"\".join(chunks)\n    return self._body\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.close","title":"close async","text":"
close() -> None\n
Source code in starlette/requests.py
async def close(self) -> None:\n    if self._form is not None:\n        await self._form.close()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.form","title":"form","text":"
form(\n    *,\n    max_files: typing.Union[int, float] = 1000,\n    max_fields: typing.Union[int, float] = 1000\n) -> AwaitableOrContextManager[FormData]\n
Source code in starlette/requests.py
def form(\n    self,\n    *,\n    max_files: typing.Union[int, float] = 1000,\n    max_fields: typing.Union[int, float] = 1000,\n) -> AwaitableOrContextManager[FormData]:\n    return AwaitableOrContextManagerWrapper(\n        self._get_form(max_files=max_files, max_fields=max_fields)\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.get_session","title":"get_session classmethod","text":"
get_session(\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[\n    [NativeMessage[Any]], Awaitable[SendableMessage]\n]\n

Creates a session for handling requests.

PARAMETER DESCRIPTION dependant

The dependant object representing the session.

TYPE: Dependant

dependency_overrides_provider

Optional provider for dependency overrides.

TYPE: Optional[Any] DEFAULT: None

RETURNS DESCRIPTION Callable[[StreamMessage[Any]], Awaitable[SendableMessage]]

A callable that takes a native message and returns an awaitable sendable message.

RAISES DESCRIPTION AssertionError

If the dependant call is not defined.

Note

This function is used to create a session for handling requests. It takes a dependant object, which represents the session, and a dependency overrides provider, which allows for overriding dependencies. It returns a callable that takes a native message and returns an awaitable sendable message. The session is created based on the dependant object and the message passed to the callable. The session is then used to call the function obtained from the dependant object, and the result is returned.

Source code in faststream/broker/fastapi/route.py
@classmethod\ndef get_session(\n    cls,\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[[NativeMessage[Any]], Awaitable[SendableMessage]]:\n    \"\"\"Creates a session for handling requests.\n\n    Args:\n        dependant: The dependant object representing the session.\n        dependency_overrides_provider: Optional provider for dependency overrides.\n\n    Returns:\n        A callable that takes a native message and returns an awaitable sendable message.\n\n    Raises:\n        AssertionError: If the dependant call is not defined.\n\n    Note:\n        This function is used to create a session for handling requests. It takes a dependant object, which represents the session, and a dependency overrides provider, which allows for overriding dependencies. It returns a callable that takes a native message and returns an awaitable sendable message. The session is created based on the dependant object and the message passed to the callable. The session is then used to call the function obtained from the dependant object, and the result is returned.\n\n    \"\"\"\n    assert dependant.call  # nosec B101\n\n    func = get_app(dependant, dependency_overrides_provider)\n\n    dependencies_names = tuple(i.name for i in dependant.dependencies)\n\n    first_arg = next(\n        dropwhile(\n            lambda i: i in dependencies_names,\n            inspect.signature(dependant.call).parameters,\n        ),\n        None,\n    )\n\n    async def app(message: NativeMessage[Any]) -> SendableMessage:\n        \"\"\"An asynchronous function that processes an incoming message and returns a sendable message.\n\n        Args:\n            message : The incoming message to be processed\n\n        Returns:\n            The sendable message\n\n        Raises:\n            TypeError: If the body of the message is not a dictionary\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        body = message.decoded_body\n\n        fastapi_body: Union[AnyDict, List[Any]]\n        if first_arg is not None:\n            if isinstance(body, dict):\n                path = fastapi_body = body or {}\n            elif isinstance(body, list):\n                fastapi_body, path = body, {}\n            else:\n                path = fastapi_body = {first_arg: body}\n\n            session = cls(\n                body=fastapi_body,\n                headers=message.headers,\n                path={**path, **message.path},\n            )\n\n        else:\n            session = cls(\n                body={},\n                headers={},\n                path={},\n            )\n\n        return await func(session)\n\n    return app\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.is_disconnected","title":"is_disconnected async","text":"
is_disconnected() -> bool\n
Source code in starlette/requests.py
async def is_disconnected(self) -> bool:\n    if not self._is_disconnected:\n        message: Message = {}\n\n        # If message isn't immediately available, move on\n        with anyio.CancelScope() as cs:\n            cs.cancel()\n            message = await self._receive()\n\n        if message.get(\"type\") == \"http.disconnect\":\n            self._is_disconnected = True\n\n    return self._is_disconnected\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.json","title":"json async","text":"
json() -> typing.Any\n
Source code in starlette/requests.py
async def json(self) -> typing.Any:\n    if not hasattr(self, \"_json\"):\n        body = await self.body()\n        self._json = json.loads(body)\n    return self._json\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.send_push_promise","title":"send_push_promise async","text":"
send_push_promise(path: str) -> None\n
Source code in starlette/requests.py
async def send_push_promise(self, path: str) -> None:\n    if \"http.response.push\" in self.scope.get(\"extensions\", {}):\n        raw_headers: \"typing.List[typing.Tuple[bytes, bytes]]\" = []\n        for name in SERVER_PUSH_HEADERS_TO_COPY:\n            for value in self.headers.getlist(name):\n                raw_headers.append(\n                    (name.encode(\"latin-1\"), value.encode(\"latin-1\"))\n                )\n        await self._send(\n            {\"type\": \"http.response.push\", \"path\": path, \"headers\": raw_headers}\n        )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.stream","title":"stream async","text":"
stream() -> typing.AsyncGenerator[bytes, None]\n
Source code in starlette/requests.py
async def stream(self) -> typing.AsyncGenerator[bytes, None]:\n    if hasattr(self, \"_body\"):\n        yield self._body\n        yield b\"\"\n        return\n    if self._stream_consumed:\n        raise RuntimeError(\"Stream consumed\")\n    self._stream_consumed = True\n    while True:\n        message = await self._receive()\n        if message[\"type\"] == \"http.request\":\n            body = message.get(\"body\", b\"\")\n            if body:\n                yield body\n            if not message.get(\"more_body\", False):\n                break\n        elif message[\"type\"] == \"http.disconnect\":\n            self._is_disconnected = True\n            raise ClientDisconnect()\n    yield b\"\"\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.url_for","title":"url_for","text":"
url_for(__name: str, **path_params: typing.Any) -> URL\n
Source code in starlette/requests.py
def url_for(self, __name: str, **path_params: typing.Any) -> URL:\n    router: Router = self.scope[\"router\"]\n    url_path = router.url_path_for(__name, **path_params)\n    return url_path.make_absolute_url(base_url=self.base_url)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/","title":"StreamRoute","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute","title":"faststream.broker.fastapi.StreamRoute","text":"
StreamRoute(\n    path: Union[NameRequired, str, None],\n    *extra: Union[NameRequired, str],\n    endpoint: Union[\n        Callable[P_HandlerParams, T_HandlerReturn],\n        HandlerCallWrapper[\n            MsgType, P_HandlerParams, T_HandlerReturn\n        ],\n    ],\n    broker: BrokerAsyncUsecase[MsgType, Any],\n    dependencies: Sequence[params.Depends] = (),\n    dependency_overrides_provider: Optional[Any] = None,\n    **handle_kwargs: Any\n)\n

Bases: BaseRoute, Generic[MsgType, P_HandlerParams, T_HandlerReturn]

A class representing a stream route.

Initialize a class instance.

PARAMETER DESCRIPTION path

The path of the instance.

TYPE: Union[NameRequired, str, None]

*extra

Additional arguments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint of the instance.

TYPE: Union[Callable[P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

broker

The broker of the instance.

TYPE: BrokerAsyncUsecase[MsgType, Any]

dependencies

The dependencies of the instance.

TYPE: Sequence[Depends] DEFAULT: ()

dependency_overrides_provider

The provider for dependency overrides.

TYPE: Optional[Any] DEFAULT: None

**handle_kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None.

Source code in faststream/broker/fastapi/route.py
def __init__(\n    self,\n    path: Union[NameRequired, str, None],\n    *extra: Union[NameRequired, str],\n    endpoint: Union[\n        Callable[P_HandlerParams, T_HandlerReturn],\n        HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n    ],\n    broker: BrokerAsyncUsecase[MsgType, Any],\n    dependencies: Sequence[params.Depends] = (),\n    dependency_overrides_provider: Optional[Any] = None,\n    **handle_kwargs: Any,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        path: The path of the instance.\n        *extra: Additional arguments.\n        endpoint: The endpoint of the instance.\n        broker: The broker of the instance.\n        dependencies: The dependencies of the instance.\n        dependency_overrides_provider: The provider for dependency overrides.\n        **handle_kwargs: Additional keyword arguments.\n\n    Returns:\n        None.\n\n    \"\"\"\n    self.path = path or \"\"\n    self.broker = broker\n\n    path_name = self.path if isinstance(self.path, str) else self.path.name\n\n    if isinstance(endpoint, HandlerCallWrapper):\n        orig_call = endpoint._original_call\n    else:\n        orig_call = endpoint\n\n    dependant = get_dependant(\n        path=path_name,\n        call=orig_call,\n    )\n    for depends in dependencies[::-1]:\n        dependant.dependencies.insert(\n            0,\n            get_parameterless_sub_dependant(depends=depends, path=path_name),\n        )\n    self.dependant = dependant\n\n    call = wraps(orig_call)(\n        StreamMessage.get_session(\n            dependant,\n            dependency_overrides_provider,\n        )\n    )\n\n    if isinstance(endpoint, HandlerCallWrapper):\n        endpoint._original_call = call\n        handler = endpoint\n\n    else:\n        handler = call\n\n    self.handler = broker.subscriber(\n        path,\n        *extra,\n        _raw=True,\n        _get_dependant=lambda call: dependant,\n        **handle_kwargs,\n    )(\n        handler  # type: ignore[arg-type]\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.dependant","title":"dependant instance-attribute","text":"
dependant = dependant\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.handler","title":"handler instance-attribute","text":"
handler: HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n] = broker.subscriber(\n    path,\n    *extra,\n    _raw=True,\n    _get_dependant=lambda: dependant,\n    **handle_kwargs\n)(\n    handler\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.path","title":"path instance-attribute","text":"
path = path or ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.handle","title":"handle async","text":"
handle(scope: Scope, receive: Receive, send: Send) -> None\n
Source code in starlette/routing.py
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.matches","title":"matches","text":"
matches(scope: Scope) -> typing.Tuple[Match, Scope]\n
Source code in starlette/routing.py
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/","title":"StreamRouter","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter","title":"faststream.broker.fastapi.StreamRouter","text":"
StreamRouter(\n    *connection_args: Tuple[Any, ...],\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    setup_state: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id),\n    asyncapi_tags: Optional[\n        Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]\n    ] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    **connection_kwars: Any\n)\n

Bases: APIRouter, Generic[MsgType]

A class to route streams.

METHOD DESCRIPTION __init__

initialize the StreamRouter

add_api_mq_route

add a route for API and message queue

subscriber

decorator to define a subscriber

wrap_lifespan

wrap the lifespan of the router

after_startup

decorator to define a function to be executed after startup

publisher

create a publisher for the broker

asyncapi_router

create an APIRouter for AsyncAPI documentation

include_router

include another router in the StreamRouter

_setup_log_context

setup log context for the broker

Initialize an instance of a class.

PARAMETER DESCRIPTION *connection_args

Variable length arguments for the connection

TYPE: Tuple[Any, ...] DEFAULT: ()

prefix

Prefix for the class

TYPE: str DEFAULT: ''

tags

Optional list of tags for the class

TYPE: Optional[List[Union[str, Enum]]] DEFAULT: None

dependencies

Optional sequence of dependencies for the class

TYPE: Optional[Sequence[Depends]] DEFAULT: None

default_response_class

Default response class for the class

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

Optional dictionary of responses for the class

TYPE: Optional[Dict[Union[int, str], AnyDict]] DEFAULT: None

callbacks

Optional list of callbacks for the class

TYPE: Optional[List[BaseRoute]] DEFAULT: None

routes

Optional list of routes for the class

TYPE: Optional[List[BaseRoute]] DEFAULT: None

redirect_slashes

Boolean value indicating whether to redirect slashes

TYPE: bool DEFAULT: True

default

Optional default value for the class

TYPE: Optional[ASGIApp] DEFAULT: None

dependency_overrides_provider

Optional provider for dependency overrides

TYPE: Optional[Any] DEFAULT: None

route_class

Route class for the class

TYPE: Type[APIRoute] DEFAULT: APIRoute

on_startup

Optional sequence of functions to run on startup

TYPE: Optional[Sequence[Callable[[], Any]]] DEFAULT: None

on_shutdown

Optional sequence of functions to run on shutdown

TYPE: Optional[Sequence[Callable[[], Any]]] DEFAULT: None

deprecated

Optional boolean value indicating whether the class is deprecated

TYPE: Optional[bool] DEFAULT: None

include_in_schema

Boolean value indicating whether to include the class in the schema

TYPE: bool DEFAULT: True

setup_state

Boolean value indicating whether to setup state

TYPE: bool DEFAULT: True

lifespan

Optional lifespan for the class

TYPE: Optional[Lifespan[Any]] DEFAULT: None

generate_unique_id_function

Function to generate unique ID for the class

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

asyncapi_tags

Optional sequence of asyncapi tags for the class schema

TYPE: Optional[Sequence[Union[Tag, TagDict]]] DEFAULT: None

Source code in faststream/broker/fastapi/router.py
def __init__(\n    self,\n    *connection_args: Tuple[Any, ...],\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[Sequence[Callable[[], Any]]] = None,\n    on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    setup_state: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n    # AsyncAPI information\n    asyncapi_tags: Optional[Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    **connection_kwars: Any,\n) -> None:\n    \"\"\"Initialize an instance of a class.\n\n    Args:\n        *connection_args: Variable length arguments for the connection\n        prefix: Prefix for the class\n        tags: Optional list of tags for the class\n        dependencies: Optional sequence of dependencies for the class\n        default_response_class: Default response class for the class\n        responses: Optional dictionary of responses for the class\n        callbacks: Optional list of callbacks for the class\n        routes: Optional list of routes for the class\n        redirect_slashes: Boolean value indicating whether to redirect slashes\n        default: Optional default value for the class\n        dependency_overrides_provider: Optional provider for dependency overrides\n        route_class: Route class for the class\n        on_startup: Optional sequence of functions to run on startup\n        on_shutdown: Optional sequence of functions to run on shutdown\n        deprecated: Optional boolean value indicating whether the class is deprecated\n        include_in_schema: Boolean value indicating whether to include the class in the schema\n        setup_state: Boolean value indicating whether to setup state\n        lifespan: Optional lifespan for the class\n        generate_unique_id_function: Function to generate unique ID for the class\n        asyncapi_tags: Optional sequence of asyncapi tags for the class schema\n\n    \"\"\"\n    assert (  # nosec B101\n        self.broker_class\n    ), \"You should specify `broker_class` at your implementation\"\n\n    self.broker = self.broker_class(\n        *connection_args,\n        apply_types=False,\n        tags=asyncapi_tags,\n        **connection_kwars,\n    )\n\n    self.setup_state = setup_state\n\n    # AsyncAPI information\n    # Empty\n    self.terms_of_service = None\n    self.identifier = None\n    self.asyncapi_tags = None\n    self.external_docs = None\n    # parse from FastAPI app on startup\n    self.title = \"\"\n    self.version = \"\"\n    self.description = \"\"\n    self.license = None\n    self.contact = None\n\n    self.schema = None\n\n    super().__init__(\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        routes=routes,\n        redirect_slashes=redirect_slashes,\n        default=default,\n        dependency_overrides_provider=dependency_overrides_provider,\n        route_class=route_class,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n        lifespan=self.wrap_lifespan(lifespan),\n        on_startup=on_startup,\n        on_shutdown=on_shutdown,\n    )\n\n    self.docs_router = self.asyncapi_router(schema_url)\n\n    self._after_startup_hooks = []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.broker","title":"broker instance-attribute","text":"
broker: BrokerAsyncUsecase[\n    MsgType, Any\n] = self.broker_class(\n    *connection_args,\n    apply_types=False,\n    tags=asyncapi_tags,\n    **connection_kwars\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.broker_class","title":"broker_class instance-attribute","text":"
broker_class: Type[BrokerAsyncUsecase[MsgType, Any]]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any\n) -> HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n]\n

Add an API message queue route.

PARAMETER DESCRIPTION path

The path of the route.

TYPE: Union[NameRequired, str]

*extra

Additional path segments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint function to be called for this route.

TYPE: Callable[P_HandlerParams, T_HandlerReturn]

dependencies

The dependencies required by the endpoint function.

TYPE: Sequence[Depends]

**broker_kwargs

Additional keyword arguments to be passed to the broker.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]

The handler call wrapper for the route.

Source code in faststream/broker/fastapi/router.py
def add_api_mq_route(\n    self,\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any,\n) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n    \"\"\"Add an API message queue route.\n\n    Args:\n        path: The path of the route.\n        *extra: Additional path segments.\n        endpoint: The endpoint function to be called for this route.\n        dependencies: The dependencies required by the endpoint function.\n        **broker_kwargs: Additional keyword arguments to be passed to the broker.\n\n    Returns:\n        The handler call wrapper for the route.\n\n    \"\"\"\n    route: StreamRoute[MsgType, P_HandlerParams, T_HandlerReturn] = StreamRoute(\n        path,\n        *extra,\n        endpoint=endpoint,\n        dependencies=dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        broker=self.broker,\n        **broker_kwargs,\n    )\n    self.routes.append(route)\n    return route.handler\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.publisher","title":"publisher","text":"
publisher(\n    queue: Union[NameRequired, str],\n    *publisher_args: Any,\n    **publisher_kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes messages to a queue.

PARAMETER DESCRIPTION queue

The queue to publish the messages to. Can be either a NameRequired object or a string.

TYPE: Union[NameRequired, str]

*publisher_args

Additional arguments to be passed to the publisher.

TYPE: Any DEFAULT: ()

**publisher_kwargs

Additional keyword arguments to be passed to the publisher.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

An instance of BasePublisher that can be used to publish messages to the specified queue.

Source code in faststream/broker/fastapi/router.py
def publisher(\n    self,\n    queue: Union[NameRequired, str],\n    *publisher_args: Any,\n    **publisher_kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes messages to a queue.\n\n    Args:\n        queue: The queue to publish the messages to. Can be either a `NameRequired` object or a string.\n        *publisher_args: Additional arguments to be passed to the publisher.\n        **publisher_kwargs: Additional keyword arguments to be passed to the publisher.\n\n    Returns:\n        An instance of `BasePublisher` that can be used to publish messages to the specified queue.\n\n    \"\"\"\n    return self.broker.publisher(\n        queue,\n        *publisher_args,\n        **publisher_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.subscriber","title":"subscriber","text":"
subscriber(\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function decorator for subscribing to a message queue.

PARAMETER DESCRIPTION path

The path to subscribe to. Can be a string or a NameRequired object.

*extra

Additional path segments. Can be a NameRequired object or a string.

DEFAULT: ()

dependencies

Optional sequence of dependencies.

DEFAULT: None

**broker_kwargs

Additional keyword arguments for the broker.

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable decorator that adds the decorated function as an endpoint for the specified path.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def subscriber(\n    self,\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function decorator for subscribing to a message queue.\n\n    Args:\n        path : The path to subscribe to. Can be a string or a `NameRequired` object.\n        *extra : Additional path segments. Can be a `NameRequired` object or a string.\n        dependencies : Optional sequence of dependencies.\n        **broker_kwargs : Additional keyword arguments for the broker.\n\n    Returns:\n        A callable decorator that adds the decorated function as an endpoint for the specified path.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    def decorator(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n        \"\"\"A decorator function.\n\n        Args:\n            func: The function to be decorated.\n\n        Returns:\n            The decorated function.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        return self.add_api_mq_route(\n            path,\n            *extra,\n            endpoint=func,\n            dependencies=current_dependencies,\n            **broker_kwargs,\n        )\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/context/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/context/Context/#faststream.broker.fastapi.context.Context","title":"faststream.broker.fastapi.context.Context","text":"
Context(name: str) -> Any\n
Source code in faststream/broker/fastapi/context.py
def Context(name: str) -> Any:\n    return params.Depends(\n        lambda: context.resolve(name),\n        use_cache=True,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/","title":"StreamMessage","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage","title":"faststream.broker.fastapi.route.StreamMessage","text":"
StreamMessage(\n    *,\n    body: Union[AnyDict, List[Any]],\n    headers: AnyDict,\n    path: AnyDict\n)\n

Bases: Request

A class to represent a stream message.

METHOD DESCRIPTION __init__

initializes the StreamMessage object

get_session

returns a callable function that handles the session of the message

Initialize a class instance.

PARAMETER DESCRIPTION body

The body of the request as a dictionary.

TYPE: Union[AnyDict, List[Any]]

headers

The headers of the request as a dictionary.

TYPE: AnyDict

Source code in faststream/broker/fastapi/route.py
def __init__(\n    self,\n    *,\n    body: Union[AnyDict, List[Any]],\n    headers: AnyDict,\n    path: AnyDict,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        body: The body of the request as a dictionary.\n        headers: The headers of the request as a dictionary.\n\n    Attributes:\n        scope: A dictionary to store the scope of the request.\n        _cookies: A dictionary to store the cookies of the request.\n        _headers: A dictionary to store the headers of the request.\n        _body: A dictionary to store the body of the request.\n        _query_params: A dictionary to store the query parameters of the request.\n\n    \"\"\"\n    self._headers = headers\n    self._body = body\n    self._query_params = path\n\n    self.scope = {\"path_params\": self._query_params}\n    self._cookies = {}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.app","title":"app property","text":"
app: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.auth","title":"auth property","text":"
auth: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.base_url","title":"base_url property","text":"
base_url: URL\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.client","title":"client property","text":"
client: typing.Optional[Address]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.cookies","title":"cookies property","text":"
cookies: typing.Dict[str, str]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.headers","title":"headers property","text":"
headers: Headers\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.method","title":"method property","text":"
method: str\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.path_params","title":"path_params property","text":"
path_params: typing.Dict[str, typing.Any]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.query_params","title":"query_params property","text":"
query_params: QueryParams\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.receive","title":"receive property","text":"
receive: Receive\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.scope","title":"scope instance-attribute","text":"
scope: AnyDict = {'path_params': self._query_params}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.session","title":"session property","text":"
session: typing.Dict[str, typing.Any]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.state","title":"state property","text":"
state: State\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.url","title":"url property","text":"
url: URL\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.user","title":"user property","text":"
user: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.body","title":"body async","text":"
body() -> bytes\n
Source code in starlette/requests.py
async def body(self) -> bytes:\n    if not hasattr(self, \"_body\"):\n        chunks: \"typing.List[bytes]\" = []\n        async for chunk in self.stream():\n            chunks.append(chunk)\n        self._body = b\"\".join(chunks)\n    return self._body\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.close","title":"close async","text":"
close() -> None\n
Source code in starlette/requests.py
async def close(self) -> None:\n    if self._form is not None:\n        await self._form.close()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.form","title":"form","text":"
form(\n    *,\n    max_files: typing.Union[int, float] = 1000,\n    max_fields: typing.Union[int, float] = 1000\n) -> AwaitableOrContextManager[FormData]\n
Source code in starlette/requests.py
def form(\n    self,\n    *,\n    max_files: typing.Union[int, float] = 1000,\n    max_fields: typing.Union[int, float] = 1000,\n) -> AwaitableOrContextManager[FormData]:\n    return AwaitableOrContextManagerWrapper(\n        self._get_form(max_files=max_files, max_fields=max_fields)\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.get_session","title":"get_session classmethod","text":"
get_session(\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[\n    [NativeMessage[Any]], Awaitable[SendableMessage]\n]\n

Creates a session for handling requests.

PARAMETER DESCRIPTION dependant

The dependant object representing the session.

TYPE: Dependant

dependency_overrides_provider

Optional provider for dependency overrides.

TYPE: Optional[Any] DEFAULT: None

RETURNS DESCRIPTION Callable[[StreamMessage[Any]], Awaitable[SendableMessage]]

A callable that takes a native message and returns an awaitable sendable message.

RAISES DESCRIPTION AssertionError

If the dependant call is not defined.

Note

This function is used to create a session for handling requests. It takes a dependant object, which represents the session, and a dependency overrides provider, which allows for overriding dependencies. It returns a callable that takes a native message and returns an awaitable sendable message. The session is created based on the dependant object and the message passed to the callable. The session is then used to call the function obtained from the dependant object, and the result is returned.

Source code in faststream/broker/fastapi/route.py
@classmethod\ndef get_session(\n    cls,\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[[NativeMessage[Any]], Awaitable[SendableMessage]]:\n    \"\"\"Creates a session for handling requests.\n\n    Args:\n        dependant: The dependant object representing the session.\n        dependency_overrides_provider: Optional provider for dependency overrides.\n\n    Returns:\n        A callable that takes a native message and returns an awaitable sendable message.\n\n    Raises:\n        AssertionError: If the dependant call is not defined.\n\n    Note:\n        This function is used to create a session for handling requests. It takes a dependant object, which represents the session, and a dependency overrides provider, which allows for overriding dependencies. It returns a callable that takes a native message and returns an awaitable sendable message. The session is created based on the dependant object and the message passed to the callable. The session is then used to call the function obtained from the dependant object, and the result is returned.\n\n    \"\"\"\n    assert dependant.call  # nosec B101\n\n    func = get_app(dependant, dependency_overrides_provider)\n\n    dependencies_names = tuple(i.name for i in dependant.dependencies)\n\n    first_arg = next(\n        dropwhile(\n            lambda i: i in dependencies_names,\n            inspect.signature(dependant.call).parameters,\n        ),\n        None,\n    )\n\n    async def app(message: NativeMessage[Any]) -> SendableMessage:\n        \"\"\"An asynchronous function that processes an incoming message and returns a sendable message.\n\n        Args:\n            message : The incoming message to be processed\n\n        Returns:\n            The sendable message\n\n        Raises:\n            TypeError: If the body of the message is not a dictionary\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        body = message.decoded_body\n\n        fastapi_body: Union[AnyDict, List[Any]]\n        if first_arg is not None:\n            if isinstance(body, dict):\n                path = fastapi_body = body or {}\n            elif isinstance(body, list):\n                fastapi_body, path = body, {}\n            else:\n                path = fastapi_body = {first_arg: body}\n\n            session = cls(\n                body=fastapi_body,\n                headers=message.headers,\n                path={**path, **message.path},\n            )\n\n        else:\n            session = cls(\n                body={},\n                headers={},\n                path={},\n            )\n\n        return await func(session)\n\n    return app\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.is_disconnected","title":"is_disconnected async","text":"
is_disconnected() -> bool\n
Source code in starlette/requests.py
async def is_disconnected(self) -> bool:\n    if not self._is_disconnected:\n        message: Message = {}\n\n        # If message isn't immediately available, move on\n        with anyio.CancelScope() as cs:\n            cs.cancel()\n            message = await self._receive()\n\n        if message.get(\"type\") == \"http.disconnect\":\n            self._is_disconnected = True\n\n    return self._is_disconnected\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.json","title":"json async","text":"
json() -> typing.Any\n
Source code in starlette/requests.py
async def json(self) -> typing.Any:\n    if not hasattr(self, \"_json\"):\n        body = await self.body()\n        self._json = json.loads(body)\n    return self._json\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.send_push_promise","title":"send_push_promise async","text":"
send_push_promise(path: str) -> None\n
Source code in starlette/requests.py
async def send_push_promise(self, path: str) -> None:\n    if \"http.response.push\" in self.scope.get(\"extensions\", {}):\n        raw_headers: \"typing.List[typing.Tuple[bytes, bytes]]\" = []\n        for name in SERVER_PUSH_HEADERS_TO_COPY:\n            for value in self.headers.getlist(name):\n                raw_headers.append(\n                    (name.encode(\"latin-1\"), value.encode(\"latin-1\"))\n                )\n        await self._send(\n            {\"type\": \"http.response.push\", \"path\": path, \"headers\": raw_headers}\n        )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.stream","title":"stream async","text":"
stream() -> typing.AsyncGenerator[bytes, None]\n
Source code in starlette/requests.py
async def stream(self) -> typing.AsyncGenerator[bytes, None]:\n    if hasattr(self, \"_body\"):\n        yield self._body\n        yield b\"\"\n        return\n    if self._stream_consumed:\n        raise RuntimeError(\"Stream consumed\")\n    self._stream_consumed = True\n    while True:\n        message = await self._receive()\n        if message[\"type\"] == \"http.request\":\n            body = message.get(\"body\", b\"\")\n            if body:\n                yield body\n            if not message.get(\"more_body\", False):\n                break\n        elif message[\"type\"] == \"http.disconnect\":\n            self._is_disconnected = True\n            raise ClientDisconnect()\n    yield b\"\"\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.url_for","title":"url_for","text":"
url_for(__name: str, **path_params: typing.Any) -> URL\n
Source code in starlette/requests.py
def url_for(self, __name: str, **path_params: typing.Any) -> URL:\n    router: Router = self.scope[\"router\"]\n    url_path = router.url_path_for(__name, **path_params)\n    return url_path.make_absolute_url(base_url=self.base_url)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/","title":"StreamRoute","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute","title":"faststream.broker.fastapi.route.StreamRoute","text":"
StreamRoute(\n    path: Union[NameRequired, str, None],\n    *extra: Union[NameRequired, str],\n    endpoint: Union[\n        Callable[P_HandlerParams, T_HandlerReturn],\n        HandlerCallWrapper[\n            MsgType, P_HandlerParams, T_HandlerReturn\n        ],\n    ],\n    broker: BrokerAsyncUsecase[MsgType, Any],\n    dependencies: Sequence[params.Depends] = (),\n    dependency_overrides_provider: Optional[Any] = None,\n    **handle_kwargs: Any\n)\n

Bases: BaseRoute, Generic[MsgType, P_HandlerParams, T_HandlerReturn]

A class representing a stream route.

Initialize a class instance.

PARAMETER DESCRIPTION path

The path of the instance.

TYPE: Union[NameRequired, str, None]

*extra

Additional arguments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint of the instance.

TYPE: Union[Callable[P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

broker

The broker of the instance.

TYPE: BrokerAsyncUsecase[MsgType, Any]

dependencies

The dependencies of the instance.

TYPE: Sequence[Depends] DEFAULT: ()

dependency_overrides_provider

The provider for dependency overrides.

TYPE: Optional[Any] DEFAULT: None

**handle_kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None.

Source code in faststream/broker/fastapi/route.py
def __init__(\n    self,\n    path: Union[NameRequired, str, None],\n    *extra: Union[NameRequired, str],\n    endpoint: Union[\n        Callable[P_HandlerParams, T_HandlerReturn],\n        HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n    ],\n    broker: BrokerAsyncUsecase[MsgType, Any],\n    dependencies: Sequence[params.Depends] = (),\n    dependency_overrides_provider: Optional[Any] = None,\n    **handle_kwargs: Any,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        path: The path of the instance.\n        *extra: Additional arguments.\n        endpoint: The endpoint of the instance.\n        broker: The broker of the instance.\n        dependencies: The dependencies of the instance.\n        dependency_overrides_provider: The provider for dependency overrides.\n        **handle_kwargs: Additional keyword arguments.\n\n    Returns:\n        None.\n\n    \"\"\"\n    self.path = path or \"\"\n    self.broker = broker\n\n    path_name = self.path if isinstance(self.path, str) else self.path.name\n\n    if isinstance(endpoint, HandlerCallWrapper):\n        orig_call = endpoint._original_call\n    else:\n        orig_call = endpoint\n\n    dependant = get_dependant(\n        path=path_name,\n        call=orig_call,\n    )\n    for depends in dependencies[::-1]:\n        dependant.dependencies.insert(\n            0,\n            get_parameterless_sub_dependant(depends=depends, path=path_name),\n        )\n    self.dependant = dependant\n\n    call = wraps(orig_call)(\n        StreamMessage.get_session(\n            dependant,\n            dependency_overrides_provider,\n        )\n    )\n\n    if isinstance(endpoint, HandlerCallWrapper):\n        endpoint._original_call = call\n        handler = endpoint\n\n    else:\n        handler = call\n\n    self.handler = broker.subscriber(\n        path,\n        *extra,\n        _raw=True,\n        _get_dependant=lambda call: dependant,\n        **handle_kwargs,\n    )(\n        handler  # type: ignore[arg-type]\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.dependant","title":"dependant instance-attribute","text":"
dependant = dependant\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.handler","title":"handler instance-attribute","text":"
handler: HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n] = broker.subscriber(\n    path,\n    *extra,\n    _raw=True,\n    _get_dependant=lambda: dependant,\n    **handle_kwargs\n)(\n    handler\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.path","title":"path instance-attribute","text":"
path = path or ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.handle","title":"handle async","text":"
handle(scope: Scope, receive: Receive, send: Send) -> None\n
Source code in starlette/routing.py
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.matches","title":"matches","text":"
matches(scope: Scope) -> typing.Tuple[Match, Scope]\n
Source code in starlette/routing.py
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/get_app/","title":"get_app","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/route/get_app/#faststream.broker.fastapi.route.get_app","title":"faststream.broker.fastapi.route.get_app","text":"
get_app(\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[\n    [StreamMessage], Coroutine[Any, Any, SendableMessage]\n]\n

Creates a FastAPI application.

PARAMETER DESCRIPTION dependant

The dependant object that defines the endpoint function and its dependencies.

TYPE: Dependant

dependency_overrides_provider

Optional provider for dependency overrides.

TYPE: Optional[Any] DEFAULT: None

RETURNS DESCRIPTION Callable[[StreamMessage], Coroutine[Any, Any, SendableMessage]]

The FastAPI application as a callable that takes a StreamMessage object as input and returns a SendableMessage coroutine.

RAISES DESCRIPTION AssertionError

If the code reaches an unreachable state.

Source code in faststream/broker/fastapi/route.py
def get_app(\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[[StreamMessage], Coroutine[Any, Any, SendableMessage]]:\n    \"\"\"Creates a FastAPI application.\n\n    Args:\n        dependant: The dependant object that defines the endpoint function and its dependencies.\n        dependency_overrides_provider: Optional provider for dependency overrides.\n\n    Returns:\n        The FastAPI application as a callable that takes a StreamMessage object as input and returns a SendableMessage coroutine.\n\n    Raises:\n        AssertionError: If the code reaches an unreachable state.\n\n    \"\"\"\n\n    async def app(request: StreamMessage) -> SendableMessage:\n        \"\"\"Handle an HTTP request and return a response.\n\n        Args:\n            request: The incoming HTTP request.\n\n        Returns:\n            The response to be sent back to the client.\n\n        Raises:\n            AssertionError: If the code reaches an unreachable point.\n\n        \"\"\"\n        async with AsyncExitStack() as stack:\n            request.scope[\"fastapi_astack\"] = stack\n\n            solved_result = await solve_dependencies(\n                request=request,\n                body=request._body,\n                dependant=dependant,\n                dependency_overrides_provider=dependency_overrides_provider,\n            )\n\n            values, errors, _, _2, _3 = solved_result\n            if errors:\n                raise_fastapi_validation_error(errors, request._body)\n\n            return cast(\n                SendableMessage,\n                await run_endpoint_function(\n                    dependant=dependant,\n                    values=values,\n                    is_coroutine=asyncio.iscoroutinefunction(dependant.call),\n                ),\n            )\n\n        raise AssertionError(\"unreachable\")\n\n    return app\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/","title":"StreamRouter","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter","title":"faststream.broker.fastapi.router.StreamRouter","text":"
StreamRouter(\n    *connection_args: Tuple[Any, ...],\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    setup_state: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id),\n    asyncapi_tags: Optional[\n        Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]\n    ] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    **connection_kwars: Any\n)\n

Bases: APIRouter, Generic[MsgType]

A class to route streams.

METHOD DESCRIPTION __init__

initialize the StreamRouter

add_api_mq_route

add a route for API and message queue

subscriber

decorator to define a subscriber

wrap_lifespan

wrap the lifespan of the router

after_startup

decorator to define a function to be executed after startup

publisher

create a publisher for the broker

asyncapi_router

create an APIRouter for AsyncAPI documentation

include_router

include another router in the StreamRouter

_setup_log_context

setup log context for the broker

Initialize an instance of a class.

PARAMETER DESCRIPTION *connection_args

Variable length arguments for the connection

TYPE: Tuple[Any, ...] DEFAULT: ()

prefix

Prefix for the class

TYPE: str DEFAULT: ''

tags

Optional list of tags for the class

TYPE: Optional[List[Union[str, Enum]]] DEFAULT: None

dependencies

Optional sequence of dependencies for the class

TYPE: Optional[Sequence[Depends]] DEFAULT: None

default_response_class

Default response class for the class

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

Optional dictionary of responses for the class

TYPE: Optional[Dict[Union[int, str], AnyDict]] DEFAULT: None

callbacks

Optional list of callbacks for the class

TYPE: Optional[List[BaseRoute]] DEFAULT: None

routes

Optional list of routes for the class

TYPE: Optional[List[BaseRoute]] DEFAULT: None

redirect_slashes

Boolean value indicating whether to redirect slashes

TYPE: bool DEFAULT: True

default

Optional default value for the class

TYPE: Optional[ASGIApp] DEFAULT: None

dependency_overrides_provider

Optional provider for dependency overrides

TYPE: Optional[Any] DEFAULT: None

route_class

Route class for the class

TYPE: Type[APIRoute] DEFAULT: APIRoute

on_startup

Optional sequence of functions to run on startup

TYPE: Optional[Sequence[Callable[[], Any]]] DEFAULT: None

on_shutdown

Optional sequence of functions to run on shutdown

TYPE: Optional[Sequence[Callable[[], Any]]] DEFAULT: None

deprecated

Optional boolean value indicating whether the class is deprecated

TYPE: Optional[bool] DEFAULT: None

include_in_schema

Boolean value indicating whether to include the class in the schema

TYPE: bool DEFAULT: True

setup_state

Boolean value indicating whether to setup state

TYPE: bool DEFAULT: True

lifespan

Optional lifespan for the class

TYPE: Optional[Lifespan[Any]] DEFAULT: None

generate_unique_id_function

Function to generate unique ID for the class

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

asyncapi_tags

Optional sequence of asyncapi tags for the class schema

TYPE: Optional[Sequence[Union[Tag, TagDict]]] DEFAULT: None

Source code in faststream/broker/fastapi/router.py
def __init__(\n    self,\n    *connection_args: Tuple[Any, ...],\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[Sequence[Callable[[], Any]]] = None,\n    on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    setup_state: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n    # AsyncAPI information\n    asyncapi_tags: Optional[Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    **connection_kwars: Any,\n) -> None:\n    \"\"\"Initialize an instance of a class.\n\n    Args:\n        *connection_args: Variable length arguments for the connection\n        prefix: Prefix for the class\n        tags: Optional list of tags for the class\n        dependencies: Optional sequence of dependencies for the class\n        default_response_class: Default response class for the class\n        responses: Optional dictionary of responses for the class\n        callbacks: Optional list of callbacks for the class\n        routes: Optional list of routes for the class\n        redirect_slashes: Boolean value indicating whether to redirect slashes\n        default: Optional default value for the class\n        dependency_overrides_provider: Optional provider for dependency overrides\n        route_class: Route class for the class\n        on_startup: Optional sequence of functions to run on startup\n        on_shutdown: Optional sequence of functions to run on shutdown\n        deprecated: Optional boolean value indicating whether the class is deprecated\n        include_in_schema: Boolean value indicating whether to include the class in the schema\n        setup_state: Boolean value indicating whether to setup state\n        lifespan: Optional lifespan for the class\n        generate_unique_id_function: Function to generate unique ID for the class\n        asyncapi_tags: Optional sequence of asyncapi tags for the class schema\n\n    \"\"\"\n    assert (  # nosec B101\n        self.broker_class\n    ), \"You should specify `broker_class` at your implementation\"\n\n    self.broker = self.broker_class(\n        *connection_args,\n        apply_types=False,\n        tags=asyncapi_tags,\n        **connection_kwars,\n    )\n\n    self.setup_state = setup_state\n\n    # AsyncAPI information\n    # Empty\n    self.terms_of_service = None\n    self.identifier = None\n    self.asyncapi_tags = None\n    self.external_docs = None\n    # parse from FastAPI app on startup\n    self.title = \"\"\n    self.version = \"\"\n    self.description = \"\"\n    self.license = None\n    self.contact = None\n\n    self.schema = None\n\n    super().__init__(\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        routes=routes,\n        redirect_slashes=redirect_slashes,\n        default=default,\n        dependency_overrides_provider=dependency_overrides_provider,\n        route_class=route_class,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n        lifespan=self.wrap_lifespan(lifespan),\n        on_startup=on_startup,\n        on_shutdown=on_shutdown,\n    )\n\n    self.docs_router = self.asyncapi_router(schema_url)\n\n    self._after_startup_hooks = []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.broker","title":"broker instance-attribute","text":"
broker: BrokerAsyncUsecase[\n    MsgType, Any\n] = self.broker_class(\n    *connection_args,\n    apply_types=False,\n    tags=asyncapi_tags,\n    **connection_kwars\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.broker_class","title":"broker_class instance-attribute","text":"
broker_class: Type[BrokerAsyncUsecase[MsgType, Any]]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any\n) -> HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n]\n

Add an API message queue route.

PARAMETER DESCRIPTION path

The path of the route.

TYPE: Union[NameRequired, str]

*extra

Additional path segments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint function to be called for this route.

TYPE: Callable[P_HandlerParams, T_HandlerReturn]

dependencies

The dependencies required by the endpoint function.

TYPE: Sequence[Depends]

**broker_kwargs

Additional keyword arguments to be passed to the broker.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]

The handler call wrapper for the route.

Source code in faststream/broker/fastapi/router.py
def add_api_mq_route(\n    self,\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any,\n) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n    \"\"\"Add an API message queue route.\n\n    Args:\n        path: The path of the route.\n        *extra: Additional path segments.\n        endpoint: The endpoint function to be called for this route.\n        dependencies: The dependencies required by the endpoint function.\n        **broker_kwargs: Additional keyword arguments to be passed to the broker.\n\n    Returns:\n        The handler call wrapper for the route.\n\n    \"\"\"\n    route: StreamRoute[MsgType, P_HandlerParams, T_HandlerReturn] = StreamRoute(\n        path,\n        *extra,\n        endpoint=endpoint,\n        dependencies=dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        broker=self.broker,\n        **broker_kwargs,\n    )\n    self.routes.append(route)\n    return route.handler\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.publisher","title":"publisher","text":"
publisher(\n    queue: Union[NameRequired, str],\n    *publisher_args: Any,\n    **publisher_kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes messages to a queue.

PARAMETER DESCRIPTION queue

The queue to publish the messages to. Can be either a NameRequired object or a string.

TYPE: Union[NameRequired, str]

*publisher_args

Additional arguments to be passed to the publisher.

TYPE: Any DEFAULT: ()

**publisher_kwargs

Additional keyword arguments to be passed to the publisher.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

An instance of BasePublisher that can be used to publish messages to the specified queue.

Source code in faststream/broker/fastapi/router.py
def publisher(\n    self,\n    queue: Union[NameRequired, str],\n    *publisher_args: Any,\n    **publisher_kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes messages to a queue.\n\n    Args:\n        queue: The queue to publish the messages to. Can be either a `NameRequired` object or a string.\n        *publisher_args: Additional arguments to be passed to the publisher.\n        **publisher_kwargs: Additional keyword arguments to be passed to the publisher.\n\n    Returns:\n        An instance of `BasePublisher` that can be used to publish messages to the specified queue.\n\n    \"\"\"\n    return self.broker.publisher(\n        queue,\n        *publisher_args,\n        **publisher_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.subscriber","title":"subscriber","text":"
subscriber(\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function decorator for subscribing to a message queue.

PARAMETER DESCRIPTION path

The path to subscribe to. Can be a string or a NameRequired object.

*extra

Additional path segments. Can be a NameRequired object or a string.

DEFAULT: ()

dependencies

Optional sequence of dependencies.

DEFAULT: None

**broker_kwargs

Additional keyword arguments for the broker.

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable decorator that adds the decorated function as an endpoint for the specified path.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def subscriber(\n    self,\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function decorator for subscribing to a message queue.\n\n    Args:\n        path : The path to subscribe to. Can be a string or a `NameRequired` object.\n        *extra : Additional path segments. Can be a `NameRequired` object or a string.\n        dependencies : Optional sequence of dependencies.\n        **broker_kwargs : Additional keyword arguments for the broker.\n\n    Returns:\n        A callable decorator that adds the decorated function as an endpoint for the specified path.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    def decorator(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n        \"\"\"A decorator function.\n\n        Args:\n            func: The function to be decorated.\n\n        Returns:\n            The decorated function.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        return self.add_api_mq_route(\n            path,\n            *extra,\n            endpoint=func,\n            dependencies=current_dependencies,\n            **broker_kwargs,\n        )\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/","title":"AsyncHandler","text":"","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler","title":"faststream.broker.handler.AsyncHandler","text":"
AsyncHandler(\n    *,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    graceful_timeout: Optional[float] = None\n)\n

Bases: BaseHandler[MsgType]

A class representing an asynchronous handler.

METHOD DESCRIPTION add_call

adds a new call to the list of calls

consume

consumes a message and returns a sendable message

start

starts the handler

close

closes the handler

Source code in faststream/broker/handler.py
def __init__(\n    self,\n    *,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    graceful_timeout: Optional[float] = None,\n) -> None:\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n    )\n    self.lock = MultiLock()\n    self.graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n    parser: CustomParser[MsgType, Any],\n    decoder: CustomDecoder[Any],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    filter: Filter[StreamMessage[MsgType]],\n    middlewares: Optional[\n        Sequence[Callable[[Any], BaseMiddleware]]\n    ]\n) -> None\n

Adds a call to the handler.

PARAMETER DESCRIPTION handler

The handler call wrapper.

TYPE: HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]

parser

The custom parser.

TYPE: CustomParser[MsgType, Any]

decoder

The custom decoder.

TYPE: CustomDecoder[Any]

dependant

The call model.

TYPE: CallModel[P_HandlerParams, T_HandlerReturn]

filter

The filter for stream messages.

TYPE: Filter[StreamMessage[MsgType]]

middlewares

Optional sequence of middlewares.

TYPE: Optional[Sequence[Callable[[Any], BaseMiddleware]]]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n    parser: CustomParser[MsgType, Any],\n    decoder: CustomDecoder[Any],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    filter: Filter[StreamMessage[MsgType]],\n    middlewares: Optional[Sequence[Callable[[Any], BaseMiddleware]]],\n) -> None:\n    \"\"\"Adds a call to the handler.\n\n    Args:\n        handler: The handler call wrapper.\n        parser: The custom parser.\n        decoder: The custom decoder.\n        dependant: The call model.\n        filter: The filter for stream messages.\n        middlewares: Optional sequence of middlewares.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.calls.append(\n        (\n            handler,\n            to_async(filter),\n            to_async(parser) if parser else None,  # type: ignore[arg-type]\n            to_async(decoder) if decoder else None,  # type: ignore[arg-type]\n            middlewares or (),\n            dependant,\n        )\n    )\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.close","title":"close abstractmethod async","text":"
close() -> None\n
Source code in faststream/broker/handler.py
@abstractmethod\nasync def close(self) -> None:\n    self.running = False\n    await self.lock.wait_release(self.graceful_timeout)\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.start","title":"start abstractmethod async","text":"
start() -> None\n
Source code in faststream/broker/handler.py
@abstractmethod\nasync def start(self) -> None:\n    self.running = True\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/","title":"BaseHandler","text":"","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler","title":"faststream.broker.handler.BaseHandler","text":"
BaseHandler(\n    *,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True\n)\n

Bases: AsyncAPIOperation, Generic[MsgType]

A base handler class for asynchronous API operations.

METHOD DESCRIPTION __init__

Initializes the BaseHandler object.

name

Returns the name of the handler.

call_name

Returns the name of the handler call.

description

Returns the description of the handler.

consume

Abstract method to consume a message.

Note: This class inherits from AsyncAPIOperation and is a generic class with type parameter MsgType.

Initialize a new instance of the class.

PARAMETER DESCRIPTION description

Optional description of the instance.

TYPE: Optional[str] DEFAULT: None

title

Optional title of the instance.

TYPE: Optional[str] DEFAULT: None

Source code in faststream/broker/handler.py
def __init__(\n    self,\n    *,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    \"\"\"Initialize a new instance of the class.\n\n    Args:\n        description: Optional description of the instance.\n        title: Optional title of the instance.\n\n    \"\"\"\n    self.calls = []  # type: ignore[assignment]\n    self.global_middlewares = []\n\n    self.log_context_builder = log_context_builder\n    self.running = False\n\n    # AsyncAPI information\n    self._description = description\n    self._title = title\n    self.include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.calls","title":"calls instance-attribute","text":"
calls: Union[\n    List[\n        Tuple[\n            HandlerCallWrapper[\n                MsgType, Any, SendableMessage\n            ],\n            Callable[[StreamMessage[MsgType]], bool],\n            SyncParser[MsgType, StreamMessage[MsgType]],\n            SyncDecoder[StreamMessage[MsgType]],\n            Sequence[Callable[[Any], BaseMiddleware]],\n            CallModel[Any, SendableMessage],\n        ]\n    ],\n    List[\n        Tuple[\n            HandlerCallWrapper[\n                MsgType, Any, SendableMessage\n            ],\n            Callable[\n                [StreamMessage[MsgType]], Awaitable[bool]\n            ],\n            AsyncParser[MsgType, StreamMessage[MsgType]],\n            AsyncDecoder[StreamMessage[MsgType]],\n            Sequence[Callable[[Any], BaseMiddleware]],\n            CallModel[Any, SendableMessage],\n        ]\n    ],\n] = []\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.consume","title":"consume abstractmethod","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/handler.py
@abstractmethod\ndef consume(self, msg: MsgType) -> SendableMessage:\n    \"\"\"Consume a message.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/","title":"MultiLock","text":"","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/#faststream.broker.handler.MultiLock","title":"faststream.broker.handler.MultiLock","text":"
MultiLock()\n
Source code in faststream/broker/handler.py
def __init__(self) -> None:\n    self.queue: \"asyncio.Queue[None]\" = asyncio.Queue()\n
","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/#faststream.broker.handler.MultiLock.empty","title":"empty property","text":"
empty: bool\n
","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/#faststream.broker.handler.MultiLock.qsize","title":"qsize property","text":"
qsize: int\n
","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/#faststream.broker.handler.MultiLock.queue","title":"queue instance-attribute","text":"
queue: asyncio.Queue[None] = asyncio.Queue()\n
","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/#faststream.broker.handler.MultiLock.wait_release","title":"wait_release async","text":"
wait_release(timeout: Optional[float] = None) -> None\n
Source code in faststream/broker/handler.py
async def wait_release(self, timeout: Optional[float] = None) -> None:\n    if timeout:\n        with anyio.move_on_after(timeout):\n            await self.queue.join()\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/","title":"ABCStreamMessage","text":"","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage","title":"faststream.broker.message.ABCStreamMessage dataclass","text":"

Bases: Generic[Msg]

A generic class to represent a stream message.

","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/","title":"StreamMessage","text":"","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage","title":"faststream.broker.message.StreamMessage","text":"

Bases: ABCStreamMessage[Msg]

","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.ack","title":"ack async","text":"
ack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def ack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.nack","title":"nack async","text":"
nack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def nack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.reject","title":"reject async","text":"
reject(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def reject(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/","title":"SyncStreamMessage","text":"","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage","title":"faststream.broker.message.SyncStreamMessage","text":"

Bases: ABCStreamMessage[Msg]

","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.ack","title":"ack","text":"
ack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
def ack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.nack","title":"nack","text":"
nack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
def nack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.reject","title":"reject","text":"
reject(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
def reject(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/","title":"BaseMiddleware","text":"","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware","title":"faststream.broker.middlewares.BaseMiddleware","text":"
BaseMiddleware(msg: Any)\n

A base middleware class.

METHOD DESCRIPTION on_receive

Called when a message is received.

after_processed

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) -> Optional[bool]: Called after processing a message.

__aenter__

Called when entering a context.

__aexit__

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) -> Optional[bool]: Called when exiting a context.

on_consume

DecodedMessage) -> DecodedMessage: Called before consuming a message.

after_consume

Optional[Exception]) -> None: Called after consuming a message.

consume_scope

DecodedMessage) -> AsyncIterator[DecodedMessage]: Context manager for consuming a message.

on_publish

SendableMessage) -> SendableMessage: Called before publishing a message.

after_publish

Optional[Exception]) -> None: Asynchronous function to handle the after publish event.

Initialize the class.

PARAMETER DESCRIPTION msg

Any message to be stored.

TYPE: Any

Source code in faststream/broker/middlewares.py
def __init__(self, msg: Any) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        msg: Any message to be stored.\n    \"\"\"\n    self.msg = msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.msg","title":"msg instance-attribute","text":"
msg = msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.after_consume","title":"after_consume async","text":"
after_consume(err: Optional[Exception]) -> None\n

A function to handle the result of consuming a resource asynchronously.

PARAMETER DESCRIPTION err

Optional exception that occurred during consumption

RAISES DESCRIPTION err

If an exception occurred during consumption

Source code in faststream/broker/middlewares.py
async def after_consume(self, err: Optional[Exception]) -> None:\n    \"\"\"A function to handle the result of consuming a resource asynchronously.\n\n    Args:\n        err : Optional exception that occurred during consumption\n\n    Raises:\n        err : If an exception occurred during consumption\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.after_processed","title":"after_processed async","text":"
after_processed(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> Optional[bool]\n

Asynchronously called after processing.

PARAMETER DESCRIPTION exc_type

Optional exception type

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

Optional exception value

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

Optional traceback

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION Optional[bool]

Optional boolean value indicating whether the processing was successful or not.

Source code in faststream/broker/middlewares.py
async def after_processed(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> Optional[bool]:\n    \"\"\"Asynchronously called after processing.\n\n    Args:\n        exc_type: Optional exception type\n        exc_val: Optional exception value\n        exec_tb: Optional traceback\n\n    Returns:\n        Optional boolean value indicating whether the processing was successful or not.\n    \"\"\"\n    return False\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.after_publish","title":"after_publish async","text":"
after_publish(err: Optional[Exception]) -> None\n

Asynchronous function to handle the after publish event.

PARAMETER DESCRIPTION err

Optional exception that occurred during the publish

TYPE: Optional[Exception]

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION Exception

If an error occurred during the publish

Source code in faststream/broker/middlewares.py
async def after_publish(self, err: Optional[Exception]) -> None:\n    \"\"\"Asynchronous function to handle the after publish event.\n\n    Args:\n        err: Optional exception that occurred during the publish\n\n    Returns:\n        None\n\n    Raises:\n        Exception: If an error occurred during the publish\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.consume_scope","title":"consume_scope async","text":"
consume_scope(\n    msg: DecodedMessage,\n) -> AsyncIterator[DecodedMessage]\n

Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.

PARAMETER DESCRIPTION msg

The decoded message to consume.

TYPE: DecodedMessage

YIELDS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RETURNS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RAISES DESCRIPTION Exception

If an error occurs while consuming the message.

AsyncIterator

An asynchronous iterator that yields decoded messages.

Note

This function is an async function.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def consume_scope(self, msg: DecodedMessage) -> AsyncIterator[DecodedMessage]:\n    \"\"\"Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.\n\n    Args:\n        msg: The decoded message to consume.\n\n    Yields:\n        An asynchronous iterator of decoded messages.\n\n    Returns:\n        An asynchronous iterator of decoded messages.\n\n    Raises:\n        Exception: If an error occurs while consuming the message.\n\n    AsyncIterator:\n        An asynchronous iterator that yields decoded messages.\n\n    Note:\n        This function is an async function.\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_consume(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_consume(err)\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.on_consume","title":"on_consume async","text":"
on_consume(msg: DecodedMessage) -> DecodedMessage\n

Asynchronously consumes a message.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: DecodedMessage

RETURNS DESCRIPTION DecodedMessage

The consumed message.

Source code in faststream/broker/middlewares.py
async def on_consume(self, msg: DecodedMessage) -> DecodedMessage:\n    \"\"\"Asynchronously consumes a message.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The consumed message.\n    \"\"\"\n    return msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.on_publish","title":"on_publish async","text":"
on_publish(msg: SendableMessage) -> SendableMessage\n

Asynchronously handle a publish event.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

RETURNS DESCRIPTION SendableMessage

The published message.

Source code in faststream/broker/middlewares.py
async def on_publish(self, msg: SendableMessage) -> SendableMessage:\n    \"\"\"Asynchronously handle a publish event.\n\n    Args:\n        msg: The message to be published.\n\n    Returns:\n        The published message.\n    \"\"\"\n    return msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.on_receive","title":"on_receive async","text":"
on_receive() -> None\n
Source code in faststream/broker/middlewares.py
async def on_receive(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.publish_scope","title":"publish_scope async","text":"
publish_scope(\n    msg: SendableMessage,\n) -> AsyncIterator[SendableMessage]\n

Publish a message and return an async iterator.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

YIELDS DESCRIPTION AsyncIterator[SendableMessage]

A sendable message.

RETURNS DESCRIPTION AsyncIterator[SendableMessage]

An async iterator of sendable messages.

RAISES DESCRIPTION Exception

If an error occurs during publishing.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def publish_scope(\n    self, msg: SendableMessage\n) -> AsyncIterator[SendableMessage]:\n    \"\"\"Publish a message and return an async iterator.\n\n    Args:\n        msg: The message to be published.\n\n    Yields:\n        A sendable message.\n\n    Returns:\n        An async iterator of sendable messages.\n\n    Raises:\n        Exception: If an error occurs during publishing.\n\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_publish(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_publish(err)\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/","title":"CriticalLogMiddleware","text":"","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware","title":"faststream.broker.middlewares.CriticalLogMiddleware","text":"
CriticalLogMiddleware(\n    logger: Optional[logging.Logger], log_level: int\n)\n

Bases: BaseMiddleware

A middleware class for logging critical errors.

PARAMETER DESCRIPTION logger

The logger object to use for logging

TYPE: Optional[Logger]

METHOD DESCRIPTION __call__

Any) -> Self: Returns the middleware instance

after_processed

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) -> bool: Logs critical errors if they occur and returns True

Initialize the class.

PARAMETER DESCRIPTION logger

an instance of the logging.Logger class

TYPE: Optional[Logger]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/middlewares.py
def __init__(\n    self,\n    logger: Optional[logging.Logger],\n    log_level: int,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        logger: an instance of the logging.Logger class\n\n    Returns:\n        None\n    \"\"\"\n    self.logger = logger\n    self.log_level = log_level\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.msg","title":"msg instance-attribute","text":"
msg = msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.after_consume","title":"after_consume async","text":"
after_consume(err: Optional[Exception]) -> None\n

A function to handle the result of consuming a resource asynchronously.

PARAMETER DESCRIPTION err

Optional exception that occurred during consumption

RAISES DESCRIPTION err

If an exception occurred during consumption

Source code in faststream/broker/middlewares.py
async def after_consume(self, err: Optional[Exception]) -> None:\n    \"\"\"A function to handle the result of consuming a resource asynchronously.\n\n    Args:\n        err : Optional exception that occurred during consumption\n\n    Raises:\n        err : If an exception occurred during consumption\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.after_processed","title":"after_processed async","text":"
after_processed(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> bool\n

Asynchronously called after processing.

PARAMETER DESCRIPTION exc_type

Type of the exception raised during processing.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

Value of the exception raised during processing.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

Traceback of the exception raised during processing.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION bool

True if the method is successfully executed.

TYPE: bool

Source code in faststream/broker/middlewares.py
async def after_processed(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> bool:\n    \"\"\"Asynchronously called after processing.\n\n    Args:\n        exc_type (Optional[Type[BaseException]]): Type of the exception raised during processing.\n        exc_val (Optional[BaseException]): Value of the exception raised during processing.\n        exec_tb (Optional[TracebackType]): Traceback of the exception raised during processing.\n\n    Returns:\n        bool: True if the method is successfully executed.\n    \"\"\"\n    if self.logger is not None:\n        c = context.get_local(\"log_context\")\n\n        if exc_type and exc_val:\n            self.logger.error(\n                f\"{exc_type.__name__}: {exc_val}\",\n                exc_info=exc_val,\n                extra=c,\n            )\n\n        self.logger.log(self.log_level, \"Processed\", extra=c)\n    return True\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.after_publish","title":"after_publish async","text":"
after_publish(err: Optional[Exception]) -> None\n

Asynchronous function to handle the after publish event.

PARAMETER DESCRIPTION err

Optional exception that occurred during the publish

TYPE: Optional[Exception]

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION Exception

If an error occurred during the publish

Source code in faststream/broker/middlewares.py
async def after_publish(self, err: Optional[Exception]) -> None:\n    \"\"\"Asynchronous function to handle the after publish event.\n\n    Args:\n        err: Optional exception that occurred during the publish\n\n    Returns:\n        None\n\n    Raises:\n        Exception: If an error occurred during the publish\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.consume_scope","title":"consume_scope async","text":"
consume_scope(\n    msg: DecodedMessage,\n) -> AsyncIterator[DecodedMessage]\n

Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.

PARAMETER DESCRIPTION msg

The decoded message to consume.

TYPE: DecodedMessage

YIELDS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RETURNS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RAISES DESCRIPTION Exception

If an error occurs while consuming the message.

AsyncIterator

An asynchronous iterator that yields decoded messages.

Note

This function is an async function.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def consume_scope(self, msg: DecodedMessage) -> AsyncIterator[DecodedMessage]:\n    \"\"\"Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.\n\n    Args:\n        msg: The decoded message to consume.\n\n    Yields:\n        An asynchronous iterator of decoded messages.\n\n    Returns:\n        An asynchronous iterator of decoded messages.\n\n    Raises:\n        Exception: If an error occurs while consuming the message.\n\n    AsyncIterator:\n        An asynchronous iterator that yields decoded messages.\n\n    Note:\n        This function is an async function.\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_consume(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_consume(err)\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.on_consume","title":"on_consume async","text":"
on_consume(msg: DecodedMessage) -> DecodedMessage\n
Source code in faststream/broker/middlewares.py
async def on_consume(self, msg: DecodedMessage) -> DecodedMessage:\n    if self.logger is not None:\n        c = context.get_local(\"log_context\")\n        self.logger.log(self.log_level, \"Received\", extra=c)\n\n    return await super().on_consume(msg)\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.on_publish","title":"on_publish async","text":"
on_publish(msg: SendableMessage) -> SendableMessage\n

Asynchronously handle a publish event.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

RETURNS DESCRIPTION SendableMessage

The published message.

Source code in faststream/broker/middlewares.py
async def on_publish(self, msg: SendableMessage) -> SendableMessage:\n    \"\"\"Asynchronously handle a publish event.\n\n    Args:\n        msg: The message to be published.\n\n    Returns:\n        The published message.\n    \"\"\"\n    return msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.on_receive","title":"on_receive async","text":"
on_receive() -> None\n
Source code in faststream/broker/middlewares.py
async def on_receive(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.publish_scope","title":"publish_scope async","text":"
publish_scope(\n    msg: SendableMessage,\n) -> AsyncIterator[SendableMessage]\n

Publish a message and return an async iterator.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

YIELDS DESCRIPTION AsyncIterator[SendableMessage]

A sendable message.

RETURNS DESCRIPTION AsyncIterator[SendableMessage]

An async iterator of sendable messages.

RAISES DESCRIPTION Exception

If an error occurs during publishing.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def publish_scope(\n    self, msg: SendableMessage\n) -> AsyncIterator[SendableMessage]:\n    \"\"\"Publish a message and return an async iterator.\n\n    Args:\n        msg: The message to be published.\n\n    Yields:\n        A sendable message.\n\n    Returns:\n        An async iterator of sendable messages.\n\n    Raises:\n        Exception: If an error occurs during publishing.\n\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_publish(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_publish(err)\n
","boost":0.5},{"location":"api/faststream/broker/parsers/decode_message/","title":"decode_message","text":"","boost":0.5},{"location":"api/faststream/broker/parsers/decode_message/#faststream.broker.parsers.decode_message","title":"faststream.broker.parsers.decode_message","text":"
decode_message(\n    message: StreamMessage[Any],\n) -> DecodedMessage\n

Decodes a message.

PARAMETER DESCRIPTION message

The message to decode.

TYPE: StreamMessage[Any]

RETURNS DESCRIPTION DecodedMessage

The decoded message.

RAISES DESCRIPTION JSONDecodeError

If the message body cannot be decoded as JSON.

Source code in faststream/broker/parsers.py
def decode_message(message: StreamMessage[Any]) -> DecodedMessage:\n    \"\"\"Decodes a message.\n\n    Args:\n        message: The message to decode.\n\n    Returns:\n        The decoded message.\n\n    Raises:\n        JSONDecodeError: If the message body cannot be decoded as JSON.\n\n    \"\"\"\n    body: Any = getattr(message, \"body\", message)\n    m: DecodedMessage = body\n\n    if content_type := getattr(message, \"content_type\", None):\n        if ContentTypes.text.value in content_type:\n            m = body.decode()\n        elif ContentTypes.json.value in content_type:  # pragma: no branch\n            m = json.loads(body)\n\n    else:\n        with suppress(json.JSONDecodeError):\n            m = json.loads(body)\n\n    return m\n
","boost":0.5},{"location":"api/faststream/broker/parsers/encode_message/","title":"encode_message","text":"","boost":0.5},{"location":"api/faststream/broker/parsers/encode_message/#faststream.broker.parsers.encode_message","title":"faststream.broker.parsers.encode_message","text":"
encode_message(\n    msg: SendableMessage,\n) -> Tuple[bytes, Optional[ContentType]]\n

Encodes a message.

PARAMETER DESCRIPTION msg

The message to be encoded.

TYPE: SendableMessage

RETURNS DESCRIPTION Tuple[bytes, Optional[ContentType]]

A tuple containing the encoded message as bytes and the content type of the message.

Source code in faststream/broker/parsers.py
def encode_message(msg: SendableMessage) -> Tuple[bytes, Optional[ContentType]]:\n    \"\"\"Encodes a message.\n\n    Args:\n        msg: The message to be encoded.\n\n    Returns:\n        A tuple containing the encoded message as bytes and the content type of the message.\n\n    \"\"\"\n    if msg is None:\n        return b\"\", None\n\n    if isinstance(msg, bytes):\n        return msg, None\n\n    if isinstance(msg, str):\n        return msg.encode(), ContentTypes.text.value\n\n    return (\n        dump_json(msg).encode(),\n        ContentTypes.json.value,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/parsers/resolve_custom_func/","title":"resolve_custom_func","text":"","boost":0.5},{"location":"api/faststream/broker/parsers/resolve_custom_func/#faststream.broker.parsers.resolve_custom_func","title":"faststream.broker.parsers.resolve_custom_func","text":"
resolve_custom_func(\n    custom_func: Optional[\n        Union[\n            CustomDecoder[StreamMsg],\n            CustomParser[MsgType, StreamMsg],\n        ]\n    ],\n    default_func: Union[\n        Decoder[StreamMsg], Parser[MsgType, StreamMsg]\n    ],\n) -> Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]]\n

Resolve a custom function.

PARAMETER DESCRIPTION custom_func

Optional custom function of type CustomDecoder or CustomParser.

TYPE: Optional[Union[CustomDecoder[StreamMsg], CustomParser[MsgType, StreamMsg]]]

default_func

Default function of type Decoder or Parser.

TYPE: Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]]

RETURNS DESCRIPTION Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]]

The resolved function of type Decoder or Parser.

Source code in faststream/broker/parsers.py
def resolve_custom_func(  # type: ignore[misc]\n    custom_func: Optional[\n        Union[CustomDecoder[StreamMsg], CustomParser[MsgType, StreamMsg]]\n    ],\n    default_func: Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]],\n) -> Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]]:\n    \"\"\"Resolve a custom function.\n\n    Args:\n        custom_func: Optional custom function of type CustomDecoder or CustomParser.\n        default_func: Default function of type Decoder or Parser.\n\n    Returns:\n        The resolved function of type Decoder or Parser.\n\n    \"\"\"\n    if custom_func is None:\n        return default_func\n\n    original_params = inspect.signature(custom_func).parameters\n    if len(original_params) == 1:\n        return cast(Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]], custom_func)\n\n    else:\n        name = tuple(original_params.items())[1][0]\n        return partial(custom_func, **{name: default_func})  # type: ignore\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/","title":"BasePublisher","text":"","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher","title":"faststream.broker.publisher.BasePublisher dataclass","text":"

Bases: AsyncAPIOperation, Generic[MsgType]

A base class for publishers in an asynchronous API.

METHOD DESCRIPTION description

returns the description of the publisher

__call__

decorator to register a function as a handler for the publisher

publish

publishes a message with optional correlation ID

RAISES DESCRIPTION NotImplementedError

if the publish method is not implemented.

","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.publish","title":"publish abstractmethod async","text":"
publish(\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

correlation_id

Optional correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/publisher.py
@abstractmethod\nasync def publish(\n    self,\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        correlation_id: Optional correlation ID for the message.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/","title":"BaseWatcher","text":"","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher","title":"faststream.broker.push_back_watcher.BaseWatcher","text":"
BaseWatcher(\n    max_tries: int = 0, logger: Optional[Logger] = None\n)\n

Bases: ABC

A base class for a watcher.

PARAMETER DESCRIPTION max_tries

maximum number of tries allowed (default=0)

DEFAULT: 0

logger

logger object (optional)

DEFAULT: None

METHOD DESCRIPTION add

add a message to the watcher

is_max

check if the maximum number of tries has been reached for a message

remove

remove a message from the watcher

Initialize the class.

PARAMETER DESCRIPTION max_tries

Maximum number of tries allowed

TYPE: int DEFAULT: 0

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented in the subclass.

Source code in faststream/broker/push_back_watcher.py
def __init__(\n    self,\n    max_tries: int = 0,\n    logger: Optional[Logger] = None,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        max_tries: Maximum number of tries allowed\n        logger: Optional logger object\n\n    Raises:\n        NotImplementedError: If the method is not implemented in the subclass.\n\n    \"\"\"\n    self.logger = logger\n    self.max_tries = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher.max_tries","title":"max_tries instance-attribute","text":"
max_tries: int = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher.add","title":"add abstractmethod","text":"
add(message_id: str) -> None\n

Add a message.

PARAMETER DESCRIPTION message_id

ID of the message to be added

TYPE: str

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/push_back_watcher.py
@abstractmethod\ndef add(self, message_id: str) -> None:\n    \"\"\"Add a message.\n\n    Args:\n        message_id: ID of the message to be added\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher.is_max","title":"is_max abstractmethod","text":"
is_max(message_id: str) -> bool\n

Check if the given message ID is the maximum.

PARAMETER DESCRIPTION message_id

The ID of the message to check.

TYPE: str

RETURNS DESCRIPTION bool

True if the given message ID is the maximum, False otherwise.

RAISES DESCRIPTION NotImplementedError

This method is meant to be overridden by subclasses.

Source code in faststream/broker/push_back_watcher.py
@abstractmethod\ndef is_max(self, message_id: str) -> bool:\n    \"\"\"Check if the given message ID is the maximum.\n\n    Args:\n        message_id: The ID of the message to check.\n\n    Returns:\n        True if the given message ID is the maximum, False otherwise.\n\n    Raises:\n        NotImplementedError: This method is meant to be overridden by subclasses.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher.remove","title":"remove abstractmethod","text":"
remove(message_id: str) -> None\n

Remove a message.

PARAMETER DESCRIPTION message_id

ID of the message to be removed

TYPE: str

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/push_back_watcher.py
@abstractmethod\ndef remove(self, message_id: str) -> None:\n    \"\"\"Remove a message.\n\n    Args:\n        message_id: ID of the message to be removed\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/","title":"CounterWatcher","text":"","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher","title":"faststream.broker.push_back_watcher.CounterWatcher","text":"
CounterWatcher(\n    max_tries: int = 3, logger: Optional[Logger] = None\n)\n

Bases: BaseWatcher

A class to watch and track the count of messages.

PARAMETER DESCRIPTION max_tries

int - maximum number of tries allowed

DEFAULT: 3

logger

Optional[Logger] - logger object for logging messages

DEFAULT: None

METHOD DESCRIPTION add

str) -> None - adds a message to the counter

is_max

str) -> bool - checks if the count of a message has reached the maximum tries

remove

str) -> None - removes a message from the counter

Initialize the class.

PARAMETER DESCRIPTION max_tries

maximum number of tries

TYPE: int DEFAULT: 3

logger

logger object (default: None)

TYPE: Optional[Logger] DEFAULT: None

Source code in faststream/broker/push_back_watcher.py
def __init__(\n    self,\n    max_tries: int = 3,\n    logger: Optional[Logger] = None,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        max_tries (int): maximum number of tries\n        logger (Optional[Logger]): logger object (default: None)\n\n    \"\"\"\n    super().__init__(logger=logger, max_tries=max_tries)\n    self.memory = Counter()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.max_tries","title":"max_tries instance-attribute","text":"
max_tries: int = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.memory","title":"memory instance-attribute","text":"
memory: CounterType[str] = Counter()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.add","title":"add","text":"
add(message_id: str) -> None\n

Increments the count of a message in the memory.

PARAMETER DESCRIPTION message_id

The ID of the message to be incremented.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def add(self, message_id: str) -> None:\n    \"\"\"Increments the count of a message in the memory.\n\n    Args:\n        message_id: The ID of the message to be incremented.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.memory[message_id] += 1\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.is_max","title":"is_max","text":"
is_max(message_id: str) -> bool\n

Check if the number of tries for a message has exceeded the maximum allowed tries.

PARAMETER DESCRIPTION message_id

The ID of the message

TYPE: str

RETURNS DESCRIPTION bool

True if the number of tries has exceeded the maximum allowed tries, False otherwise

Source code in faststream/broker/push_back_watcher.py
def is_max(self, message_id: str) -> bool:\n    \"\"\"Check if the number of tries for a message has exceeded the maximum allowed tries.\n\n    Args:\n        message_id: The ID of the message\n\n    Returns:\n        True if the number of tries has exceeded the maximum allowed tries, False otherwise\n\n    \"\"\"\n    is_max = self.memory[message_id] > self.max_tries\n    if self.logger is not None:\n        if is_max:\n            self.logger.error(f\"Already retried {self.max_tries} times. Skipped.\")\n        else:\n            self.logger.error(\"Error is occured. Pushing back to queue.\")\n    return is_max\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.remove","title":"remove","text":"
remove(message: str) -> None\n

Remove a message from memory.

PARAMETER DESCRIPTION message

The message to be removed.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def remove(self, message: str) -> None:\n    \"\"\"Remove a message from memory.\n\n    Args:\n        message: The message to be removed.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.memory[message] = 0\n    self.memory += Counter()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/","title":"EndlessWatcher","text":"","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher","title":"faststream.broker.push_back_watcher.EndlessWatcher","text":"
EndlessWatcher(\n    max_tries: int = 0, logger: Optional[Logger] = None\n)\n

Bases: BaseWatcher

Initialize the class.

PARAMETER DESCRIPTION max_tries

Maximum number of tries allowed

TYPE: int DEFAULT: 0

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented in the subclass.

Source code in faststream/broker/push_back_watcher.py
def __init__(\n    self,\n    max_tries: int = 0,\n    logger: Optional[Logger] = None,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        max_tries: Maximum number of tries allowed\n        logger: Optional logger object\n\n    Raises:\n        NotImplementedError: If the method is not implemented in the subclass.\n\n    \"\"\"\n    self.logger = logger\n    self.max_tries = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher.max_tries","title":"max_tries instance-attribute","text":"
max_tries: int = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher.add","title":"add","text":"
add(message_id: str) -> None\n

Add a message to the list.

PARAMETER DESCRIPTION message_id

ID of the message to be added

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def add(self, message_id: str) -> None:\n    \"\"\"Add a message to the list.\n\n    Args:\n        message_id: ID of the message to be added\n\n    Returns:\n        None\n\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher.is_max","title":"is_max","text":"
is_max(message_id: str) -> bool\n

Check if a message is the maximum.

PARAMETER DESCRIPTION message_id

ID of the message to check

TYPE: str

RETURNS DESCRIPTION bool

True if the message is the maximum, False otherwise

Source code in faststream/broker/push_back_watcher.py
def is_max(self, message_id: str) -> bool:\n    \"\"\"Check if a message is the maximum.\n\n    Args:\n        message_id: ID of the message to check\n\n    Returns:\n        True if the message is the maximum, False otherwise\n\n    \"\"\"\n    return False\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher.remove","title":"remove","text":"
remove(message_id: str) -> None\n

Remove a message.

PARAMETER DESCRIPTION message_id

The ID of the message to be removed.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def remove(self, message_id: str) -> None:\n    \"\"\"Remove a message.\n\n    Args:\n        message_id: The ID of the message to be removed.\n\n    Returns:\n        None\n\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/","title":"OneTryWatcher","text":"","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher","title":"faststream.broker.push_back_watcher.OneTryWatcher","text":"
OneTryWatcher(\n    max_tries: int = 0, logger: Optional[Logger] = None\n)\n

Bases: BaseWatcher

Initialize the class.

PARAMETER DESCRIPTION max_tries

Maximum number of tries allowed

TYPE: int DEFAULT: 0

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented in the subclass.

Source code in faststream/broker/push_back_watcher.py
def __init__(\n    self,\n    max_tries: int = 0,\n    logger: Optional[Logger] = None,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        max_tries: Maximum number of tries allowed\n        logger: Optional logger object\n\n    Raises:\n        NotImplementedError: If the method is not implemented in the subclass.\n\n    \"\"\"\n    self.logger = logger\n    self.max_tries = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher.max_tries","title":"max_tries instance-attribute","text":"
max_tries: int = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher.add","title":"add","text":"
add(message_id: str) -> None\n

Add a message.

PARAMETER DESCRIPTION message_id

ID of the message to be added

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def add(self, message_id: str) -> None:\n    \"\"\"Add a message.\n\n    Args:\n        message_id: ID of the message to be added\n\n    Returns:\n        None\n\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher.is_max","title":"is_max","text":"
is_max(message_id: str) -> bool\n

Check if the given message ID is the maximum.

PARAMETER DESCRIPTION message_id

The ID of the message to check.

TYPE: str

RETURNS DESCRIPTION bool

True if the given message ID is the maximum, False otherwise.

Source code in faststream/broker/push_back_watcher.py
def is_max(self, message_id: str) -> bool:\n    \"\"\"Check if the given message ID is the maximum.\n\n    Args:\n        message_id: The ID of the message to check.\n\n    Returns:\n        True if the given message ID is the maximum, False otherwise.\n\n    \"\"\"\n    return True\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher.remove","title":"remove","text":"
remove(message_id: str) -> None\n

Remove a message.

PARAMETER DESCRIPTION message_id

ID of the message to be removed

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def remove(self, message_id: str) -> None:\n    \"\"\"Remove a message.\n\n    Args:\n        message_id: ID of the message to be removed\n\n    Returns:\n        None\n\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/WatcherContext/","title":"WatcherContext","text":"","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/WatcherContext/#faststream.broker.push_back_watcher.WatcherContext","title":"faststream.broker.push_back_watcher.WatcherContext","text":"
WatcherContext(\n    message: Union[\n        SyncStreamMessage[MsgType], StreamMessage[MsgType]\n    ],\n    watcher: BaseWatcher,\n    **extra_ack_args: Any\n)\n

A class representing a context for a watcher.

METHOD DESCRIPTION __aenter__

called when entering the context

__aexit__

called when exiting the context

__ack

acknowledges the message

__nack

negatively acknowledges the message

__reject

rejects the message

Initialize a new instance of the class.

PARAMETER DESCRIPTION watcher

An instance of BaseWatcher.

TYPE: BaseWatcher

message

An instance of SyncStreamMessage or StreamMessage.

TYPE: Union[SyncStreamMessage[MsgType], StreamMessage[MsgType]]

**extra_ack_args

Additional arguments for acknowledgement.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/push_back_watcher.py
def __init__(\n    self,\n    message: Union[SyncStreamMessage[MsgType], StreamMessage[MsgType]],\n    watcher: BaseWatcher,\n    **extra_ack_args: Any,\n) -> None:\n    \"\"\"Initialize a new instance of the class.\n\n    Args:\n        watcher: An instance of BaseWatcher.\n        message: An instance of SyncStreamMessage or StreamMessage.\n        **extra_ack_args: Additional arguments for acknowledgement.\n\n    Attributes:\n        watcher: An instance of BaseWatcher.\n        message: An instance of SyncStreamMessage or StreamMessage.\n        extra_ack_args: Additional arguments for acknowledgement.\n\n    \"\"\"\n    self.watcher = watcher\n    self.message = message\n    self.extra_ack_args = extra_ack_args or {}\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/WatcherContext/#faststream.broker.push_back_watcher.WatcherContext.extra_ack_args","title":"extra_ack_args instance-attribute","text":"
extra_ack_args = extra_ack_args or {}\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/WatcherContext/#faststream.broker.push_back_watcher.WatcherContext.message","title":"message instance-attribute","text":"
message = message\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/WatcherContext/#faststream.broker.push_back_watcher.WatcherContext.watcher","title":"watcher instance-attribute","text":"
watcher = watcher\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRoute/","title":"BrokerRoute","text":"","boost":0.5},{"location":"api/faststream/broker/router/BrokerRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/","title":"BrokerRouter","text":"","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter","title":"faststream.broker.router.BrokerRouter","text":"
BrokerRouter(\n    prefix: str = \"\",\n    handlers: Sequence[\n        BrokerRoute[MsgType, SendableMessage]\n    ] = (),\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    include_in_schema: Optional[bool] = None,\n)\n

Bases: Generic[PublisherKeyType, MsgType]

A generic class representing a broker router.

METHOD DESCRIPTION _get_publisher_key

abstract method to get the publisher key

_update_publisher_prefix

abstract method to update the publisher prefix

__init__

constructor method

subscriber

abstract method to define a subscriber

_wrap_subscriber

method to wrap a subscriber function

publisher

abstract method to define a publisher

include_router

method to include a router

include_routers

method to include multiple routers

Initialize a class object.

PARAMETER DESCRIPTION prefix

Prefix for the object.

TYPE: str DEFAULT: ''

handlers

Handlers for the object.

TYPE: Sequence[BrokerRoute[MsgType, SendableMessage]] DEFAULT: ()

dependencies

Dependencies for the object.

TYPE: Sequence[Depends] DEFAULT: ()

middlewares

Middlewares for the object.

TYPE: Optional[Sequence[Callable[[StreamMessage[MsgType]], AsyncContextManager[None]]]] DEFAULT: None

parser

Parser for the object.

TYPE: Optional[CustomParser[MsgType]] DEFAULT: None

decoder

Decoder for the object.

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

Source code in faststream/broker/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[BrokerRoute[MsgType, SendableMessage]] = (),\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    include_in_schema: Optional[bool] = None,\n) -> None:\n    \"\"\"Initialize a class object.\n\n    Args:\n        prefix (str): Prefix for the object.\n        handlers (Sequence[BrokerRoute[MsgType, SendableMessage]]): Handlers for the object.\n        dependencies (Sequence[Depends]): Dependencies for the object.\n        middlewares (Optional[Sequence[Callable[[StreamMessage[MsgType]], AsyncContextManager[None]]]]): Middlewares for the object.\n        parser (Optional[CustomParser[MsgType]]): Parser for the object.\n        decoder (Optional[CustomDecoder[StreamMessage[MsgType]]]): Decoder for the object.\n\n    \"\"\"\n    self.prefix = prefix\n    self.include_in_schema = include_in_schema\n    self._handlers = list(handlers)\n    self._publishers = {}\n    self._dependencies = dependencies\n    self._middlewares = middlewares\n    self._parser = parser\n    self._decoder = decoder\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.subscriber","title":"subscriber abstractmethod","text":"
subscriber(\n    subj: str,\n    *args: Any,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    include_in_schema: Optional[bool] = None,\n    **kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function to subscribe to a subject.

PARAMETER DESCRIPTION subj

subject to subscribe to

*args

additional arguments

DEFAULT: ()

dependencies

sequence of dependencies

DEFAULT: ()

middlewares

optional sequence of middlewares

DEFAULT: None

parser

optional custom parser

DEFAULT: None

decoder

optional custom decoder

DEFAULT: None

**kwargs

additional keyword arguments

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable handler function

RAISES DESCRIPTION NotImplementedError

If the function is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef subscriber(\n    self,\n    subj: str,\n    *args: Any,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    include_in_schema: Optional[bool] = None,\n    **kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function to subscribe to a subject.\n\n    Args:\n        subj : subject to subscribe to\n        *args : additional arguments\n        dependencies : sequence of dependencies\n        middlewares : optional sequence of middlewares\n        parser : optional custom parser\n        decoder : optional custom decoder\n        **kwargs : additional keyword arguments\n\n    Returns:\n        A callable handler function\n\n    Raises:\n        NotImplementedError: If the function is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/schemas/NameRequired/","title":"NameRequired","text":"","boost":0.5},{"location":"api/faststream/broker/schemas/NameRequired/#faststream.broker.schemas.NameRequired","title":"faststream.broker.schemas.NameRequired","text":"
NameRequired(name: str, **kwargs: Any)\n

Bases: BaseModel

A class to represent a required name.

METHOD DESCRIPTION __eq__

object) -> bool: Check if the given value is equal to the current instance.

validate

Type[NameRequiredCls], value: Union[str, NameRequiredCls]) -> NameRequiredCls: Validate the given value and return a NameRequiredCls instance.

validate

Type[NameRequiredCls], value: None) -> None: Validate the given value and return None.

validate

Type[NameRequiredCls], value: Union[str, NameRequiredCls, None]) -> Optional[NameRequiredCls]: Validate the given value and return an optional NameRequiredCls instance.

This is a Python function.

PARAMETER DESCRIPTION name

The name of the object.

TYPE: str

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None.

Source code in faststream/broker/schemas.py
def __init__(self, name: str, **kwargs: Any) -> None:\n    \"\"\"This is a Python function.\n\n    Args:\n        name (str): The name of the object.\n        **kwargs (Any): Additional keyword arguments.\n\n    Returns:\n        None.\n\n    \"\"\"\n    super().__init__(name=name, **kwargs)\n
","boost":0.5},{"location":"api/faststream/broker/schemas/NameRequired/#faststream.broker.schemas.NameRequired.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/broker/schemas/NameRequired/#faststream.broker.schemas.NameRequired.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/broker/schemas/RawDecoced/","title":"RawDecoced","text":"","boost":0.5},{"location":"api/faststream/broker/schemas/RawDecoced/#faststream.broker.schemas.RawDecoced","title":"faststream.broker.schemas.RawDecoced","text":"

Bases: BaseModel

A class to represent a raw decoded message.

","boost":0.5},{"location":"api/faststream/broker/schemas/RawDecoced/#faststream.broker.schemas.RawDecoced.message","title":"message instance-attribute","text":"
message: Union[Json[Any], str]\n
","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/","title":"BaseSecurity","text":"","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/#faststream.security.BaseSecurity","title":"faststream.security.BaseSecurity","text":"
BaseSecurity(\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Base class for defining security configurations.

This class provides a base for defining security configurations for communication with a broker. It allows setting SSL encryption and provides methods to retrieve security requirements and schemas.

PARAMETER DESCRIPTION ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements in the form of a list of dictionaries.

get_schema

Get the security schema as a dictionary.

Source code in faststream/security.py
def __init__(\n    self,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    if ssl_context is not None:\n        use_ssl = True\n\n    self.use_ssl = use_ssl\n    self.ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/#faststream.security.BaseSecurity.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/#faststream.security.BaseSecurity.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/#faststream.security.BaseSecurity.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return []\n
","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/#faststream.security.BaseSecurity.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {}\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/","title":"SASLPlaintext","text":"","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext","title":"faststream.security.SASLPlaintext","text":"
SASLPlaintext(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/PLAINTEXT authentication.

This class defines security configuration for SASL/PLAINTEXT authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/PLAINTEXT authentication.

get_schema

Get the security schema for SASL/PLAINTEXT authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/PLAINTEXT authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/PLAINTEXT authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"user-password\": []}]\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/PLAINTEXT authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/PLAINTEXT authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"user-password\": {\"type\": \"userPassword\"}}\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/","title":"SASLScram256","text":"","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256","title":"faststream.security.SASLScram256","text":"
SASLScram256(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/SCRAM-SHA-256 authentication.

This class defines security configuration for SASL/SCRAM-SHA-256 authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/SCRAM-SHA-256 authentication.

get_schema

Get the security schema for SASL/SCRAM-SHA-256 authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/SCRAM-SHA-256 authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/SCRAM-SHA-256 authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"scram256\": []}]\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/SCRAM-SHA-256 authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/SCRAM-SHA-256 authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"scram256\": {\"type\": \"scramSha256\"}}\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/","title":"SASLScram512","text":"","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512","title":"faststream.security.SASLScram512","text":"
SASLScram512(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/SCRAM-SHA-512 authentication.

This class defines security configuration for SASL/SCRAM-SHA-512 authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/SCRAM-SHA-512 authentication.

get_schema

Get the security schema for SASL/SCRAM-SHA-512 authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/SCRAM-SHA-512 authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/SCRAM-SHA-512 authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"scram512\": []}]\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/SCRAM-SHA-512 authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/SCRAM-SHA-512 authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"scram512\": {\"type\": \"scramSha512\"}}\n
","boost":0.5},{"location":"api/faststream/broker/test/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/broker/test/TestApp/#faststream.broker.test.TestApp","title":"faststream.broker.test.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/broker/test/TestApp/#faststream.broker.test.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/","title":"TestBroker","text":"","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker","title":"faststream.broker.test.TestBroker","text":"
TestBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: Generic[Broker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber abstractmethod staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: Broker, publisher: Any\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/broker/test.py
@staticmethod\n@abstractmethod\ndef create_publisher_fake_subscriber(\n    broker: Broker, publisher: Any\n) -> HandlerCallWrapper[Any, Any, Any]:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.patch_publisher","title":"patch_publisher abstractmethod staticmethod","text":"
patch_publisher(broker: Broker, publisher: Any) -> None\n
Source code in faststream/broker/test.py
@staticmethod\n@abstractmethod\ndef patch_publisher(broker: Broker, publisher: Any) -> None:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber abstractmethod staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: Broker, publisher: Any\n) -> None\n
Source code in faststream/broker/test.py
@staticmethod\n@abstractmethod\ndef remove_publisher_fake_subscriber(broker: Broker, publisher: Any) -> None:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/test/call_handler/","title":"call_handler","text":"","boost":0.5},{"location":"api/faststream/broker/test/call_handler/#faststream.broker.test.call_handler","title":"faststream.broker.test.call_handler async","text":"
call_handler(\n    handler: AsyncHandler[Any],\n    message: Any,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[SendableMessage]\n

Asynchronously call a handler function.

PARAMETER DESCRIPTION handler

The handler function to be called.

TYPE: AsyncHandler[Any]

message

The message to be passed to the handler function.

TYPE: Any

rpc

Whether the call is a remote procedure call (RPC).

TYPE: bool DEFAULT: False

rpc_timeout

The timeout for the RPC, in seconds.

TYPE: Optional[float] DEFAULT: 30.0

raise_timeout

Whether to raise a timeout error if the RPC times out.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION Optional[SendableMessage]

The result of the handler function if rpc is True, otherwise None.

RAISES DESCRIPTION TimeoutError

If the RPC times out and raise_timeout is True.

Source code in faststream/broker/test.py
async def call_handler(\n    handler: AsyncHandler[Any],\n    message: Any,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[SendableMessage]:\n    \"\"\"Asynchronously call a handler function.\n\n    Args:\n        handler: The handler function to be called.\n        message: The message to be passed to the handler function.\n        rpc: Whether the call is a remote procedure call (RPC).\n        rpc_timeout: The timeout for the RPC, in seconds.\n        raise_timeout: Whether to raise a timeout error if the RPC times out.\n\n    Returns:\n        The result of the handler function if `rpc` is True, otherwise None.\n\n    Raises:\n        TimeoutError: If the RPC times out and `raise_timeout` is True.\n\n    \"\"\"\n    with timeout_scope(rpc_timeout, raise_timeout):\n        result = await handler.consume(message)\n\n        if rpc is True:\n            return result\n\n    return None\n
","boost":0.5},{"location":"api/faststream/broker/test/patch_broker_calls/","title":"patch_broker_calls","text":"","boost":0.5},{"location":"api/faststream/broker/test/patch_broker_calls/#faststream.broker.test.patch_broker_calls","title":"faststream.broker.test.patch_broker_calls","text":"
patch_broker_calls(broker: BrokerUsecase[Any, Any]) -> None\n

Patch broker calls.

PARAMETER DESCRIPTION broker

The broker to patch.

TYPE: BrokerUsecase[Any, Any]

RETURNS DESCRIPTION None

None.

Source code in faststream/broker/test.py
def patch_broker_calls(broker: BrokerUsecase[Any, Any]) -> None:\n    \"\"\"Patch broker calls.\n\n    Args:\n        broker: The broker to patch.\n\n    Returns:\n        None.\n\n    \"\"\"\n    broker.middlewares = tuple(\n        filter(  # type: ignore[assignment]\n            lambda x: not isinstance(x, CriticalLogMiddleware),\n            broker.middlewares,\n        )\n    )\n    broker._abc_start()\n\n    for handler in broker.handlers.values():\n        for f, _, _, _, _, _ in handler.calls:\n            f.set_test()\n
","boost":0.5},{"location":"api/faststream/broker/types/AsyncPublisherProtocol/","title":"AsyncPublisherProtocol","text":"","boost":0.5},{"location":"api/faststream/broker/types/AsyncPublisherProtocol/#faststream.broker.types.AsyncPublisherProtocol","title":"faststream.broker.types.AsyncPublisherProtocol","text":"

Bases: Protocol

A protocol for an asynchronous publisher.

METHOD DESCRIPTION publish

SendableMessage, correlation_id: Optional[str] = None, **kwargs: Any) -> Optional[SendableMessage]: Publishes a message asynchronously.

Args: message: The message to be published. correlation_id: The correlation ID for the message (optional). **kwargs: Additional keyword arguments.

Returns: The published message (optional).

","boost":0.5},{"location":"api/faststream/broker/types/AsyncPublisherProtocol/#faststream.broker.types.AsyncPublisherProtocol.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publishes a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

correlation_id

Optional correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message, or None if the message was not published.

Source code in faststream/broker/types.py
async def publish(\n    self,\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publishes a message.\n\n    Args:\n        message: The message to be published.\n        correlation_id: Optional correlation ID for the message.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message, or None if the message was not published.\n\n    \"\"\"\n    ...\n
","boost":0.5},{"location":"api/faststream/broker/utils/change_logger_handlers/","title":"change_logger_handlers","text":"","boost":0.5},{"location":"api/faststream/broker/utils/change_logger_handlers/#faststream.broker.utils.change_logger_handlers","title":"faststream.broker.utils.change_logger_handlers","text":"
change_logger_handlers(\n    logger: logging.Logger, fmt: str\n) -> None\n

Change the formatter of the logger handlers.

PARAMETER DESCRIPTION logger

The logger object.

TYPE: Logger

fmt

The format string for the formatter.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/utils.py
def change_logger_handlers(logger: logging.Logger, fmt: str) -> None:\n    \"\"\"Change the formatter of the logger handlers.\n\n    Args:\n        logger (logging.Logger): The logger object.\n        fmt (str): The format string for the formatter.\n\n    Returns:\n        None\n\n    \"\"\"\n    for handler in getattr(logger, \"handlers\", ()):\n        formatter = handler.formatter\n        if formatter is not None:  # pragma: no branch\n            use_colors = getattr(formatter, \"use_colors\", None)\n            if use_colors is not None:  # pragma: no branch\n                kwargs = {\"use_colors\": use_colors}\n            else:  # pragma: no cover\n                kwargs = {}\n            handler.setFormatter(type(formatter)(fmt, **kwargs))\n
","boost":0.5},{"location":"api/faststream/broker/utils/get_watcher/","title":"get_watcher","text":"","boost":0.5},{"location":"api/faststream/broker/utils/get_watcher/#faststream.broker.utils.get_watcher","title":"faststream.broker.utils.get_watcher","text":"
get_watcher(\n    logger: Optional[logging.Logger],\n    try_number: Union[bool, int] = True,\n) -> BaseWatcher\n

Get a watcher object based on the provided parameters.

PARAMETER DESCRIPTION logger

Optional logger object for logging messages.

TYPE: Optional[Logger]

try_number

Optional parameter to specify the type of watcher. - If set to True, an EndlessWatcher object will be returned. - If set to False, a OneTryWatcher object will be returned. - If set to an integer, a CounterWatcher object with the specified maximum number of tries will be returned.

TYPE: Union[bool, int] DEFAULT: True

RETURNS DESCRIPTION BaseWatcher

A watcher object based on the provided parameters.

Source code in faststream/broker/utils.py
def get_watcher(\n    logger: Optional[logging.Logger],\n    try_number: Union[bool, int] = True,\n) -> BaseWatcher:\n    \"\"\"Get a watcher object based on the provided parameters.\n\n    Args:\n        logger: Optional logger object for logging messages.\n        try_number: Optional parameter to specify the type of watcher.\n            - If set to True, an EndlessWatcher object will be returned.\n            - If set to False, a OneTryWatcher object will be returned.\n            - If set to an integer, a CounterWatcher object with the specified maximum number of tries will be returned.\n\n    Returns:\n        A watcher object based on the provided parameters.\n\n    \"\"\"\n    watcher: Optional[BaseWatcher]\n    if try_number is True:\n        watcher = EndlessWatcher()\n    elif try_number is False:\n        watcher = OneTryWatcher()\n    else:\n        watcher = CounterWatcher(logger=logger, max_tries=try_number)\n    return watcher\n
","boost":0.5},{"location":"api/faststream/broker/utils/set_message_context/","title":"set_message_context","text":"","boost":0.5},{"location":"api/faststream/broker/utils/set_message_context/#faststream.broker.utils.set_message_context","title":"faststream.broker.utils.set_message_context","text":"
set_message_context(\n    func: Callable[\n        [StreamMessage[MsgType]],\n        Awaitable[WrappedReturn[T_HandlerReturn]],\n    ]\n) -> Callable[\n    [StreamMessage[MsgType]],\n    Awaitable[WrappedReturn[T_HandlerReturn]],\n]\n

Sets the message context for a function.

PARAMETER DESCRIPTION func

The function to set the message context for.

TYPE: Callable[[StreamMessage[MsgType]], Awaitable[WrappedReturn[T_HandlerReturn]]]

RETURNS DESCRIPTION Callable[[StreamMessage[MsgType]], Awaitable[WrappedReturn[T_HandlerReturn]]]

The function with the message context set.

Source code in faststream/broker/utils.py
def set_message_context(\n    func: Callable[\n        [StreamMessage[MsgType]],\n        Awaitable[WrappedReturn[T_HandlerReturn]],\n    ],\n) -> Callable[[StreamMessage[MsgType]], Awaitable[WrappedReturn[T_HandlerReturn]]]:\n    \"\"\"Sets the message context for a function.\n\n    Args:\n        func: The function to set the message context for.\n\n    Returns:\n        The function with the message context set.\n\n    \"\"\"\n\n    @wraps(func)\n    async def set_message_wrapper(\n        message: StreamMessage[MsgType],\n    ) -> WrappedReturn[T_HandlerReturn]:\n        \"\"\"Wraps a function that handles a stream message.\n\n        Args:\n            message: The stream message to be handled.\n\n        Returns:\n            The wrapped return value of the handler function.\n\n        \"\"\"\n        with context.scope(\"message\", message):\n            return await func(message)\n\n    return set_message_wrapper\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/FakePublisher/","title":"FakePublisher","text":"","boost":0.5},{"location":"api/faststream/broker/wrapper/FakePublisher/#faststream.broker.wrapper.FakePublisher","title":"faststream.broker.wrapper.FakePublisher","text":"
FakePublisher(\n    method: Callable[..., Awaitable[SendableMessage]]\n)\n

A class to represent a fake publisher.

METHOD DESCRIPTION publish

asynchronously publishes a message with optional correlation ID and additional keyword arguments

Initialize an object.

PARAMETER DESCRIPTION method

A callable that takes any number of arguments and returns an awaitable sendable message.

TYPE: Callable[..., Awaitable[SendableMessage]]

Source code in faststream/broker/wrapper.py
def __init__(self, method: Callable[..., Awaitable[SendableMessage]]) -> None:\n    \"\"\"Initialize an object.\n\n    Args:\n        method: A callable that takes any number of arguments and returns an awaitable sendable message.\n\n    \"\"\"\n    self.method = method\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/FakePublisher/#faststream.broker.wrapper.FakePublisher.method","title":"method instance-attribute","text":"
method = method\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/FakePublisher/#faststream.broker.wrapper.FakePublisher.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

correlation_id

Optional correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message.

Source code in faststream/broker/wrapper.py
async def publish(\n    self,\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        correlation_id: Optional correlation ID for the message.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message.\n\n    \"\"\"\n    return await self.method(message, correlation_id=correlation_id, **kwargs)\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/","title":"HandlerCallWrapper","text":"","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper","title":"faststream.broker.wrapper.HandlerCallWrapper","text":"
HandlerCallWrapper(\n    call: Callable[P_HandlerParams, T_HandlerReturn]\n)\n

Bases: Generic[MsgType, P_HandlerParams, T_HandlerReturn]

A generic class to wrap handler calls.

METHOD DESCRIPTION __new__

Create a new instance of the class

__init__

Initialize the instance

__call__

Call the wrapped handler

set_wrapped

Set the wrapped handler call

call_wrapped

Call the wrapped handler

wait_call

Wait for the handler call to complete

Initialize a handler.

PARAMETER DESCRIPTION call

A callable object that represents the handler function.

TYPE: Callable[P_HandlerParams, T_HandlerReturn]

Source code in faststream/broker/wrapper.py
def __init__(\n    self,\n    call: Callable[P_HandlerParams, T_HandlerReturn],\n) -> None:\n    \"\"\"Initialize a handler.\n\n    Args:\n        call: A callable object that represents the handler function.\n\n    Attributes:\n        _original_call: The original handler function.\n        _wrapped_call: The wrapped handler function.\n        _publishers: A list of publishers.\n        mock: A MagicMock object.\n        __name__: The name of the handler function.\n\n    \"\"\"\n    if not isinstance(call, HandlerCallWrapper):\n        self._original_call = call\n        self._wrapped_call = None\n        self._publishers = []\n\n        self.mock = None\n        self.future = None\n        self.is_test = False\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.future","title":"future instance-attribute","text":"
future: Optional[asyncio.Future[Any]]\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.is_test","title":"is_test instance-attribute","text":"
is_test: bool\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.mock","title":"mock instance-attribute","text":"
mock: Optional[MagicMock]\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.call_wrapped","title":"call_wrapped","text":"
call_wrapped(\n    message: StreamMessage[MsgType],\n) -> Union[\n    Optional[WrappedReturn[T_HandlerReturn]],\n    Awaitable[Optional[WrappedReturn[T_HandlerReturn]]],\n]\n

Calls the wrapped function with the given message.

PARAMETER DESCRIPTION message

The message to be passed to the wrapped function.

TYPE: StreamMessage[MsgType]

RETURNS DESCRIPTION Union[Optional[WrappedReturn[T_HandlerReturn]], Awaitable[Optional[WrappedReturn[T_HandlerReturn]]]]

The result of the wrapped function call.

RAISES DESCRIPTION AssertionError

If set_wrapped has not been called before calling this function.

AssertionError

If the broker has not been started before calling this function.

Source code in faststream/broker/wrapper.py
def call_wrapped(\n    self,\n    message: StreamMessage[MsgType],\n) -> Union[\n    Optional[WrappedReturn[T_HandlerReturn]],\n    Awaitable[Optional[WrappedReturn[T_HandlerReturn]]],\n]:\n    \"\"\"Calls the wrapped function with the given message.\n\n    Args:\n        message: The message to be passed to the wrapped function.\n\n    Returns:\n        The result of the wrapped function call.\n\n    Raises:\n        AssertionError: If `set_wrapped` has not been called before calling this function.\n        AssertionError: If the broker has not been started before calling this function.\n\n    \"\"\"\n    assert self._wrapped_call, \"You should use `set_wrapped` first\"  # nosec B101\n    if self.is_test:\n        assert self.mock  # nosec B101\n        self.mock(message.decoded_body)\n    return self._wrapped_call(message)\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.refresh","title":"refresh","text":"
refresh(with_mock: bool = False) -> None\n
Source code in faststream/broker/wrapper.py
def refresh(self, with_mock: bool = False) -> None:\n    self.future = asyncio.Future()\n    if with_mock and self.mock is not None:\n        self.mock.reset_mock()\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/wrapper.py
def reset_test(self) -> None:\n    self.is_test = False\n    self.mock = None\n    self.future = None\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.set_test","title":"set_test","text":"
set_test() -> None\n
Source code in faststream/broker/wrapper.py
def set_test(self) -> None:\n    self.is_test = True\n    if self.mock is None:\n        self.mock = MagicMock()\n    self.refresh(with_mock=True)\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.set_wrapped","title":"set_wrapped","text":"
set_wrapped(\n    wrapped: WrappedHandlerCall[MsgType, T_HandlerReturn]\n) -> None\n

Set the wrapped handler call.

PARAMETER DESCRIPTION wrapped

The wrapped handler call to set

TYPE: WrappedHandlerCall[MsgType, T_HandlerReturn]

Source code in faststream/broker/wrapper.py
def set_wrapped(\n    self, wrapped: WrappedHandlerCall[MsgType, T_HandlerReturn]\n) -> None:\n    \"\"\"Set the wrapped handler call.\n\n    Args:\n        wrapped: The wrapped handler call to set\n\n    \"\"\"\n    self._wrapped_call = wrapped\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.trigger","title":"trigger","text":"
trigger(\n    result: Any = None,\n    error: Optional[BaseException] = None,\n) -> None\n
Source code in faststream/broker/wrapper.py
def trigger(\n    self,\n    result: Any = None,\n    error: Optional[BaseException] = None,\n) -> None:\n    if not self.is_test:\n        return\n\n    assert (  # nosec B101\n        self.future is not None\n    ), \"You can use this method only with TestClient\"\n\n    if self.future.done():\n        self.future = asyncio.Future()\n\n    if error:\n        self.future.set_exception(error)\n    else:\n        self.future.set_result(result)\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.wait_call","title":"wait_call async","text":"
wait_call(timeout: Optional[float] = None) -> None\n

Waits for a call with an optional timeout.

PARAMETER DESCRIPTION timeout

Optional timeout in seconds

TYPE: Optional[float] DEFAULT: None

RAISES DESCRIPTION AssertionError

If the broker is not started

RETURNS DESCRIPTION None

None

Source code in faststream/broker/wrapper.py
async def wait_call(self, timeout: Optional[float] = None) -> None:\n    \"\"\"Waits for a call with an optional timeout.\n\n    Args:\n        timeout: Optional timeout in seconds\n\n    Raises:\n        AssertionError: If the broker is not started\n\n    Returns:\n        None\n\n    \"\"\"\n    assert (  # nosec B101\n        self.future is not None\n    ), \"You can use this method only with TestClient\"\n    with anyio.fail_after(timeout):\n        await self.future\n
","boost":0.5},{"location":"api/faststream/cli/docs/app/gen/","title":"gen","text":"","boost":0.5},{"location":"api/faststream/cli/docs/app/gen/#faststream.cli.docs.app.gen","title":"faststream.cli.docs.app.gen","text":"
gen(\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] - path to your application\",\n    ),\n    yaml: bool = typer.Option(\n        False,\n        \"--yaml\",\n        is_flag=True,\n        help=\"generate `asyncapi.yaml` schema\",\n    ),\n    out: Optional[str] = typer.Option(\n        None, help=\"output filename\"\n    ),\n) -> None\n

Generate project AsyncAPI schema

Source code in faststream/cli/docs/app.py
@docs_app.command(name=\"gen\")\ndef gen(\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] - path to your application\",\n    ),\n    yaml: bool = typer.Option(\n        False,\n        \"--yaml\",\n        is_flag=True,\n        help=\"generate `asyncapi.yaml` schema\",\n    ),\n    out: Optional[str] = typer.Option(\n        None,\n        help=\"output filename\",\n    ),\n) -> None:\n    \"\"\"Generate project AsyncAPI schema\"\"\"\n    _, app_obj = import_from_string(app)\n    raw_schema = get_app_schema(app_obj)\n\n    if yaml:\n        try:\n            schema = raw_schema.to_yaml()\n        except ImportError as e:  # pragma: no cover\n            typer.echo(INSTALL_YAML, err=True)\n            raise typer.Exit(1) from e\n\n        name = out or \"asyncapi.yaml\"\n\n        with open(name, \"w\") as f:\n            f.write(schema)\n\n    else:\n        schema = raw_schema.to_jsonable()\n        name = out or \"asyncapi.json\"\n\n        with open(name, \"w\") as f:\n            json.dump(schema, f, indent=2)\n\n    typer.echo(f\"Your project AsyncAPI scheme was placed to `{name}`\")\n
","boost":0.5},{"location":"api/faststream/cli/docs/app/serve/","title":"serve","text":"","boost":0.5},{"location":"api/faststream/cli/docs/app/serve/#faststream.cli.docs.app.serve","title":"faststream.cli.docs.app.serve","text":"
serve(\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] or [asyncapi.yaml/.json] - path to your application or documentation\",\n    ),\n    host: str = typer.Option(\n        \"localhost\", help=\"documentation hosting address\"\n    ),\n    port: int = typer.Option(\n        8000, help=\"documentation hosting port\"\n    ),\n    reload: bool = typer.Option(\n        False,\n        \"--reload\",\n        is_flag=True,\n        help=\"Restart documentation at directory files changes\",\n    ),\n) -> None\n

Serve project AsyncAPI schema

Source code in faststream/cli/docs/app.py
@docs_app.command(name=\"serve\")\ndef serve(\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] or [asyncapi.yaml/.json] - path to your application or documentation\",\n    ),\n    host: str = typer.Option(\n        \"localhost\",\n        help=\"documentation hosting address\",\n    ),\n    port: int = typer.Option(\n        8000,\n        help=\"documentation hosting port\",\n    ),\n    reload: bool = typer.Option(\n        False,\n        \"--reload\",\n        is_flag=True,\n        help=\"Restart documentation at directory files changes\",\n    ),\n) -> None:\n    \"\"\"Serve project AsyncAPI schema\"\"\"\n\n    if \":\" in app:\n        module, _ = import_from_string(app)\n\n        module_parent = module.parent\n        extra_extensions: Sequence[str] = ()\n\n    else:\n        module_parent = Path.cwd()\n        schema_filepath = module_parent / app\n        extra_extensions = (schema_filepath.suffix,)\n\n    if reload is True:\n        try:\n            from faststream.cli.supervisors.watchfiles import WatchReloader\n\n        except ImportError:\n            warnings.warn(INSTALL_WATCHFILES, category=ImportWarning, stacklevel=1)\n            _parse_and_serve(app, host, port)\n\n        else:\n            WatchReloader(\n                target=_parse_and_serve,\n                args=(app, host, port),\n                reload_dirs=(str(module_parent),),\n                extra_extensions=extra_extensions,\n            ).run()\n\n    else:\n        _parse_and_serve(app, host, port)\n
","boost":0.5},{"location":"api/faststream/cli/main/main/","title":"main","text":"","boost":0.5},{"location":"api/faststream/cli/main/main/#faststream.cli.main.main","title":"faststream.cli.main.main","text":"
main(\n    version: Optional[bool] = typer.Option(\n        False,\n        \"-v\",\n        \"--version\",\n        callback=version_callback,\n        is_eager=True,\n        help=\"Show current platform, python and FastStream version\",\n    )\n) -> None\n

Generate, run and manage FastStream apps to greater development experience

Source code in faststream/cli/main.py
@cli.callback()\ndef main(\n    version: Optional[bool] = typer.Option(\n        False,\n        \"-v\",\n        \"--version\",\n        callback=version_callback,\n        is_eager=True,\n        help=\"Show current platform, python and FastStream version\",\n    ),\n) -> None:\n    \"\"\"\n    Generate, run and manage FastStream apps to greater development experience\n    \"\"\"\n
","boost":0.5},{"location":"api/faststream/cli/main/run/","title":"run","text":"","boost":0.5},{"location":"api/faststream/cli/main/run/#faststream.cli.main.run","title":"faststream.cli.main.run","text":"
run(\n    ctx: typer.Context,\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] - path to your application\",\n    ),\n    workers: int = typer.Option(\n        1,\n        show_default=False,\n        help=\"Run [workers] applications with process spawning\",\n    ),\n    log_level: LogLevels = typer.Option(\n        LogLevels.info,\n        case_sensitive=False,\n        show_default=False,\n        help=\"[INFO] default\",\n    ),\n    reload: bool = typer.Option(\n        False,\n        \"--reload\",\n        is_flag=True,\n        help=\"Restart app at directory files changes\",\n    ),\n    watch_extensions: List[str] = typer.Option(\n        (),\n        \"--extension\",\n        \"--reload-extension\",\n        \"--reload-ext\",\n        \"--ext\",\n        help=\"List of file extensions to watch by\",\n    ),\n    app_dir: str = typer.Option(\n        \".\",\n        \"--app-dir\",\n        help=\"Look for APP in the specified directory, by adding this to the PYTHONPATH. Defaults to the current working directory.\",\n    ),\n) -> None\n

Run [MODULE:APP] FastStream application

Source code in faststream/cli/main.py
@cli.command(\n    context_settings={\"allow_extra_args\": True, \"ignore_unknown_options\": True}\n)\ndef run(\n    ctx: typer.Context,\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] - path to your application\",\n    ),\n    workers: int = typer.Option(\n        1,\n        show_default=False,\n        help=\"Run [workers] applications with process spawning\",\n    ),\n    log_level: LogLevels = typer.Option(\n        LogLevels.info,\n        case_sensitive=False,\n        show_default=False,\n        help=\"[INFO] default\",\n    ),\n    reload: bool = typer.Option(\n        False,\n        \"--reload\",\n        is_flag=True,\n        help=\"Restart app at directory files changes\",\n    ),\n    watch_extensions: List[str] = typer.Option(\n        (),\n        \"--extension\",\n        \"--reload-extension\",\n        \"--reload-ext\",\n        \"--ext\",\n        help=\"List of file extensions to watch by\",\n    ),\n    app_dir: str = typer.Option(\n        \".\",\n        \"--app-dir\",\n        help=(\n            \"Look for APP in the specified directory, by adding this to the PYTHONPATH.\"\n            \" Defaults to the current working directory.\"\n        ),\n    ),\n) -> None:\n    \"\"\"Run [MODULE:APP] FastStream application\"\"\"\n    if watch_extensions and not reload:\n        typer.echo(\n            \"Extra reload extensions has no effect without `--reload` flag.\"\n            \"\\nProbably, you forgot it?\"\n        )\n\n    app, extra = parse_cli_args(app, *ctx.args)\n    casted_log_level = get_log_level(log_level)\n\n    if app_dir:  # pragma: no branch\n        sys.path.insert(0, app_dir)\n\n    args = (app, extra, casted_log_level)\n\n    if reload and workers > 1:\n        raise ValueError(\"You can't use reload option with multiprocessing\")\n\n    if reload is True:\n        try:\n            from faststream.cli.supervisors.watchfiles import WatchReloader\n        except ImportError:\n            warnings.warn(INSTALL_WATCHFILES, category=ImportWarning, stacklevel=1)\n            _run(*args)\n\n        else:\n            module_path, _ = import_from_string(app)\n\n            WatchReloader(\n                target=_run,\n                args=args,\n                reload_dirs=[str(module_path)] + ([app_dir] if app_dir else []),\n            ).run()\n\n    elif workers > 1:\n        from faststream.cli.supervisors.multiprocess import Multiprocess\n\n        Multiprocess(\n            target=_run,\n            args=(*args, logging.DEBUG),\n            workers=workers,\n        ).run()\n\n    else:\n        _run(*args)\n
","boost":0.5},{"location":"api/faststream/cli/main/version_callback/","title":"version_callback","text":"","boost":0.5},{"location":"api/faststream/cli/main/version_callback/#faststream.cli.main.version_callback","title":"faststream.cli.main.version_callback","text":"
version_callback(version: bool) -> None\n

Callback function for displaying version information.

PARAMETER DESCRIPTION version

If True, display version information

TYPE: bool

RETURNS DESCRIPTION None

None

Source code in faststream/cli/main.py
def version_callback(version: bool) -> None:\n    \"\"\"Callback function for displaying version information.\n\n    Args:\n        version: If True, display version information\n\n    Returns:\n        None\n\n    \"\"\"\n    if version is True:\n        import platform\n\n        typer.echo(\n            \"Running FastStream %s with %s %s on %s\"\n            % (\n                __version__,\n                platform.python_implementation(),\n                platform.python_version(),\n                platform.system(),\n            )\n        )\n\n        raise typer.Exit()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/","title":"BaseReload","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload","title":"faststream.cli.supervisors.basereload.BaseReload","text":"
BaseReload(\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    reload_delay: Optional[float] = 0.5,\n)\n

A base class for implementing a reloader process.

METHOD DESCRIPTION run

Runs the reloader process.

startup

Performs startup operations for the reloader process.

restart

Restarts the process.

shutdown

Shuts down the reloader process.

_stop_process

Stops the spawned process.

_start_process

Starts the spawned process.

should_restart

Determines whether the process should be restarted.

Initialize a class instance.

PARAMETER DESCRIPTION target

The target callable object

TYPE: DecoratedCallable

args

Tuple of arguments to be passed to the target callable

TYPE: Tuple[Any, ...]

reload_delay

Optional delay in seconds before reloading the target callable (default is 0.5 seconds)

TYPE: Optional[float] DEFAULT: 0.5

RETURNS DESCRIPTION None

None

Source code in faststream/cli/supervisors/basereload.py
def __init__(\n    self,\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    reload_delay: Optional[float] = 0.5,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        target: The target callable object\n        args: Tuple of arguments to be passed to the target callable\n        reload_delay: Optional delay in seconds before reloading the target callable (default is 0.5 seconds)\n\n    Returns:\n        None\n\n    \"\"\"\n    self._target = target\n    self._args = args\n\n    self.should_exit = threading.Event()\n    self.pid = os.getpid()\n    self.reload_delay = reload_delay\n\n    set_exit(lambda *_: self.should_exit.set())\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.pid","title":"pid instance-attribute","text":"
pid: int = os.getpid()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.reload_delay","title":"reload_delay instance-attribute","text":"
reload_delay: Optional[float] = reload_delay\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.reloader_name","title":"reloader_name class-attribute instance-attribute","text":"
reloader_name: str = ''\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.should_exit","title":"should_exit instance-attribute","text":"
should_exit: threading.Event = threading.Event()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.restart","title":"restart","text":"
restart() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def restart(self) -> None:\n    self._stop_process()\n    logger.info(\"Process successfully reloaded\")\n    self._process = self._start_process()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.run","title":"run","text":"
run() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def run(self) -> None:\n    self.startup()\n    while not self.should_exit.wait(self.reload_delay):\n        if self.should_restart():  # pragma: no branch\n            self.restart()\n    self.shutdown()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.should_restart","title":"should_restart","text":"
should_restart() -> bool\n
Source code in faststream/cli/supervisors/basereload.py
def should_restart(self) -> bool:\n    raise NotImplementedError(\"Reload strategies should override should_restart()\")\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.shutdown","title":"shutdown","text":"
shutdown() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def shutdown(self) -> None:\n    self._stop_process()\n    logger.info(f\"Stopping reloader process [{self.pid}]\")\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.startup","title":"startup","text":"
startup() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def startup(self) -> None:\n    logger.info(f\"Started reloader process [{self.pid}] using {self.reloader_name}\")\n    self._process = self._start_process()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/","title":"Multiprocess","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess","title":"faststream.cli.supervisors.multiprocess.Multiprocess","text":"
Multiprocess(\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    workers: int,\n)\n

Bases: BaseReload

A class to represent a multiprocess.

METHOD DESCRIPTION startup

starts the parent process and creates worker processes

shutdown

terminates and joins all worker processes, and stops the parent process

Initialize a new instance of the class.

PARAMETER DESCRIPTION target

The target callable object to be executed.

TYPE: DecoratedCallable

args

The arguments to be passed to the target callable.

TYPE: Tuple[Any, ...]

workers

The number of workers to be used.

TYPE: int

RETURNS DESCRIPTION None

None.

Source code in faststream/cli/supervisors/multiprocess.py
def __init__(\n    self,\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    workers: int,\n) -> None:\n    \"\"\"Initialize a new instance of the class.\n\n    Args:\n        target: The target callable object to be executed.\n        args: The arguments to be passed to the target callable.\n        workers: The number of workers to be used.\n\n    Returns:\n        None.\n\n    \"\"\"\n    super().__init__(target, args, None)\n\n    self.workers = workers\n    self.processes: List[SpawnProcess] = []\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.pid","title":"pid instance-attribute","text":"
pid: int = os.getpid()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.processes","title":"processes instance-attribute","text":"
processes: List[SpawnProcess] = []\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.reload_delay","title":"reload_delay instance-attribute","text":"
reload_delay: Optional[float] = reload_delay\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.reloader_name","title":"reloader_name class-attribute instance-attribute","text":"
reloader_name: str = ''\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.should_exit","title":"should_exit instance-attribute","text":"
should_exit: threading.Event = threading.Event()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.workers","title":"workers instance-attribute","text":"
workers = workers\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.restart","title":"restart","text":"
restart() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def restart(self) -> None:\n    self._stop_process()\n    logger.info(\"Process successfully reloaded\")\n    self._process = self._start_process()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.run","title":"run","text":"
run() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def run(self) -> None:\n    self.startup()\n    while not self.should_exit.wait(self.reload_delay):\n        if self.should_restart():  # pragma: no branch\n            self.restart()\n    self.shutdown()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.should_restart","title":"should_restart","text":"
should_restart() -> bool\n
Source code in faststream/cli/supervisors/basereload.py
def should_restart(self) -> bool:\n    raise NotImplementedError(\"Reload strategies should override should_restart()\")\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.shutdown","title":"shutdown","text":"
shutdown() -> None\n
Source code in faststream/cli/supervisors/multiprocess.py
def shutdown(self) -> None:\n    for process in self.processes:\n        process.terminate()\n        logger.info(f\"Stopping child process [{process.pid}]\")\n        process.join()\n\n    logger.info(f\"Stopping parent process [{self.pid}]\")\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.startup","title":"startup","text":"
startup() -> None\n
Source code in faststream/cli/supervisors/multiprocess.py
def startup(self) -> None:\n    logger.info(f\"Started parent process [{self.pid}]\")\n\n    for _ in range(self.workers):\n        process = self._start_process()\n        logger.info(f\"Started child process [{process.pid}]\")\n        self.processes.append(process)\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/get_subprocess/","title":"get_subprocess","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/get_subprocess/#faststream.cli.supervisors.utils.get_subprocess","title":"faststream.cli.supervisors.utils.get_subprocess","text":"
get_subprocess(\n    target: DecoratedCallableNone, args: Any\n) -> SpawnProcess\n

Spawn a subprocess.

PARAMETER DESCRIPTION target

The target function to be executed in the subprocess.

TYPE: DecoratedCallableNone

args

The arguments to be passed to the target function.

TYPE: Any

RETURNS DESCRIPTION SpawnProcess

The spawned subprocess.

RAISES DESCRIPTION OSError

If there is an error getting the file descriptor of sys.stdin.

Source code in faststream/cli/supervisors/utils.py
def get_subprocess(target: DecoratedCallableNone, args: Any) -> SpawnProcess:\n    \"\"\"Spawn a subprocess.\n\n    Args:\n        target: The target function to be executed in the subprocess.\n        args: The arguments to be passed to the target function.\n\n    Returns:\n        The spawned subprocess.\n\n    Raises:\n        OSError: If there is an error getting the file descriptor of sys.stdin.\n\n    \"\"\"\n    stdin_fileno: Optional[int]\n    try:\n        stdin_fileno = sys.stdin.fileno()\n    except OSError:\n        stdin_fileno = None\n\n    return spawn.Process(\n        target=subprocess_started,\n        args=args,\n        kwargs={\"t\": target, \"stdin_fileno\": stdin_fileno},\n    )\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/set_exit/","title":"set_exit","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/set_exit/#faststream.cli.supervisors.utils.set_exit","title":"faststream.cli.supervisors.utils.set_exit","text":"
set_exit(\n    func: Callable[[int, Optional[FrameType]], Any]\n) -> None\n

Set exit handler for signals.

PARAMETER DESCRIPTION func

A callable object that takes an integer and an optional frame type as arguments and returns any value.

TYPE: Callable[[int, Optional[FrameType]], Any]

RETURNS DESCRIPTION None

None

Source code in faststream/cli/supervisors/utils.py
def set_exit(func: Callable[[int, Optional[FrameType]], Any]) -> None:\n    \"\"\"Set exit handler for signals.\n\n    Args:\n        func: A callable object that takes an integer and an optional frame type as arguments and returns any value.\n\n    Returns:\n        None\n\n    \"\"\"\n    for sig in HANDLED_SIGNALS:\n        signal.signal(sig, func)\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/subprocess_started/","title":"subprocess_started","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/subprocess_started/#faststream.cli.supervisors.utils.subprocess_started","title":"faststream.cli.supervisors.utils.subprocess_started","text":"
subprocess_started(\n    *args: Any,\n    t: DecoratedCallableNone,\n    stdin_fileno: Optional[int]\n) -> None\n

Start a subprocess.

PARAMETER DESCRIPTION *args

Arguments to be passed to the subprocess.

TYPE: Any DEFAULT: ()

t

The decorated callable function.

TYPE: DecoratedCallableNone

stdin_fileno

File descriptor for the standard input of the subprocess.

TYPE: Optional[int]

RETURNS DESCRIPTION None

None

Source code in faststream/cli/supervisors/utils.py
def subprocess_started(\n    *args: Any,\n    t: DecoratedCallableNone,\n    stdin_fileno: Optional[int],\n) -> None:\n    \"\"\"Start a subprocess.\n\n    Args:\n        *args: Arguments to be passed to the subprocess.\n        t: The decorated callable function.\n        stdin_fileno: File descriptor for the standard input of the subprocess.\n\n    Returns:\n        None\n\n    \"\"\"\n    if stdin_fileno is not None:  # pragma: no cover\n        sys.stdin = os.fdopen(stdin_fileno)\n    t(*args)\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/ExtendedFilter/","title":"ExtendedFilter","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/ExtendedFilter/#faststream.cli.supervisors.watchfiles.ExtendedFilter","title":"faststream.cli.supervisors.watchfiles.ExtendedFilter","text":"
ExtendedFilter(\n    *,\n    ignore_paths: Optional[\n        Sequence[Union[str, Path]]\n    ] = None,\n    extra_extensions: Sequence[str] = ()\n)\n

Bases: PythonFilter

A class that extends the watchfiles.PythonFilter class.

METHOD DESCRIPTION __init__

Initializes the ExtendedFilter object Args: ignore_paths : Optional sequence of paths to ignore extra_extensions : Sequence of extra extensions to include

Returns: None

Initialize the class.

PARAMETER DESCRIPTION ignore_paths

Optional sequence of paths to ignore.

TYPE: Optional[Sequence[Union[str, Path]]] DEFAULT: None

extra_extensions

Sequence of extra extensions.

TYPE: Sequence[str] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/cli/supervisors/watchfiles.py
def __init__(\n    self,\n    *,\n    ignore_paths: Optional[Sequence[Union[str, Path]]] = None,\n    extra_extensions: Sequence[str] = (),\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        ignore_paths: Optional sequence of paths to ignore.\n        extra_extensions: Sequence of extra extensions.\n\n    Returns:\n        None\n\n    \"\"\"\n    super().__init__(ignore_paths=ignore_paths, extra_extensions=extra_extensions)\n    self.ignore_dirs = self.ignore_dirs + (\n        \"venv\",\n        \"env\",\n        \".github\",\n        \".mypy_cache\",\n        \".pytest_cache\",\n        \".ruff_cache\",\n        \"__pycache__\",\n    )\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/ExtendedFilter/#faststream.cli.supervisors.watchfiles.ExtendedFilter.ignore_dirs","title":"ignore_dirs instance-attribute","text":"
ignore_dirs: Tuple[str, ...] = self.ignore_dirs + (\n    \"venv\",\n    \"env\",\n    \".github\",\n    \".mypy_cache\",\n    \".pytest_cache\",\n    \".ruff_cache\",\n    \"__pycache__\",\n)\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/","title":"WatchReloader","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader","title":"faststream.cli.supervisors.watchfiles.WatchReloader","text":"
WatchReloader(\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    reload_dirs: Sequence[Union[Path, str]],\n    reload_delay: float = 0.3,\n    extra_extensions: Sequence[str] = (),\n)\n

Bases: BaseReload

A class to reload a target function when files in specified directories change.

METHOD DESCRIPTION should_restart

Checks if any files in the watched directories have changed and returns True if a change is detected, False otherwise.

Initialize a WatchFilesReloader object.

PARAMETER DESCRIPTION target

The target callable to be executed.

TYPE: DecoratedCallable

args

The arguments to be passed to the target callable.

TYPE: Tuple[Any, ...]

reload_dirs

A sequence of directories to watch for changes.

TYPE: Sequence[Union[Path, str]]

reload_delay

The delay in seconds between checking for changes. Default is 0.3.

TYPE: float DEFAULT: 0.3

RETURNS DESCRIPTION None

None.

Source code in faststream/cli/supervisors/watchfiles.py
def __init__(\n    self,\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    reload_dirs: Sequence[Union[Path, str]],\n    reload_delay: float = 0.3,\n    extra_extensions: Sequence[str] = (),\n) -> None:\n    \"\"\"Initialize a WatchFilesReloader object.\n\n    Args:\n        target: The target callable to be executed.\n        args: The arguments to be passed to the target callable.\n        reload_dirs: A sequence of directories to watch for changes.\n        reload_delay: The delay in seconds between checking for changes. Default is 0.3.\n\n    Returns:\n        None.\n\n    \"\"\"\n    super().__init__(target, args, reload_delay)\n    self.reloader_name = \"WatchFiles\"\n    self.reload_dirs = reload_dirs\n    self.watcher = watchfiles.watch(\n        *reload_dirs,\n        step=int(reload_delay * 1000),\n        watch_filter=ExtendedFilter(extra_extensions=extra_extensions),\n        stop_event=self.should_exit,\n        yield_on_timeout=True,\n    )\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.pid","title":"pid instance-attribute","text":"
pid: int = os.getpid()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.reload_delay","title":"reload_delay instance-attribute","text":"
reload_delay: Optional[float] = reload_delay\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.reload_dirs","title":"reload_dirs instance-attribute","text":"
reload_dirs = reload_dirs\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.reloader_name","title":"reloader_name instance-attribute","text":"
reloader_name = 'WatchFiles'\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.should_exit","title":"should_exit instance-attribute","text":"
should_exit: threading.Event = threading.Event()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.watcher","title":"watcher instance-attribute","text":"
watcher = watchfiles.watch(\n    *reload_dirs,\n    step=int(reload_delay * 1000),\n    watch_filter=ExtendedFilter(\n        extra_extensions=extra_extensions\n    ),\n    stop_event=self.should_exit,\n    yield_on_timeout=True\n)\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.restart","title":"restart","text":"
restart() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def restart(self) -> None:\n    self._stop_process()\n    logger.info(\"Process successfully reloaded\")\n    self._process = self._start_process()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.run","title":"run","text":"
run() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def run(self) -> None:\n    self.startup()\n    while not self.should_exit.wait(self.reload_delay):\n        if self.should_restart():  # pragma: no branch\n            self.restart()\n    self.shutdown()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.should_restart","title":"should_restart","text":"
should_restart() -> bool\n
Source code in faststream/cli/supervisors/watchfiles.py
def should_restart(self) -> bool:\n    for changes in self.watcher:  # pragma: no branch\n        if changes:  # pragma: no branch\n            unique_paths = {Path(c[1]).name for c in changes}\n            message = \"WatchReloader detected file change in '%s'. Reloading...\"\n            logger.info(message % tuple(unique_paths))\n            return True\n    return False  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.shutdown","title":"shutdown","text":"
shutdown() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def shutdown(self) -> None:\n    self._stop_process()\n    logger.info(f\"Stopping reloader process [{self.pid}]\")\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.startup","title":"startup","text":"
startup() -> None\n
Source code in faststream/cli/supervisors/watchfiles.py
def startup(self) -> None:\n    logger.info(f\"Will watch for changes in these directories: {self.reload_dirs}\")\n    super().startup()\n
","boost":0.5},{"location":"api/faststream/cli/utils/imports/get_app_path/","title":"get_app_path","text":"","boost":0.5},{"location":"api/faststream/cli/utils/imports/get_app_path/#faststream.cli.utils.imports.get_app_path","title":"faststream.cli.utils.imports.get_app_path","text":"
get_app_path(app: str) -> Tuple[Path, str]\n

Get the application path.

PARAMETER DESCRIPTION app

The name of the application in the format \"module:app_name\".

TYPE: str

RETURNS DESCRIPTION Tuple[Path, str]

Tuple[Path, str]: A tuple containing the path to the module and the name of the application.

RAISES DESCRIPTION ValueError

If the given app is not in the format \"module:app_name\".

Source code in faststream/cli/utils/imports.py
def get_app_path(app: str) -> Tuple[Path, str]:\n    \"\"\"Get the application path.\n\n    Args:\n        app (str): The name of the application in the format \"module:app_name\".\n\n    Returns:\n        Tuple[Path, str]: A tuple containing the path to the module and the name of the application.\n\n    Raises:\n        ValueError: If the given app is not in the format \"module:app_name\".\n\n    \"\"\"\n    if \":\" not in app:\n        raise ValueError(f\"{app} is not a FastStream\")\n\n    module, app_name = app.split(\":\", 2)\n\n    mod_path = Path.cwd()\n    for i in module.split(\".\"):\n        mod_path = mod_path / i\n\n    return mod_path, app_name\n
","boost":0.5},{"location":"api/faststream/cli/utils/imports/import_from_string/","title":"import_from_string","text":"","boost":0.5},{"location":"api/faststream/cli/utils/imports/import_from_string/#faststream.cli.utils.imports.import_from_string","title":"faststream.cli.utils.imports.import_from_string","text":"
import_from_string(\n    import_str: str,\n) -> Tuple[Path, FastStream]\n

Import FastStream application from module specified by a string.

PARAMETER DESCRIPTION import_str

A string in the format \":\" specifying the module and faststream application to import.

TYPE: str

RETURNS DESCRIPTION Tuple[Path, FastStream]

Tuple[ModuleType, FastStream]: A tuple containing the imported module and the faststream application.

RAISES DESCRIPTION BadParameter

Raised if the given value is not of type string, if the import string is not in the format \":\", if the module is not found, or if the faststream appliation is not found in the module. Source code in faststream/cli/utils/imports.py

def import_from_string(import_str: str) -> Tuple[Path, FastStream]:\n    \"\"\"\n    Import FastStream application from module specified by a string.\n\n    Parameters:\n        import_str (str): A string in the format \"<module>:<attribute>\" specifying the module and faststream application to import.\n\n    Returns:\n        Tuple[ModuleType, FastStream]: A tuple containing the imported module and the faststream application.\n\n    Raises:\n        typer.BadParameter: Raised if the given value is not of type string, if the import string is not in the format\n            \"<module>:<attribute>\", if the module is not found, or if the faststream appliation is not found in the module.\n    \"\"\"\n    if not isinstance(import_str, str):\n        raise typer.BadParameter(\"Given value is not of type string\")\n\n    module_str, _, attrs_str = import_str.partition(\":\")\n    if not module_str or not attrs_str:\n        raise typer.BadParameter(\n            f'Import string \"{import_str}\" must be in format \"<module>:<attribute>\"'\n        )\n\n    try:\n        module = importlib.import_module(  # nosemgrep: python.lang.security.audit.non-literal-import.non-literal-import\n            module_str\n        )\n\n    except ModuleNotFoundError:\n        module_path, app_name = get_app_path(import_str)\n        instance = try_import_app(module_path, app_name)\n\n    else:\n        attr = module\n        try:\n            for attr_str in attrs_str.split(\".\"):\n                attr = getattr(attr, attr_str)\n            instance = attr  # type: ignore[assignment]\n\n        except AttributeError as e:\n            typer.echo(e, err=True)\n            raise typer.BadParameter(\n                f'Attribute \"{attrs_str}\" not found in module \"{module_str}\".'\n            ) from e\n\n        if module.__file__:\n            module_path = Path(module.__file__).resolve().parent\n        else:\n            module_path = Path.cwd()\n\n    return module_path, instance\n
","boost":0.5},{"location":"api/faststream/cli/utils/imports/import_object/","title":"import_object","text":"","boost":0.5},{"location":"api/faststream/cli/utils/imports/import_object/#faststream.cli.utils.imports.import_object","title":"faststream.cli.utils.imports.import_object","text":"
import_object(module: Path, app: str) -> object\n

Import an object from a module.

PARAMETER DESCRIPTION module

The path to the module file.

TYPE: Path

app

The name of the object to import.

TYPE: str

RETURNS DESCRIPTION object

The imported object.

RAISES DESCRIPTION FileNotFoundError

If the module file is not found.

ValueError

If the module has no loader.

AttributeError

If the object is not found in the module.

Source code in faststream/cli/utils/imports.py
def import_object(module: Path, app: str) -> object:\n    \"\"\"Import an object from a module.\n\n    Args:\n        module: The path to the module file.\n        app: The name of the object to import.\n\n    Returns:\n        The imported object.\n\n    Raises:\n        FileNotFoundError: If the module file is not found.\n        ValueError: If the module has no loader.\n        AttributeError: If the object is not found in the module.\n\n    \"\"\"\n    spec = spec_from_file_location(\n        \"mode\",\n        f\"{module}.py\",\n        submodule_search_locations=[str(module.parent.absolute())],\n    )\n\n    if spec is None:  # pragma: no cover\n        raise FileNotFoundError(module)\n\n    mod = module_from_spec(spec)\n    loader = spec.loader\n\n    if loader is None:  # pragma: no cover\n        raise ValueError(f\"{spec} has no loader\")\n\n    loader.exec_module(mod)\n\n    try:\n        obj = getattr(mod, app)\n    except AttributeError as e:\n        raise FileNotFoundError(module) from e\n\n    return obj\n
","boost":0.5},{"location":"api/faststream/cli/utils/imports/try_import_app/","title":"try_import_app","text":"","boost":0.5},{"location":"api/faststream/cli/utils/imports/try_import_app/#faststream.cli.utils.imports.try_import_app","title":"faststream.cli.utils.imports.try_import_app","text":"
try_import_app(module: Path, app: str) -> FastStream\n

Tries to import a FastStream app from a module.

PARAMETER DESCRIPTION module

Path to the module containing the app.

TYPE: Path

app

Name of the FastStream app.

TYPE: str

RETURNS DESCRIPTION FastStream

The imported FastStream app object.

RAISES DESCRIPTION FileNotFoundError

If the module file is not found.

BadParameter

If the module or app name is not provided correctly.

Source code in faststream/cli/utils/imports.py
def try_import_app(module: Path, app: str) -> FastStream:\n    \"\"\"Tries to import a FastStream app from a module.\n\n    Args:\n        module: Path to the module containing the app.\n        app: Name of the FastStream app.\n\n    Returns:\n        The imported FastStream app object.\n\n    Raises:\n        FileNotFoundError: If the module file is not found.\n        typer.BadParameter: If the module or app name is not provided correctly.\n\n    \"\"\"\n    try:\n        app_object = import_object(module, app)\n\n    except FileNotFoundError as e:\n        typer.echo(e, err=True)\n        raise typer.BadParameter(\n            \"Please, input module like [python_file:faststream_app_name] or [module:attribute]\"\n        ) from e\n\n    else:\n        return app_object  # type: ignore\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/","title":"LogLevels","text":"","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels","title":"faststream.cli.utils.logs.LogLevels","text":"

Bases: str, Enum

A class to represent log levels.

","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels.critical","title":"critical class-attribute instance-attribute","text":"
critical = 'critical'\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels.debug","title":"debug class-attribute instance-attribute","text":"
debug = 'debug'\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels.error","title":"error class-attribute instance-attribute","text":"
error = 'error'\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels.info","title":"info class-attribute instance-attribute","text":"
info = 'info'\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels.warning","title":"warning class-attribute instance-attribute","text":"
warning = 'warning'\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/get_log_level/","title":"get_log_level","text":"","boost":0.5},{"location":"api/faststream/cli/utils/logs/get_log_level/#faststream.cli.utils.logs.get_log_level","title":"faststream.cli.utils.logs.get_log_level","text":"
get_log_level(level: Union[LogLevels, str, int]) -> int\n

Get the log level.

PARAMETER DESCRIPTION level

The log level to get. Can be an integer, a LogLevels enum value, or a string.

TYPE: Union[LogLevels, str, int]

RETURNS DESCRIPTION int

The log level as an integer.

Source code in faststream/cli/utils/logs.py
def get_log_level(level: Union[LogLevels, str, int]) -> int:\n    \"\"\"Get the log level.\n\n    Args:\n        level: The log level to get. Can be an integer, a LogLevels enum value, or a string.\n\n    Returns:\n        The log level as an integer.\n\n    \"\"\"\n    if isinstance(level, int):\n        return level\n\n    if isinstance(level, LogLevels):\n        return LOG_LEVELS[level.value]\n\n    if isinstance(level, str):  # pragma: no branch\n        return LOG_LEVELS[level.lower()]\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/set_log_level/","title":"set_log_level","text":"","boost":0.5},{"location":"api/faststream/cli/utils/logs/set_log_level/#faststream.cli.utils.logs.set_log_level","title":"faststream.cli.utils.logs.set_log_level","text":"
set_log_level(level: int, app: FastStream) -> None\n

Sets the log level for an application.

PARAMETER DESCRIPTION level

The log level to set.

TYPE: int

app

The application object.

TYPE: FastStream

RETURNS DESCRIPTION None

None

Source code in faststream/cli/utils/logs.py
def set_log_level(level: int, app: FastStream) -> None:\n    \"\"\"Sets the log level for an application.\n\n    Args:\n        level (int): The log level to set.\n        app (FastStream): The application object.\n\n    Returns:\n        None\n\n    \"\"\"\n    if app.logger and isinstance(app.logger, logging.Logger):\n        app.logger.setLevel(level)\n\n    broker_logger: Optional[logging.Logger] = getattr(app.broker, \"logger\", None)\n    if broker_logger is not None and isinstance(broker_logger, logging.Logger):\n        broker_logger.setLevel(level)\n
","boost":0.5},{"location":"api/faststream/cli/utils/parser/parse_cli_args/","title":"parse_cli_args","text":"","boost":0.5},{"location":"api/faststream/cli/utils/parser/parse_cli_args/#faststream.cli.utils.parser.parse_cli_args","title":"faststream.cli.utils.parser.parse_cli_args","text":"
parse_cli_args(\n    *args: str,\n) -> Tuple[str, Dict[str, SettingField]]\n

Parses command line arguments.

PARAMETER DESCRIPTION *args

Command line arguments as strings.

TYPE: str DEFAULT: ()

RETURNS DESCRIPTION Tuple[str, Dict[str, SettingField]]

A tuple containing the application name and a dictionary of additional keyword arguments.

Source code in faststream/cli/utils/parser.py
def parse_cli_args(*args: str) -> Tuple[str, Dict[str, SettingField]]:\n    \"\"\"Parses command line arguments.\n\n    Args:\n        *args: Command line arguments as strings.\n\n    Returns:\n        A tuple containing the application name and a dictionary of additional keyword arguments.\n    \"\"\"\n    extra_kwargs: Dict[str, SettingField] = {}\n\n    k: str = \"\"\n    v: SettingField\n\n    field_args: List[str] = []\n    app = \"\"\n    for item in reduce(\n        lambda acc, x: acc + x.split(\"=\"),  # type: ignore\n        args,\n        [],\n    ) + [\"-\"]:\n        if \":\" in item:\n            app = item\n\n        else:\n            if \"-\" in item:\n                if k:\n                    k = k.strip().lstrip(\"-\").replace(\"-\", \"_\")\n\n                    if len(field_args) == 0:\n                        v = not k.startswith(\"no_\")\n                    elif len(field_args) == 1:\n                        v = field_args[0]\n                    else:\n                        v = field_args\n\n                    key = remove_prefix(k, \"no_\")\n                    if (exists := extra_kwargs.get(key)) is not None:\n                        if not isinstance(exists, list):\n                            v = [exists, v]\n                        else:\n                            v = exists + [v]\n\n                    extra_kwargs[key] = v\n                    field_args = []\n\n                k = item\n\n            else:\n                field_args.append(item)\n\n    return app, extra_kwargs\n
","boost":0.5},{"location":"api/faststream/cli/utils/parser/remove_prefix/","title":"remove_prefix","text":"","boost":0.5},{"location":"api/faststream/cli/utils/parser/remove_prefix/#faststream.cli.utils.parser.remove_prefix","title":"faststream.cli.utils.parser.remove_prefix","text":"
remove_prefix(text: str, prefix: str) -> str\n

Removes a prefix from a given text.

Python 3.8 compatibility function

PARAMETER DESCRIPTION text

The text from which the prefix will be removed.

TYPE: str

prefix

The prefix to be removed from the text.

TYPE: str

RETURNS DESCRIPTION str

The text with the prefix removed. If the text does not start with the prefix, the original text is returned.

TYPE: str

Source code in faststream/cli/utils/parser.py
def remove_prefix(text: str, prefix: str) -> str:\n    \"\"\"Removes a prefix from a given text.\n\n    Python 3.8 compatibility function\n\n    Args:\n        text (str): The text from which the prefix will be removed.\n        prefix (str): The prefix to be removed from the text.\n\n    Returns:\n        str: The text with the prefix removed. If the text does not start with the prefix, the original text is returned.\n    \"\"\"\n    if text.startswith(prefix):\n        return text[len(prefix) :]\n    return text\n
","boost":0.5},{"location":"api/faststream/constants/ContentTypes/","title":"ContentTypes","text":"","boost":0.5},{"location":"api/faststream/constants/ContentTypes/#faststream.constants.ContentTypes","title":"faststream.constants.ContentTypes","text":"

Bases: str, Enum

A class to represent content types.

","boost":0.5},{"location":"api/faststream/constants/ContentTypes/#faststream.constants.ContentTypes.json","title":"json class-attribute instance-attribute","text":"
json = 'application/json'\n
","boost":0.5},{"location":"api/faststream/constants/ContentTypes/#faststream.constants.ContentTypes.text","title":"text class-attribute instance-attribute","text":"
text = 'text/plain'\n
","boost":0.5},{"location":"api/faststream/exceptions/AckMessage/","title":"AckMessage","text":"","boost":0.5},{"location":"api/faststream/exceptions/AckMessage/#faststream.exceptions.AckMessage","title":"faststream.exceptions.AckMessage","text":"

Bases: HandlerException

Raise it to ack a message immediately

","boost":0.5},{"location":"api/faststream/exceptions/HandlerException/","title":"HandlerException","text":"","boost":0.5},{"location":"api/faststream/exceptions/HandlerException/#faststream.exceptions.HandlerException","title":"faststream.exceptions.HandlerException","text":"

Bases: Exception

Base Handler Exception

","boost":0.5},{"location":"api/faststream/exceptions/NackMessage/","title":"NackMessage","text":"","boost":0.5},{"location":"api/faststream/exceptions/NackMessage/#faststream.exceptions.NackMessage","title":"faststream.exceptions.NackMessage","text":"

Bases: HandlerException

Raise it to nack a message immediately

","boost":0.5},{"location":"api/faststream/exceptions/RejectMessage/","title":"RejectMessage","text":"","boost":0.5},{"location":"api/faststream/exceptions/RejectMessage/#faststream.exceptions.RejectMessage","title":"faststream.exceptions.RejectMessage","text":"

Bases: HandlerException

Raise it to reject a message immediately

","boost":0.5},{"location":"api/faststream/exceptions/SkipMessage/","title":"SkipMessage","text":"","boost":0.5},{"location":"api/faststream/exceptions/SkipMessage/#faststream.exceptions.SkipMessage","title":"faststream.exceptions.SkipMessage","text":"

Bases: Exception

Watcher Instruction to skip message

","boost":0.5},{"location":"api/faststream/exceptions/StopConsume/","title":"StopConsume","text":"","boost":0.5},{"location":"api/faststream/exceptions/StopConsume/#faststream.exceptions.StopConsume","title":"faststream.exceptions.StopConsume","text":"

Bases: Exception

Raise it to stop Handler consuming

","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/","title":"KafkaBroker","text":"","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker","title":"faststream.kafka.KafkaBroker","text":"
KafkaBroker(\n    bootstrap_servers: Union[\n        str, Iterable[str]\n    ] = \"localhost\",\n    *,\n    protocol: str = None,\n    protocol_version: str = \"auto\",\n    client_id: str = \"faststream-\" + __version__,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: KafkaLoggingMixin, BrokerAsyncUsecase[ConsumerRecord, ConsumerConnectionParams]

KafkaBroker is a class for managing Kafka message consumption and publishing. It extends BrokerAsyncUsecase to handle asynchronous operations.

PARAMETER DESCRIPTION bootstrap_servers

Kafka bootstrap server(s).

TYPE: Union[str, Iterable[str]] DEFAULT: 'localhost'

protocol

The protocol used (default is \"kafka\").

TYPE: str DEFAULT: None

protocol_version

The Kafka protocol version (default is \"auto\").

TYPE: str DEFAULT: 'auto'

client_id

The client ID for the Kafka client.

TYPE: str DEFAULT: 'faststream-' + __version__

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

METHOD DESCRIPTION connect

Establishes a connection to Kafka.

start

Starts the KafkaBroker and message handlers.

publish

Publishes a message to Kafka.

Initialize a KafkaBroker instance.

PARAMETER DESCRIPTION bootstrap_servers

Kafka bootstrap server(s).

TYPE: Union[str, Iterable[str]] DEFAULT: 'localhost'

protocol

The protocol used (default is \"kafka\").

TYPE: str DEFAULT: None

protocol_version

The Kafka protocol version (default is \"auto\").

TYPE: str DEFAULT: 'auto'

client_id

The client ID for the Kafka client.

TYPE: str DEFAULT: 'faststream-' + __version__

security

Security protocol to use in communication with the broker (default is None).

TYPE: Optional[BaseSecurity] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/kafka/broker.py
def __init__(\n    self,\n    bootstrap_servers: Union[str, Iterable[str]] = \"localhost\",\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: str = \"auto\",\n    client_id: str = \"faststream-\" + __version__,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Initialize a KafkaBroker instance.\n\n    Args:\n        bootstrap_servers (Union[str, Iterable[str]]): Kafka bootstrap server(s).\n        protocol (str): The protocol used (default is \"kafka\").\n        protocol_version (str): The Kafka protocol version (default is \"auto\").\n        client_id (str): The client ID for the Kafka client.\n        security (Optional[BaseSecurity]): Security protocol to use in communication with the broker (default is None).\n        **kwargs: Additional keyword arguments.\n    \"\"\"\n    if protocol is None:\n        if security is not None and security.use_ssl:\n            protocol = \"kafka-secure\"\n        else:\n            protocol = \"kafka\"\n\n    super().__init__(\n        url=[bootstrap_servers]\n        if isinstance(bootstrap_servers, str)\n        else list(bootstrap_servers),\n        protocol=protocol,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n        client_id=client_id,\n        bootstrap_servers=bootstrap_servers,\n    )\n    self.client_id = client_id\n    self._producer = None\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.client_id","title":"client_id instance-attribute","text":"
client_id = client_id\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[str, Handler]\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.url","title":"url instance-attribute","text":"
url: List[str]\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.connect","title":"connect async","text":"
connect(\n    *args: Any, **kwargs: Any\n) -> ConsumerConnectionParams\n

Establishes a connection to Kafka and returns connection parameters.

PARAMETER DESCRIPTION *args

Additional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION ConsumerConnectionParams

The connection parameters.

TYPE: ConsumerConnectionParams

Source code in faststream/kafka/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> ConsumerConnectionParams:\n    \"\"\"\n    Establishes a connection to Kafka and returns connection parameters.\n\n    Args:\n        *args: Additional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        ConsumerConnectionParams: The connection parameters.\n    \"\"\"\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.publish","title":"publish async","text":"
publish(*args: Any, **kwargs: Any) -> None\n

Publish a message to Kafka.

PARAMETER DESCRIPTION *args

Positional arguments for message publishing.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments for message publishing.

TYPE: Any DEFAULT: {}

RAISES DESCRIPTION RuntimeError

If KafkaBroker is not started yet.

Source code in faststream/kafka/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Publish a message to Kafka.\n\n    Args:\n        *args: Positional arguments for message publishing.\n        **kwargs: Keyword arguments for message publishing.\n\n    Raises:\n        RuntimeError: If KafkaBroker is not started yet.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.publish_batch","title":"publish_batch async","text":"
publish_batch(*args: Any, **kwargs: Any) -> None\n

Publish a batch of messages to Kafka.

PARAMETER DESCRIPTION *args

Positional arguments for message publishing.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments for message publishing.

TYPE: Any DEFAULT: {}

RAISES DESCRIPTION RuntimeError

If KafkaBroker is not started yet.

Source code in faststream/kafka/broker.py
async def publish_batch(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Publish a batch of messages to Kafka.\n\n    Args:\n        *args: Positional arguments for message publishing.\n        **kwargs: Keyword arguments for message publishing.\n\n    Raises:\n        RuntimeError: If KafkaBroker is not started yet.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    await self._producer.publish_batch(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.publisher","title":"publisher","text":"
publisher(\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n

Create a message publisher for the specified topic.

PARAMETER DESCRIPTION topic

The topic to publish messages to.

TYPE: str

key

Message key.

TYPE: Optional[bytes] DEFAULT: None

partition

Partition to send the message to.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

Message timestamp in milliseconds.

TYPE: Optional[int] DEFAULT: None

headers

Message headers.

TYPE: Optional[Dict[str, str]] DEFAULT: None

reply_to

The topic to which responses should be sent.

TYPE: str DEFAULT: ''

batch

Whether to publish messages in batches.

TYPE: bool DEFAULT: False

title

AsyncAPI title.

TYPE: Optional[str] DEFAULT: None

description

AsyncAPI description.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION Publisher

A message publisher.

TYPE: Publisher

Source code in faststream/kafka/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"\n    Create a message publisher for the specified topic.\n\n    Args:\n        topic (str): The topic to publish messages to.\n        key (Optional[bytes]): Message key.\n        partition (Optional[int]): Partition to send the message to.\n        timestamp_ms (Optional[int]): Message timestamp in milliseconds.\n        headers (Optional[Dict[str, str]]): Message headers.\n        reply_to (str): The topic to which responses should be sent.\n        batch (bool): Whether to publish messages in batches.\n        title (Optional[str]): AsyncAPI title.\n        description (Optional[str]): AsyncAPI description.\n\n    Returns:\n        Publisher: A message publisher.\n    \"\"\"\n    publisher = self._publishers.get(\n        topic,\n        Publisher(\n            topic=topic,\n            client_id=self.client_id,\n            key=key,\n            batch=batch,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(topic, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.start","title":"start async","text":"
start() -> None\n

Start the KafkaBroker and message handlers.

Source code in faststream/kafka/broker.py
async def start(self) -> None:\n    \"\"\"\n    Start the KafkaBroker and message handlers.\n    \"\"\"\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n\n    for handler in self.handlers.values():\n        c = self._get_log_context(None, handler.topics, handler.group_id)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(**(self._connection or {}))\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.subscriber","title":"subscriber","text":"
subscriber(\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    value_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\", \"earliest\", \"none\"\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[\n        AbstractPartitionAssignor\n    ] = (RoundRobinPartitionAssignor),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\", \"read_committed\"\n    ] = \"read_uncommitted\",\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        Union[\n            CustomParser[\n                aiokafka.ConsumerRecord, KafkaMessage\n            ],\n            CustomParser[\n                Tuple[aiokafka.ConsumerRecord, ...],\n                KafkaMessage,\n            ],\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[\n            StreamMessage[\n                Tuple[aiokafka.ConsumerRecord, ...]\n            ]\n        ],\n    ] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    Union[\n        HandlerCallWrapper[\n            aiokafka.ConsumerRecord,\n            P_HandlerParams,\n            T_HandlerReturn,\n        ],\n        HandlerCallWrapper[\n            Tuple[aiokafka.ConsumerRecord, ...],\n            P_HandlerParams,\n            T_HandlerReturn,\n        ],\n    ],\n]\n

Create a message subscriber for the specified topics.

PARAMETER DESCRIPTION *topics

The topics to subscribe to.

TYPE: str DEFAULT: ()

group_id

The Kafka consumer group ID.

TYPE: Optional[str] DEFAULT: None

key_deserializer

Key deserializer function.

TYPE: Optional[Callable[[bytes], Any]] DEFAULT: None

value_deserializer

Value deserializer function.

TYPE: Optional[Callable[[bytes], Any]] DEFAULT: None

fetch_max_wait_ms

The maximum time to wait for data.

TYPE: int DEFAULT: 500

fetch_max_bytes

The maximum number of bytes to fetch.

TYPE: int DEFAULT: 52428800

fetch_min_bytes

The minimum number of bytes to fetch.

TYPE: int DEFAULT: 1

max_partition_fetch_bytes

The maximum bytes to fetch for a partition.

TYPE: int DEFAULT: 1 * 1024 * 1024

auto_offset_reset

Auto offset reset policy.

TYPE: Literal['latest', 'earliest', 'none'] DEFAULT: 'latest'

auto_commit

Whether to enable auto-commit.

TYPE: bool DEFAULT: True

auto_commit_interval_ms

Auto-commit interval in milliseconds.

TYPE: int DEFAULT: 5000

check_crcs

Whether to check CRCs.

TYPE: bool DEFAULT: True

partition_assignment_strategy

Partition assignment strategy.

TYPE: Sequence[AbstractPartitionAssignor] DEFAULT: (RoundRobinPartitionAssignor)

max_poll_interval_ms

Maximum poll interval in milliseconds.

TYPE: int DEFAULT: 300000

rebalance_timeout_ms

Rebalance timeout in milliseconds.

TYPE: Optional[int] DEFAULT: None

session_timeout_ms

Session timeout in milliseconds.

TYPE: int DEFAULT: 10000

heartbeat_interval_ms

Heartbeat interval in milliseconds.

TYPE: int DEFAULT: 3000

consumer_timeout_ms

Consumer timeout in milliseconds.

TYPE: int DEFAULT: 200

max_poll_records

Maximum number of records to poll.

TYPE: Optional[int] DEFAULT: None

exclude_internal_topics

Whether to exclude internal topics.

TYPE: bool DEFAULT: True

isolation_level

Isolation level.

TYPE: Literal['read_uncommitted', 'read_committed'] DEFAULT: 'read_uncommitted'

dependencies

Additional dependencies for message handling.

TYPE: Sequence[Depends] DEFAULT: ()

parser

Message parser.

TYPE: Optional[Union[CustomParser[ConsumerRecord], CustomParser[Tuple[ConsumerRecord, ...]]]] DEFAULT: None

decoder

Message decoder.

TYPE: Optional[CustomDecoder] DEFAULT: None

middlewares

Message middlewares.

TYPE: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]] DEFAULT: None

filter

Message filter.

TYPE: Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[ConsumerRecord, ...]]]] DEFAULT: default_filter

batch

Whether to process messages in batches.

TYPE: bool DEFAULT: False

max_records

Maximum number of records to process in each batch.

TYPE: Optional[int] DEFAULT: None

batch_timeout_ms

Batch timeout in milliseconds.

TYPE: int DEFAULT: 200

no_ack

Whether not to ack/nack/reject messages.

TYPE: bool DEFAULT: False

title

AsyncAPI title.

TYPE: Optional[str] DEFAULT: None

description

AsyncAPI description.

TYPE: Optional[str] DEFAULT: None

**original_kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Callable

A decorator that wraps a message handler function.

TYPE: Callable[[Callable[P_HandlerParams, T_HandlerReturn]], Union[HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[Tuple[ConsumerRecord, ...], P_HandlerParams, T_HandlerReturn]]]

Source code in faststream/kafka/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[Callable[[bytes], Any]] = None,\n    value_deserializer: Optional[Callable[[bytes], Any]] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\",\n        \"earliest\",\n        \"none\",\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[AbstractPartitionAssignor] = (\n        RoundRobinPartitionAssignor,\n    ),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\",\n        \"read_committed\",\n    ] = \"read_uncommitted\",\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        Union[\n            CustomParser[aiokafka.ConsumerRecord, KafkaMessage],\n            CustomParser[Tuple[aiokafka.ConsumerRecord, ...], KafkaMessage],\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord],\n                BaseMiddleware,\n            ]\n        ]\n    ] = None,\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[aiokafka.ConsumerRecord, ...]]],\n    ] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    Union[\n        HandlerCallWrapper[\n            aiokafka.ConsumerRecord, P_HandlerParams, T_HandlerReturn\n        ],\n        HandlerCallWrapper[\n            Tuple[aiokafka.ConsumerRecord, ...], P_HandlerParams, T_HandlerReturn\n        ],\n    ],\n]:\n    \"\"\"\n    Create a message subscriber for the specified topics.\n\n    Args:\n        *topics (str): The topics to subscribe to.\n        group_id (Optional[str]): The Kafka consumer group ID.\n        key_deserializer (Optional[Callable[[bytes], Any]]): Key deserializer function.\n        value_deserializer (Optional[Callable[[bytes], Any]]): Value deserializer function.\n        fetch_max_wait_ms (int): The maximum time to wait for data.\n        fetch_max_bytes (int): The maximum number of bytes to fetch.\n        fetch_min_bytes (int): The minimum number of bytes to fetch.\n        max_partition_fetch_bytes (int): The maximum bytes to fetch for a partition.\n        auto_offset_reset (Literal[\"latest\", \"earliest\", \"none\"]): Auto offset reset policy.\n        auto_commit (bool): Whether to enable auto-commit.\n        auto_commit_interval_ms (int): Auto-commit interval in milliseconds.\n        check_crcs (bool): Whether to check CRCs.\n        partition_assignment_strategy (Sequence[AbstractPartitionAssignor]): Partition assignment strategy.\n        max_poll_interval_ms (int): Maximum poll interval in milliseconds.\n        rebalance_timeout_ms (Optional[int]): Rebalance timeout in milliseconds.\n        session_timeout_ms (int): Session timeout in milliseconds.\n        heartbeat_interval_ms (int): Heartbeat interval in milliseconds.\n        consumer_timeout_ms (int): Consumer timeout in milliseconds.\n        max_poll_records (Optional[int]): Maximum number of records to poll.\n        exclude_internal_topics (bool): Whether to exclude internal topics.\n        isolation_level (Literal[\"read_uncommitted\", \"read_committed\"]): Isolation level.\n        dependencies (Sequence[Depends]): Additional dependencies for message handling.\n        parser (Optional[Union[CustomParser[aiokafka.ConsumerRecord], CustomParser[Tuple[aiokafka.ConsumerRecord, ...]]]]): Message parser.\n        decoder (Optional[CustomDecoder]): Message decoder.\n        middlewares (Optional[Sequence[Callable[[aiokafka.ConsumerRecord], BaseMiddleware]]]): Message middlewares.\n        filter (Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[aiokafka.ConsumerRecord, ...]]]]): Message filter.\n        batch (bool): Whether to process messages in batches.\n        max_records (Optional[int]): Maximum number of records to process in each batch.\n        batch_timeout_ms (int): Batch timeout in milliseconds.\n        no_ack (bool): Whether not to ack/nack/reject messages.\n        title (Optional[str]): AsyncAPI title.\n        description (Optional[str]): AsyncAPI description.\n        **original_kwargs: Additional keyword arguments.\n\n    Returns:\n        Callable: A decorator that wraps a message handler function.\n    \"\"\"\n    super().subscriber()\n\n    self._setup_log_context(topics, group_id)\n\n    if not auto_commit and not group_id:\n        raise ValueError(\"You should install `group_id` with manual commit mode\")\n\n    key = Handler.get_routing_hash(topics, group_id)\n    builder = partial(\n        aiokafka.AIOKafkaConsumer,\n        key_deserializer=key_deserializer,\n        value_deserializer=value_deserializer,\n        fetch_max_wait_ms=fetch_max_wait_ms,\n        fetch_max_bytes=fetch_max_bytes,\n        fetch_min_bytes=fetch_min_bytes,\n        max_partition_fetch_bytes=max_partition_fetch_bytes,\n        auto_offset_reset=auto_offset_reset,\n        enable_auto_commit=auto_commit,\n        auto_commit_interval_ms=auto_commit_interval_ms,\n        check_crcs=check_crcs,\n        partition_assignment_strategy=partition_assignment_strategy,\n        max_poll_interval_ms=max_poll_interval_ms,\n        rebalance_timeout_ms=rebalance_timeout_ms,\n        session_timeout_ms=session_timeout_ms,\n        heartbeat_interval_ms=heartbeat_interval_ms,\n        consumer_timeout_ms=consumer_timeout_ms,\n        max_poll_records=max_poll_records,\n        exclude_internal_topics=exclude_internal_topics,\n        isolation_level=isolation_level,\n    )\n    handler = self.handlers.get(\n        key,\n        Handler(\n            *topics,\n            log_context_builder=partial(\n                self._get_log_context,\n                topics=topics,\n                group_id=group_id,\n            ),\n            is_manual=not auto_commit,\n            group_id=group_id,\n            client_id=self.client_id,\n            builder=builder,\n            description=description,\n            title=title,\n            batch=batch,\n            batch_timeout_ms=batch_timeout_ms,\n            max_records=max_records,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n        ),\n    )\n\n    self.handlers[key] = handler\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[\n        aiokafka.ConsumerRecord, P_HandlerParams, T_HandlerReturn\n    ]:\n        \"\"\"A wrapper function for a consumer handler.\n\n        Args:\n            func : The consumer handler function to be wrapped.\n\n        Returns:\n            The wrapped handler call.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        handler_call, dependant = self._wrap_handler(\n            func=func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRoute/","title":"KafkaRoute","text":"","boost":0.5},{"location":"api/faststream/kafka/KafkaRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/","title":"KafkaRouter","text":"","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter","title":"faststream.kafka.KafkaRouter","text":"
KafkaRouter(\n    prefix: str = \"\",\n    handlers: Sequence[KafkaRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[aiokafka.ConsumerRecord, KafkaMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[KafkaMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: KafkaRouter

A class to represent a Kafka router.

METHOD DESCRIPTION _get_publisher_key

Get the key for a publisher

_update_publisher_prefix

Update the prefix of a publisher

publisher

Create a new publisher

Source code in faststream/kafka/router.py
        publisher: The publisher object.\n\n    Returns:\n        The publisher key.\n\n    \"\"\"\n    return publisher.topic\n\n@override\n@staticmethod\ndef _update_publisher_prefix(  # type: ignore[override]\n    prefix: str,\n    publisher: Publisher,\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.publisher","title":"publisher","text":"
publisher(\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n

Publishes a message to a topic.

PARAMETER DESCRIPTION topic

The topic to publish the message to.

TYPE: str

key

The key associated with the message.

TYPE: bytes DEFAULT: None

partition

The partition to publish the message to.

TYPE: int DEFAULT: None

timestamp_ms

The timestamp of the message in milliseconds.

TYPE: int DEFAULT: None

headers

Additional headers for the message.

TYPE: Dict[str, str] DEFAULT: None

reply_to

The topic to reply to.

TYPE: str DEFAULT: ''

batch

Whether to publish the message as part of a batch.

TYPE: bool DEFAULT: False

title

The title of the message.

TYPE: str DEFAULT: None

description

The description of the message.

TYPE: str DEFAULT: None

RETURNS DESCRIPTION Publisher

The publisher object used to publish the message.

TYPE: Publisher

Source code in faststream/kafka/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"Publishes a message to a topic.\n\n    Args:\n        topic (str): The topic to publish the message to.\n        key (bytes, optional): The key associated with the message.\n        partition (int, optional): The partition to publish the message to.\n        timestamp_ms (int, optional): The timestamp of the message in milliseconds.\n        headers (Dict[str, str], optional): Additional headers for the message.\n        reply_to (str, optional): The topic to reply to.\n        batch (bool, optional): Whether to publish the message as part of a batch.\n        title (str, optional): The title of the message.\n        description (str, optional): The description of the message.\n\n    Returns:\n        Publisher: The publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            topic=topic,\n            key=key,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            batch=batch,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.subscriber","title":"subscriber","text":"
subscriber(\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    value_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\", \"earliest\", \"none\"\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[\n        AbstractPartitionAssignor\n    ] = (RoundRobinPartitionAssignor),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\", \"read_committed\"\n    ] = \"read_uncommitted\",\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[aiokafka.ConsumerRecord, KafkaMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[KafkaMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Filter[KafkaMessage] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    retry: Union[bool, int] = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aiokafka.ConsumerRecord,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n
Source code in faststream/kafka/router.py
    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"Publishes a message to a topic.\n\n    Args:\n        topic (str): The topic to publish the message to.\n        key (bytes, optional): The key associated with the message.\n        partition (int, optional): The partition to publish the message to.\n        timestamp_ms (int, optional): The timestamp of the message in milliseconds.\n        headers (Dict[str, str], optional): Additional headers for the message.\n        reply_to (str, optional): The topic to reply to.\n        batch (bool, optional): Whether to publish the message as part of a batch.\n        title (str, optional): The title of the message.\n        description (str, optional): The description of the message.\n\n    Returns:\n        Publisher: The publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            topic=topic,\n            key=key,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            batch=batch,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/kafka/TestApp/#faststream.broker.test.TestApp","title":"faststream.broker.test.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/kafka/TestApp/#faststream.broker.test.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/","title":"TestKafkaBroker","text":"","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker","title":"faststream.kafka.TestKafkaBroker","text":"
TestKafkaBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[KafkaBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/kafka/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: KafkaBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(  # type: ignore[call-overload,misc]\n        publisher.topic,\n        batch=publisher.batch,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f  # type: ignore[no-any-return]\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: KafkaBroker, publisher: Any\n) -> None\n
Source code in faststream/kafka/test.py
@staticmethod\ndef patch_publisher(broker: KafkaBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> None\n
Source code in faststream/kafka/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> None:\n    broker.handlers.pop(publisher.topic, None)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/","title":"Handler","text":"","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler","title":"faststream.kafka.asyncapi.Handler","text":"
Handler(\n    *topics: str,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    group_id: Optional[str] = None,\n    client_id: str = \"faststream-\" + __version__,\n    builder: Callable[..., AIOKafkaConsumer],\n    is_manual: bool = False,\n    batch: bool = False,\n    batch_timeout_ms: int = 200,\n    max_records: Optional[int] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True\n)\n

Bases: LogicHandler, AsyncAPIOperation

A class to handle logic and async API operations.

METHOD DESCRIPTION schema

Returns a dictionary of channels.

Initialize a Kafka consumer for the specified topics.

PARAMETER DESCRIPTION *topics

Variable length argument list of topics to consume from.

TYPE: str DEFAULT: ()

group_id

Optional group ID for the consumer.

TYPE: Optional[str] DEFAULT: None

client_id

Client ID for the consumer.

TYPE: str DEFAULT: 'faststream-' + __version__

builder

Callable that constructs an AIOKafkaConsumer instance.

TYPE: Callable[..., AIOKafkaConsumer]

batch

Flag indicating whether to consume messages in batches.

TYPE: bool DEFAULT: False

batch_timeout_ms

Timeout in milliseconds for batch consumption.

TYPE: int DEFAULT: 200

max_records

Maximum number of records to consume in a batch.

TYPE: Optional[int] DEFAULT: None

title

Optional title for the consumer.

TYPE: Optional[str] DEFAULT: None

description

Optional description for the consumer.

TYPE: Optional[str] DEFAULT: None

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/kafka/handler.py
@override\ndef __init__(\n    self,\n    *topics: str,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # Kafka information\n    group_id: Optional[str] = None,\n    client_id: str = \"faststream-\" + __version__,\n    builder: Callable[..., AIOKafkaConsumer],\n    is_manual: bool = False,\n    batch: bool = False,\n    batch_timeout_ms: int = 200,\n    max_records: Optional[int] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    \"\"\"Initialize a Kafka consumer for the specified topics.\n\n    Args:\n        *topics: Variable length argument list of topics to consume from.\n        group_id: Optional group ID for the consumer.\n        client_id: Client ID for the consumer.\n        builder: Callable that constructs an AIOKafkaConsumer instance.\n        batch: Flag indicating whether to consume messages in batches.\n        batch_timeout_ms: Timeout in milliseconds for batch consumption.\n        max_records: Maximum number of records to consume in a batch.\n        title: Optional title for the consumer.\n        description: Optional description for the consumer.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.group_id = group_id\n    self.client_id = client_id\n    self.topics = topics\n\n    self.batch = batch\n    self.batch_timeout_ms = batch_timeout_ms\n    self.max_records = max_records\n    self.is_manual = is_manual\n\n    self.builder = builder\n    self.task = None\n    self.consumer = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = batch\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.batch_timeout_ms","title":"batch_timeout_ms instance-attribute","text":"
batch_timeout_ms = batch_timeout_ms\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.builder","title":"builder instance-attribute","text":"
builder = builder\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.client_id","title":"client_id instance-attribute","text":"
client_id = client_id\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.consumer","title":"consumer class-attribute instance-attribute","text":"
consumer: Optional[AIOKafkaConsumer] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.group_id","title":"group_id class-attribute instance-attribute","text":"
group_id: Optional[str] = group_id\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.is_manual","title":"is_manual instance-attribute","text":"
is_manual = is_manual\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.max_records","title":"max_records instance-attribute","text":"
max_records = max_records\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.task","title":"task class-attribute instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.topics","title":"topics instance-attribute","text":"
topics: Sequence[str] = topics\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        ConsumerRecord, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: CustomParser[\n        Union[ConsumerRecord, Tuple[ConsumerRecord, ...]],\n        KafkaMessage,\n    ],\n    decoder: Optional[CustomDecoder[KafkaMessage]],\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[ConsumerRecord, ...]]],\n    ],\n    middlewares: Optional[\n        Sequence[Callable[[ConsumerRecord], BaseMiddleware]]\n    ]\n) -> None\n

Adds a call to the handler.

PARAMETER DESCRIPTION handler

The handler function to be called.

TYPE: HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn]

dependant

The dependant model.

TYPE: CallModel[P_HandlerParams, T_HandlerReturn]

parser

Optional custom parser for parsing the input.

TYPE: CustomParser[Union[ConsumerRecord, Tuple[ConsumerRecord, ...]], KafkaMessage]

decoder

Optional custom decoder for decoding the input.

TYPE: Optional[CustomDecoder[KafkaMessage]]

filter

The filter for filtering the input.

TYPE: Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[ConsumerRecord, ...]]]]

middlewares

Optional sequence of middlewares to be applied.

TYPE: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]]

RETURNS DESCRIPTION None

None

Source code in faststream/kafka/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: CustomParser[\n        Union[ConsumerRecord, Tuple[ConsumerRecord, ...]], KafkaMessage\n    ],\n    decoder: Optional[CustomDecoder[KafkaMessage]],\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[ConsumerRecord, ...]]],\n    ],\n    middlewares: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]],\n) -> None:\n    \"\"\"Adds a call to the handler.\n\n    Args:\n        handler: The handler function to be called.\n        dependant: The dependant model.\n        parser: Optional custom parser for parsing the input.\n        decoder: Optional custom decoder for decoding the input.\n        filter: The filter for filtering the input.\n        middlewares: Optional sequence of middlewares to be applied.\n\n    Returns:\n        None\n\n    \"\"\"\n    parser_ = resolve_custom_func(  # type: ignore[type-var]\n        parser,  # type: ignore[arg-type]\n        (\n            AioKafkaParser.parse_message_batch  # type: ignore[arg-type]\n            if self.batch\n            else AioKafkaParser.parse_message\n        ),\n    )\n    decoder_ = resolve_custom_func(\n        decoder,  # type: ignore[arg-type]\n        (\n            AioKafkaParser.decode_message_batch  # type: ignore[arg-type]\n            if self.batch\n            else AioKafkaParser.decode_message\n        ),\n    )\n    super().add_call(\n        handler=handler,\n        parser=parser_,\n        decoder=decoder_,\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/kafka/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.consumer is not None:\n        await self.consumer.stop()\n        self.consumer = None\n\n    if self.task is not None:\n        self.task.cancel()\n        self.task = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(\n    topics: Sequence[str], group_id: Optional[str] = None\n) -> str\n
Source code in faststream/kafka/handler.py
@staticmethod\ndef get_routing_hash(topics: Sequence[str], group_id: Optional[str] = None) -> str:\n    return \"\".join((*topics, group_id or \"\"))\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/kafka/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    channels = {}\n\n    payloads = self.get_payloads()\n\n    for t in self.topics:\n        handler_name = self._title or f\"{t}:{self.call_name}\"\n        channels[handler_name] = Channel(\n            description=self.description,\n            subscribe=Operation(\n                message=Message(\n                    title=f\"{handler_name}:Message\",\n                    payload=resolve_payloads(payloads),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(kafka=kafka.ChannelBinding(topic=t)),\n        )\n\n    return channels\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.start","title":"start async","text":"
start(\n    **consumer_kwargs: Unpack[ConsumerConnectionParams],\n) -> None\n

Start the consumer.

PARAMETER DESCRIPTION **consumer_kwargs

Additional keyword arguments to pass to the consumer.

TYPE: Unpack[ConsumerConnectionParams] DEFAULT: {}

RETURNS DESCRIPTION None

None

Source code in faststream/kafka/handler.py
@override\nasync def start(  # type: ignore[override]\n    self,\n    **consumer_kwargs: Unpack[ConsumerConnectionParams],\n) -> None:\n    \"\"\"Start the consumer.\n\n    Args:\n        **consumer_kwargs: Additional keyword arguments to pass to the consumer.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.consumer = consumer = self.builder(\n        *self.topics,\n        group_id=self.group_id,\n        client_id=self.client_id,\n        **consumer_kwargs,\n    )\n    await consumer.start()\n    self.task = asyncio.create_task(self._consume())\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/","title":"Publisher","text":"","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher","title":"faststream.kafka.asyncapi.Publisher","text":"

Bases: LogicPublisher, AsyncAPIOperation

A class representing a publisher.

METHOD DESCRIPTION schema

returns the schema for the publisher

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported

","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = field(default=False)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.client_id","title":"client_id class-attribute instance-attribute","text":"
client_id: str = field(default='faststream-' + __version__)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.key","title":"key class-attribute instance-attribute","text":"
key: Optional[bytes] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.name","title":"name property","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.partition","title":"partition class-attribute instance-attribute","text":"
partition: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = ''\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.timestamp_ms","title":"timestamp_ms class-attribute instance-attribute","text":"
timestamp_ms: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.topic","title":"topic class-attribute instance-attribute","text":"
topic: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.publish","title":"publish async","text":"
publish(\n    *messages: SendableMessage,\n    message: SendableMessage = \"\",\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None\n) -> None\n

Publish messages to a topic.

PARAMETER DESCRIPTION *messages

Variable length argument list of SendableMessage objects.

TYPE: SendableMessage DEFAULT: ()

message

A SendableMessage object. Default is an empty string.

TYPE: SendableMessage DEFAULT: ''

key

Optional bytes object representing the message key.

TYPE: Optional[bytes] DEFAULT: None

partition

Optional integer representing the partition to publish the message to.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

Optional integer representing the timestamp of the message in milliseconds.

TYPE: Optional[int] DEFAULT: None

headers

Optional dictionary of header key-value pairs.

TYPE: Optional[Dict[str, str]] DEFAULT: None

correlation_id

Optional string representing the correlation ID of the message.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION AssertionError

If _producer is not set up.

AssertionError

If batch flag is not set and there are multiple messages.

ValueError

If message is not a sequence when messages is empty.

Source code in faststream/kafka/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *messages: SendableMessage,\n    message: SendableMessage = \"\",\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n) -> None:\n    \"\"\"Publish messages to a topic.\n\n    Args:\n        *messages: Variable length argument list of SendableMessage objects.\n        message: A SendableMessage object. Default is an empty string.\n        key: Optional bytes object representing the message key.\n        partition: Optional integer representing the partition to publish the message to.\n        timestamp_ms: Optional integer representing the timestamp of the message in milliseconds.\n        headers: Optional dictionary of header key-value pairs.\n        correlation_id: Optional string representing the correlation ID of the message.\n\n    Returns:\n        None\n\n    Raises:\n        AssertionError: If `_producer` is not set up.\n        AssertionError: If `batch` flag is not set and there are multiple messages.\n        ValueError: If `message` is not a sequence when `messages` is empty.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    assert (  # nosec B101\n        self.batch or len(messages) < 2\n    ), \"You can't send multiple messages without `batch` flag\"\n    assert self.topic, \"You have to specify outgoing topic\"  # nosec B101\n\n    if not self.batch:\n        return await self._producer.publish(\n            message=next(iter(messages), message),\n            topic=self.topic,\n            key=key or self.key,\n            partition=partition or self.partition,\n            timestamp_ms=timestamp_ms or self.timestamp_ms,\n            correlation_id=correlation_id,\n            headers=headers or self.headers,\n            reply_to=self.reply_to or \"\",\n        )\n    else:\n        to_send: Sequence[SendableMessage]\n        if not messages:\n            if not isinstance(message, Sequence):\n                raise ValueError(\n                    f\"Message: {message} should be Sequence type to send in batch\"\n                )\n            else:\n                to_send = message\n        else:\n            to_send = messages\n\n        await self._producer.publish_batch(\n            *to_send,\n            topic=self.topic,\n            partition=partition or self.partition,\n            timestamp_ms=timestamp_ms or self.timestamp_ms,\n            headers=headers or self.headers,\n        )\n        return None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/kafka/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    return {\n        self.name: Channel(\n            description=self.description,\n            publish=Operation(\n                message=Message(\n                    title=f\"{self.name}:Message\",\n                    payload=resolve_payloads(payloads, \"Publisher\"),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(kafka=kafka.ChannelBinding(topic=self.topic)),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/","title":"KafkaBroker","text":"","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker","title":"faststream.kafka.broker.KafkaBroker","text":"
KafkaBroker(\n    bootstrap_servers: Union[\n        str, Iterable[str]\n    ] = \"localhost\",\n    *,\n    protocol: str = None,\n    protocol_version: str = \"auto\",\n    client_id: str = \"faststream-\" + __version__,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: KafkaLoggingMixin, BrokerAsyncUsecase[ConsumerRecord, ConsumerConnectionParams]

KafkaBroker is a class for managing Kafka message consumption and publishing. It extends BrokerAsyncUsecase to handle asynchronous operations.

PARAMETER DESCRIPTION bootstrap_servers

Kafka bootstrap server(s).

TYPE: Union[str, Iterable[str]] DEFAULT: 'localhost'

protocol

The protocol used (default is \"kafka\").

TYPE: str DEFAULT: None

protocol_version

The Kafka protocol version (default is \"auto\").

TYPE: str DEFAULT: 'auto'

client_id

The client ID for the Kafka client.

TYPE: str DEFAULT: 'faststream-' + __version__

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

METHOD DESCRIPTION connect

Establishes a connection to Kafka.

start

Starts the KafkaBroker and message handlers.

publish

Publishes a message to Kafka.

Initialize a KafkaBroker instance.

PARAMETER DESCRIPTION bootstrap_servers

Kafka bootstrap server(s).

TYPE: Union[str, Iterable[str]] DEFAULT: 'localhost'

protocol

The protocol used (default is \"kafka\").

TYPE: str DEFAULT: None

protocol_version

The Kafka protocol version (default is \"auto\").

TYPE: str DEFAULT: 'auto'

client_id

The client ID for the Kafka client.

TYPE: str DEFAULT: 'faststream-' + __version__

security

Security protocol to use in communication with the broker (default is None).

TYPE: Optional[BaseSecurity] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/kafka/broker.py
def __init__(\n    self,\n    bootstrap_servers: Union[str, Iterable[str]] = \"localhost\",\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: str = \"auto\",\n    client_id: str = \"faststream-\" + __version__,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Initialize a KafkaBroker instance.\n\n    Args:\n        bootstrap_servers (Union[str, Iterable[str]]): Kafka bootstrap server(s).\n        protocol (str): The protocol used (default is \"kafka\").\n        protocol_version (str): The Kafka protocol version (default is \"auto\").\n        client_id (str): The client ID for the Kafka client.\n        security (Optional[BaseSecurity]): Security protocol to use in communication with the broker (default is None).\n        **kwargs: Additional keyword arguments.\n    \"\"\"\n    if protocol is None:\n        if security is not None and security.use_ssl:\n            protocol = \"kafka-secure\"\n        else:\n            protocol = \"kafka\"\n\n    super().__init__(\n        url=[bootstrap_servers]\n        if isinstance(bootstrap_servers, str)\n        else list(bootstrap_servers),\n        protocol=protocol,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n        client_id=client_id,\n        bootstrap_servers=bootstrap_servers,\n    )\n    self.client_id = client_id\n    self._producer = None\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.client_id","title":"client_id instance-attribute","text":"
client_id = client_id\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[str, Handler]\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.url","title":"url instance-attribute","text":"
url: List[str]\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.connect","title":"connect async","text":"
connect(\n    *args: Any, **kwargs: Any\n) -> ConsumerConnectionParams\n

Establishes a connection to Kafka and returns connection parameters.

PARAMETER DESCRIPTION *args

Additional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION ConsumerConnectionParams

The connection parameters.

TYPE: ConsumerConnectionParams

Source code in faststream/kafka/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> ConsumerConnectionParams:\n    \"\"\"\n    Establishes a connection to Kafka and returns connection parameters.\n\n    Args:\n        *args: Additional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        ConsumerConnectionParams: The connection parameters.\n    \"\"\"\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.publish","title":"publish async","text":"
publish(*args: Any, **kwargs: Any) -> None\n

Publish a message to Kafka.

PARAMETER DESCRIPTION *args

Positional arguments for message publishing.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments for message publishing.

TYPE: Any DEFAULT: {}

RAISES DESCRIPTION RuntimeError

If KafkaBroker is not started yet.

Source code in faststream/kafka/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Publish a message to Kafka.\n\n    Args:\n        *args: Positional arguments for message publishing.\n        **kwargs: Keyword arguments for message publishing.\n\n    Raises:\n        RuntimeError: If KafkaBroker is not started yet.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.publish_batch","title":"publish_batch async","text":"
publish_batch(*args: Any, **kwargs: Any) -> None\n

Publish a batch of messages to Kafka.

PARAMETER DESCRIPTION *args

Positional arguments for message publishing.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments for message publishing.

TYPE: Any DEFAULT: {}

RAISES DESCRIPTION RuntimeError

If KafkaBroker is not started yet.

Source code in faststream/kafka/broker.py
async def publish_batch(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Publish a batch of messages to Kafka.\n\n    Args:\n        *args: Positional arguments for message publishing.\n        **kwargs: Keyword arguments for message publishing.\n\n    Raises:\n        RuntimeError: If KafkaBroker is not started yet.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    await self._producer.publish_batch(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.publisher","title":"publisher","text":"
publisher(\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n

Create a message publisher for the specified topic.

PARAMETER DESCRIPTION topic

The topic to publish messages to.

TYPE: str

key

Message key.

TYPE: Optional[bytes] DEFAULT: None

partition

Partition to send the message to.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

Message timestamp in milliseconds.

TYPE: Optional[int] DEFAULT: None

headers

Message headers.

TYPE: Optional[Dict[str, str]] DEFAULT: None

reply_to

The topic to which responses should be sent.

TYPE: str DEFAULT: ''

batch

Whether to publish messages in batches.

TYPE: bool DEFAULT: False

title

AsyncAPI title.

TYPE: Optional[str] DEFAULT: None

description

AsyncAPI description.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION Publisher

A message publisher.

TYPE: Publisher

Source code in faststream/kafka/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"\n    Create a message publisher for the specified topic.\n\n    Args:\n        topic (str): The topic to publish messages to.\n        key (Optional[bytes]): Message key.\n        partition (Optional[int]): Partition to send the message to.\n        timestamp_ms (Optional[int]): Message timestamp in milliseconds.\n        headers (Optional[Dict[str, str]]): Message headers.\n        reply_to (str): The topic to which responses should be sent.\n        batch (bool): Whether to publish messages in batches.\n        title (Optional[str]): AsyncAPI title.\n        description (Optional[str]): AsyncAPI description.\n\n    Returns:\n        Publisher: A message publisher.\n    \"\"\"\n    publisher = self._publishers.get(\n        topic,\n        Publisher(\n            topic=topic,\n            client_id=self.client_id,\n            key=key,\n            batch=batch,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(topic, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.start","title":"start async","text":"
start() -> None\n

Start the KafkaBroker and message handlers.

Source code in faststream/kafka/broker.py
async def start(self) -> None:\n    \"\"\"\n    Start the KafkaBroker and message handlers.\n    \"\"\"\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n\n    for handler in self.handlers.values():\n        c = self._get_log_context(None, handler.topics, handler.group_id)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(**(self._connection or {}))\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.subscriber","title":"subscriber","text":"
subscriber(\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    value_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\", \"earliest\", \"none\"\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[\n        AbstractPartitionAssignor\n    ] = (RoundRobinPartitionAssignor),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\", \"read_committed\"\n    ] = \"read_uncommitted\",\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        Union[\n            CustomParser[\n                aiokafka.ConsumerRecord, KafkaMessage\n            ],\n            CustomParser[\n                Tuple[aiokafka.ConsumerRecord, ...],\n                KafkaMessage,\n            ],\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[\n            StreamMessage[\n                Tuple[aiokafka.ConsumerRecord, ...]\n            ]\n        ],\n    ] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    Union[\n        HandlerCallWrapper[\n            aiokafka.ConsumerRecord,\n            P_HandlerParams,\n            T_HandlerReturn,\n        ],\n        HandlerCallWrapper[\n            Tuple[aiokafka.ConsumerRecord, ...],\n            P_HandlerParams,\n            T_HandlerReturn,\n        ],\n    ],\n]\n

Create a message subscriber for the specified topics.

PARAMETER DESCRIPTION *topics

The topics to subscribe to.

TYPE: str DEFAULT: ()

group_id

The Kafka consumer group ID.

TYPE: Optional[str] DEFAULT: None

key_deserializer

Key deserializer function.

TYPE: Optional[Callable[[bytes], Any]] DEFAULT: None

value_deserializer

Value deserializer function.

TYPE: Optional[Callable[[bytes], Any]] DEFAULT: None

fetch_max_wait_ms

The maximum time to wait for data.

TYPE: int DEFAULT: 500

fetch_max_bytes

The maximum number of bytes to fetch.

TYPE: int DEFAULT: 52428800

fetch_min_bytes

The minimum number of bytes to fetch.

TYPE: int DEFAULT: 1

max_partition_fetch_bytes

The maximum bytes to fetch for a partition.

TYPE: int DEFAULT: 1 * 1024 * 1024

auto_offset_reset

Auto offset reset policy.

TYPE: Literal['latest', 'earliest', 'none'] DEFAULT: 'latest'

auto_commit

Whether to enable auto-commit.

TYPE: bool DEFAULT: True

auto_commit_interval_ms

Auto-commit interval in milliseconds.

TYPE: int DEFAULT: 5000

check_crcs

Whether to check CRCs.

TYPE: bool DEFAULT: True

partition_assignment_strategy

Partition assignment strategy.

TYPE: Sequence[AbstractPartitionAssignor] DEFAULT: (RoundRobinPartitionAssignor)

max_poll_interval_ms

Maximum poll interval in milliseconds.

TYPE: int DEFAULT: 300000

rebalance_timeout_ms

Rebalance timeout in milliseconds.

TYPE: Optional[int] DEFAULT: None

session_timeout_ms

Session timeout in milliseconds.

TYPE: int DEFAULT: 10000

heartbeat_interval_ms

Heartbeat interval in milliseconds.

TYPE: int DEFAULT: 3000

consumer_timeout_ms

Consumer timeout in milliseconds.

TYPE: int DEFAULT: 200

max_poll_records

Maximum number of records to poll.

TYPE: Optional[int] DEFAULT: None

exclude_internal_topics

Whether to exclude internal topics.

TYPE: bool DEFAULT: True

isolation_level

Isolation level.

TYPE: Literal['read_uncommitted', 'read_committed'] DEFAULT: 'read_uncommitted'

dependencies

Additional dependencies for message handling.

TYPE: Sequence[Depends] DEFAULT: ()

parser

Message parser.

TYPE: Optional[Union[CustomParser[ConsumerRecord], CustomParser[Tuple[ConsumerRecord, ...]]]] DEFAULT: None

decoder

Message decoder.

TYPE: Optional[CustomDecoder] DEFAULT: None

middlewares

Message middlewares.

TYPE: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]] DEFAULT: None

filter

Message filter.

TYPE: Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[ConsumerRecord, ...]]]] DEFAULT: default_filter

batch

Whether to process messages in batches.

TYPE: bool DEFAULT: False

max_records

Maximum number of records to process in each batch.

TYPE: Optional[int] DEFAULT: None

batch_timeout_ms

Batch timeout in milliseconds.

TYPE: int DEFAULT: 200

no_ack

Whether not to ack/nack/reject messages.

TYPE: bool DEFAULT: False

title

AsyncAPI title.

TYPE: Optional[str] DEFAULT: None

description

AsyncAPI description.

TYPE: Optional[str] DEFAULT: None

**original_kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Callable

A decorator that wraps a message handler function.

TYPE: Callable[[Callable[P_HandlerParams, T_HandlerReturn]], Union[HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[Tuple[ConsumerRecord, ...], P_HandlerParams, T_HandlerReturn]]]

Source code in faststream/kafka/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[Callable[[bytes], Any]] = None,\n    value_deserializer: Optional[Callable[[bytes], Any]] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\",\n        \"earliest\",\n        \"none\",\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[AbstractPartitionAssignor] = (\n        RoundRobinPartitionAssignor,\n    ),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\",\n        \"read_committed\",\n    ] = \"read_uncommitted\",\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        Union[\n            CustomParser[aiokafka.ConsumerRecord, KafkaMessage],\n            CustomParser[Tuple[aiokafka.ConsumerRecord, ...], KafkaMessage],\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord],\n                BaseMiddleware,\n            ]\n        ]\n    ] = None,\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[aiokafka.ConsumerRecord, ...]]],\n    ] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    Union[\n        HandlerCallWrapper[\n            aiokafka.ConsumerRecord, P_HandlerParams, T_HandlerReturn\n        ],\n        HandlerCallWrapper[\n            Tuple[aiokafka.ConsumerRecord, ...], P_HandlerParams, T_HandlerReturn\n        ],\n    ],\n]:\n    \"\"\"\n    Create a message subscriber for the specified topics.\n\n    Args:\n        *topics (str): The topics to subscribe to.\n        group_id (Optional[str]): The Kafka consumer group ID.\n        key_deserializer (Optional[Callable[[bytes], Any]]): Key deserializer function.\n        value_deserializer (Optional[Callable[[bytes], Any]]): Value deserializer function.\n        fetch_max_wait_ms (int): The maximum time to wait for data.\n        fetch_max_bytes (int): The maximum number of bytes to fetch.\n        fetch_min_bytes (int): The minimum number of bytes to fetch.\n        max_partition_fetch_bytes (int): The maximum bytes to fetch for a partition.\n        auto_offset_reset (Literal[\"latest\", \"earliest\", \"none\"]): Auto offset reset policy.\n        auto_commit (bool): Whether to enable auto-commit.\n        auto_commit_interval_ms (int): Auto-commit interval in milliseconds.\n        check_crcs (bool): Whether to check CRCs.\n        partition_assignment_strategy (Sequence[AbstractPartitionAssignor]): Partition assignment strategy.\n        max_poll_interval_ms (int): Maximum poll interval in milliseconds.\n        rebalance_timeout_ms (Optional[int]): Rebalance timeout in milliseconds.\n        session_timeout_ms (int): Session timeout in milliseconds.\n        heartbeat_interval_ms (int): Heartbeat interval in milliseconds.\n        consumer_timeout_ms (int): Consumer timeout in milliseconds.\n        max_poll_records (Optional[int]): Maximum number of records to poll.\n        exclude_internal_topics (bool): Whether to exclude internal topics.\n        isolation_level (Literal[\"read_uncommitted\", \"read_committed\"]): Isolation level.\n        dependencies (Sequence[Depends]): Additional dependencies for message handling.\n        parser (Optional[Union[CustomParser[aiokafka.ConsumerRecord], CustomParser[Tuple[aiokafka.ConsumerRecord, ...]]]]): Message parser.\n        decoder (Optional[CustomDecoder]): Message decoder.\n        middlewares (Optional[Sequence[Callable[[aiokafka.ConsumerRecord], BaseMiddleware]]]): Message middlewares.\n        filter (Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[aiokafka.ConsumerRecord, ...]]]]): Message filter.\n        batch (bool): Whether to process messages in batches.\n        max_records (Optional[int]): Maximum number of records to process in each batch.\n        batch_timeout_ms (int): Batch timeout in milliseconds.\n        no_ack (bool): Whether not to ack/nack/reject messages.\n        title (Optional[str]): AsyncAPI title.\n        description (Optional[str]): AsyncAPI description.\n        **original_kwargs: Additional keyword arguments.\n\n    Returns:\n        Callable: A decorator that wraps a message handler function.\n    \"\"\"\n    super().subscriber()\n\n    self._setup_log_context(topics, group_id)\n\n    if not auto_commit and not group_id:\n        raise ValueError(\"You should install `group_id` with manual commit mode\")\n\n    key = Handler.get_routing_hash(topics, group_id)\n    builder = partial(\n        aiokafka.AIOKafkaConsumer,\n        key_deserializer=key_deserializer,\n        value_deserializer=value_deserializer,\n        fetch_max_wait_ms=fetch_max_wait_ms,\n        fetch_max_bytes=fetch_max_bytes,\n        fetch_min_bytes=fetch_min_bytes,\n        max_partition_fetch_bytes=max_partition_fetch_bytes,\n        auto_offset_reset=auto_offset_reset,\n        enable_auto_commit=auto_commit,\n        auto_commit_interval_ms=auto_commit_interval_ms,\n        check_crcs=check_crcs,\n        partition_assignment_strategy=partition_assignment_strategy,\n        max_poll_interval_ms=max_poll_interval_ms,\n        rebalance_timeout_ms=rebalance_timeout_ms,\n        session_timeout_ms=session_timeout_ms,\n        heartbeat_interval_ms=heartbeat_interval_ms,\n        consumer_timeout_ms=consumer_timeout_ms,\n        max_poll_records=max_poll_records,\n        exclude_internal_topics=exclude_internal_topics,\n        isolation_level=isolation_level,\n    )\n    handler = self.handlers.get(\n        key,\n        Handler(\n            *topics,\n            log_context_builder=partial(\n                self._get_log_context,\n                topics=topics,\n                group_id=group_id,\n            ),\n            is_manual=not auto_commit,\n            group_id=group_id,\n            client_id=self.client_id,\n            builder=builder,\n            description=description,\n            title=title,\n            batch=batch,\n            batch_timeout_ms=batch_timeout_ms,\n            max_records=max_records,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n        ),\n    )\n\n    self.handlers[key] = handler\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[\n        aiokafka.ConsumerRecord, P_HandlerParams, T_HandlerReturn\n    ]:\n        \"\"\"A wrapper function for a consumer handler.\n\n        Args:\n            func : The consumer handler function to be wrapped.\n\n        Returns:\n            The wrapped handler call.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        handler_call, dependant = self._wrap_handler(\n            func=func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/kafka/fastapi/Context/#faststream.broker.fastapi.context.Context","title":"faststream.broker.fastapi.context.Context","text":"
Context(name: str) -> Any\n
Source code in faststream/broker/fastapi/context.py
def Context(name: str) -> Any:\n    return params.Depends(\n        lambda: context.resolve(name),\n        use_cache=True,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/","title":"KafkaRouter","text":"","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter","title":"faststream.kafka.fastapi.KafkaRouter","text":"
KafkaRouter(\n    bootstrap_servers: Union[\n        str, Iterable[str]\n    ] = \"localhost\",\n    *,\n    client_id: str = \"faststream-\" + __version__,\n    request_timeout_ms: int = 40 * 1000,\n    retry_backoff_ms: int = 100,\n    metadata_max_age_ms: int = 5 * 60 * 1000,\n    api_version: str = \"auto\",\n    connections_max_idle_ms: int = 540000,\n    security: Optional[BaseSecurity] = None,\n    acks: Union[\n        Literal[0, 1, -1, \"all\"], object\n    ] = _missing,\n    key_serializer: Optional[Callable[[Any], bytes]] = None,\n    value_serializer: Optional[\n        Callable[[Any], bytes]\n    ] = None,\n    compression_type: Optional[\n        Literal[\"gzip\", \"snappy\", \"lz4\", \"zstd\"]\n    ] = None,\n    max_batch_size: int = 16384,\n    partitioner: Callable[\n        [bytes, List[Partition], List[Partition]], Partition\n    ] = DefaultPartitioner(),\n    max_request_size: int = 1048576,\n    linger_ms: int = 0,\n    send_backoff_ms: int = 100,\n    enable_idempotence: bool = False,\n    transactional_id: Optional[str] = None,\n    transaction_timeout_ms: int = 60000,\n    loop: Optional[AbstractEventLoop] = None,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id),\n    graceful_timeout: Optional[float] = None,\n    apply_types: bool = True,\n    validate: bool = True,\n    decoder: Optional[CustomDecoder[KafkaMessage]] = None,\n    parser: Optional[\n        CustomParser[aiokafka.ConsumerRecord, KafkaMessage]\n    ] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    asyncapi_url: Union[str, List[str], None] = None,\n    protocol: str = \"kafka\",\n    protocol_version: str = \"auto\",\n    description: Optional[str] = None,\n    asyncapi_tags: Optional[Sequence[asyncapi.Tag]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    setup_state: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any\n)\n

Bases: StreamRouter[ConsumerRecord]

A class to route Kafka streams.

METHOD DESCRIPTION _setup_log_context

sets up the log context for the main broker and including broker

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.broker","title":"broker instance-attribute","text":"
broker: KafkaBroker\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.broker_class","title":"broker_class class-attribute instance-attribute","text":"
broker_class: Type[KafkaBroker] = KB\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any\n) -> HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n]\n

Add an API message queue route.

PARAMETER DESCRIPTION path

The path of the route.

TYPE: Union[NameRequired, str]

*extra

Additional path segments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint function to be called for this route.

TYPE: Callable[P_HandlerParams, T_HandlerReturn]

dependencies

The dependencies required by the endpoint function.

TYPE: Sequence[Depends]

**broker_kwargs

Additional keyword arguments to be passed to the broker.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]

The handler call wrapper for the route.

Source code in faststream/broker/fastapi/router.py
def add_api_mq_route(\n    self,\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any,\n) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n    \"\"\"Add an API message queue route.\n\n    Args:\n        path: The path of the route.\n        *extra: Additional path segments.\n        endpoint: The endpoint function to be called for this route.\n        dependencies: The dependencies required by the endpoint function.\n        **broker_kwargs: Additional keyword arguments to be passed to the broker.\n\n    Returns:\n        The handler call wrapper for the route.\n\n    \"\"\"\n    route: StreamRoute[MsgType, P_HandlerParams, T_HandlerReturn] = StreamRoute(\n        path,\n        *extra,\n        endpoint=endpoint,\n        dependencies=dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        broker=self.broker,\n        **broker_kwargs,\n    )\n    self.routes.append(route)\n    return route.handler\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.publisher","title":"publisher","text":"
publisher(\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.subscriber","title":"subscriber","text":"
subscriber(\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function decorator for subscribing to a message queue.

PARAMETER DESCRIPTION path

The path to subscribe to. Can be a string or a NameRequired object.

*extra

Additional path segments. Can be a NameRequired object or a string.

DEFAULT: ()

dependencies

Optional sequence of dependencies.

DEFAULT: None

**broker_kwargs

Additional keyword arguments for the broker.

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable decorator that adds the decorated function as an endpoint for the specified path.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def subscriber(\n    self,\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function decorator for subscribing to a message queue.\n\n    Args:\n        path : The path to subscribe to. Can be a string or a `NameRequired` object.\n        *extra : Additional path segments. Can be a `NameRequired` object or a string.\n        dependencies : Optional sequence of dependencies.\n        **broker_kwargs : Additional keyword arguments for the broker.\n\n    Returns:\n        A callable decorator that adds the decorated function as an endpoint for the specified path.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    def decorator(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n        \"\"\"A decorator function.\n\n        Args:\n            func: The function to be decorated.\n\n        Returns:\n            The decorated function.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        return self.add_api_mq_route(\n            path,\n            *extra,\n            endpoint=func,\n            dependencies=current_dependencies,\n            **broker_kwargs,\n        )\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/","title":"LogicHandler","text":"","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler","title":"faststream.kafka.handler.LogicHandler","text":"
LogicHandler(\n    *topics: str,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    group_id: Optional[str] = None,\n    client_id: str = \"faststream-\" + __version__,\n    builder: Callable[..., AIOKafkaConsumer],\n    is_manual: bool = False,\n    batch: bool = False,\n    batch_timeout_ms: int = 200,\n    max_records: Optional[int] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True\n)\n

Bases: AsyncHandler[ConsumerRecord]

A class to handle logic for consuming messages from Kafka.

METHOD DESCRIPTION __init__

constructor method for the LogicHandler class

start

method to start consuming messages from Kafka

close

method to close the Kafka consumer and cancel the consuming task

add_call

method to add a handler call for processing consumed messages

_consume

method to consume messages from Kafka and call the appropriate handler

Initialize a Kafka consumer for the specified topics.

PARAMETER DESCRIPTION *topics

Variable length argument list of topics to consume from.

TYPE: str DEFAULT: ()

group_id

Optional group ID for the consumer.

TYPE: Optional[str] DEFAULT: None

client_id

Client ID for the consumer.

TYPE: str DEFAULT: 'faststream-' + __version__

builder

Callable that constructs an AIOKafkaConsumer instance.

TYPE: Callable[..., AIOKafkaConsumer]

batch

Flag indicating whether to consume messages in batches.

TYPE: bool DEFAULT: False

batch_timeout_ms

Timeout in milliseconds for batch consumption.

TYPE: int DEFAULT: 200

max_records

Maximum number of records to consume in a batch.

TYPE: Optional[int] DEFAULT: None

title

Optional title for the consumer.

TYPE: Optional[str] DEFAULT: None

description

Optional description for the consumer.

TYPE: Optional[str] DEFAULT: None

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/kafka/handler.py
@override\ndef __init__(\n    self,\n    *topics: str,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # Kafka information\n    group_id: Optional[str] = None,\n    client_id: str = \"faststream-\" + __version__,\n    builder: Callable[..., AIOKafkaConsumer],\n    is_manual: bool = False,\n    batch: bool = False,\n    batch_timeout_ms: int = 200,\n    max_records: Optional[int] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    \"\"\"Initialize a Kafka consumer for the specified topics.\n\n    Args:\n        *topics: Variable length argument list of topics to consume from.\n        group_id: Optional group ID for the consumer.\n        client_id: Client ID for the consumer.\n        builder: Callable that constructs an AIOKafkaConsumer instance.\n        batch: Flag indicating whether to consume messages in batches.\n        batch_timeout_ms: Timeout in milliseconds for batch consumption.\n        max_records: Maximum number of records to consume in a batch.\n        title: Optional title for the consumer.\n        description: Optional description for the consumer.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.group_id = group_id\n    self.client_id = client_id\n    self.topics = topics\n\n    self.batch = batch\n    self.batch_timeout_ms = batch_timeout_ms\n    self.max_records = max_records\n    self.is_manual = is_manual\n\n    self.builder = builder\n    self.task = None\n    self.consumer = None\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = batch\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.batch_timeout_ms","title":"batch_timeout_ms instance-attribute","text":"
batch_timeout_ms = batch_timeout_ms\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.builder","title":"builder instance-attribute","text":"
builder = builder\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.client_id","title":"client_id instance-attribute","text":"
client_id = client_id\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.consumer","title":"consumer class-attribute instance-attribute","text":"
consumer: Optional[AIOKafkaConsumer] = None\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.group_id","title":"group_id class-attribute instance-attribute","text":"
group_id: Optional[str] = group_id\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.is_manual","title":"is_manual instance-attribute","text":"
is_manual = is_manual\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.max_records","title":"max_records instance-attribute","text":"
max_records = max_records\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.task","title":"task class-attribute instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.topics","title":"topics instance-attribute","text":"
topics: Sequence[str] = topics\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        ConsumerRecord, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: CustomParser[\n        Union[ConsumerRecord, Tuple[ConsumerRecord, ...]],\n        KafkaMessage,\n    ],\n    decoder: Optional[CustomDecoder[KafkaMessage]],\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[ConsumerRecord, ...]]],\n    ],\n    middlewares: Optional[\n        Sequence[Callable[[ConsumerRecord], BaseMiddleware]]\n    ]\n) -> None\n

Adds a call to the handler.

PARAMETER DESCRIPTION handler

The handler function to be called.

TYPE: HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn]

dependant

The dependant model.

TYPE: CallModel[P_HandlerParams, T_HandlerReturn]

parser

Optional custom parser for parsing the input.

TYPE: CustomParser[Union[ConsumerRecord, Tuple[ConsumerRecord, ...]], KafkaMessage]

decoder

Optional custom decoder for decoding the input.

TYPE: Optional[CustomDecoder[KafkaMessage]]

filter

The filter for filtering the input.

TYPE: Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[ConsumerRecord, ...]]]]

middlewares

Optional sequence of middlewares to be applied.

TYPE: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]]

RETURNS DESCRIPTION None

None

Source code in faststream/kafka/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: CustomParser[\n        Union[ConsumerRecord, Tuple[ConsumerRecord, ...]], KafkaMessage\n    ],\n    decoder: Optional[CustomDecoder[KafkaMessage]],\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[ConsumerRecord, ...]]],\n    ],\n    middlewares: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]],\n) -> None:\n    \"\"\"Adds a call to the handler.\n\n    Args:\n        handler: The handler function to be called.\n        dependant: The dependant model.\n        parser: Optional custom parser for parsing the input.\n        decoder: Optional custom decoder for decoding the input.\n        filter: The filter for filtering the input.\n        middlewares: Optional sequence of middlewares to be applied.\n\n    Returns:\n        None\n\n    \"\"\"\n    parser_ = resolve_custom_func(  # type: ignore[type-var]\n        parser,  # type: ignore[arg-type]\n        (\n            AioKafkaParser.parse_message_batch  # type: ignore[arg-type]\n            if self.batch\n            else AioKafkaParser.parse_message\n        ),\n    )\n    decoder_ = resolve_custom_func(\n        decoder,  # type: ignore[arg-type]\n        (\n            AioKafkaParser.decode_message_batch  # type: ignore[arg-type]\n            if self.batch\n            else AioKafkaParser.decode_message\n        ),\n    )\n    super().add_call(\n        handler=handler,\n        parser=parser_,\n        decoder=decoder_,\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/kafka/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.consumer is not None:\n        await self.consumer.stop()\n        self.consumer = None\n\n    if self.task is not None:\n        self.task.cancel()\n        self.task = None\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(\n    topics: Sequence[str], group_id: Optional[str] = None\n) -> str\n
Source code in faststream/kafka/handler.py
@staticmethod\ndef get_routing_hash(topics: Sequence[str], group_id: Optional[str] = None) -> str:\n    return \"\".join((*topics, group_id or \"\"))\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.start","title":"start async","text":"
start(\n    **consumer_kwargs: Unpack[ConsumerConnectionParams],\n) -> None\n

Start the consumer.

PARAMETER DESCRIPTION **consumer_kwargs

Additional keyword arguments to pass to the consumer.

TYPE: Unpack[ConsumerConnectionParams] DEFAULT: {}

RETURNS DESCRIPTION None

None

Source code in faststream/kafka/handler.py
@override\nasync def start(  # type: ignore[override]\n    self,\n    **consumer_kwargs: Unpack[ConsumerConnectionParams],\n) -> None:\n    \"\"\"Start the consumer.\n\n    Args:\n        **consumer_kwargs: Additional keyword arguments to pass to the consumer.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.consumer = consumer = self.builder(\n        *self.topics,\n        group_id=self.group_id,\n        client_id=self.client_id,\n        **consumer_kwargs,\n    )\n    await consumer.start()\n    self.task = asyncio.create_task(self._consume())\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/","title":"KafkaMessage","text":"","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage","title":"faststream.kafka.message.KafkaMessage","text":"
KafkaMessage(\n    *args: Any,\n    consumer: aiokafka.AIOKafkaConsumer,\n    is_manual: bool = False,\n    **kwargs: Any\n)\n

Bases: StreamMessage[ConsumerRecord]

Represents a Kafka message in the FastStream framework.

This class extends StreamMessage and is specialized for handling Kafka ConsumerRecord objects.

METHOD DESCRIPTION ack

Acknowledge the Kafka message.

nack

Negative acknowledgment of the Kafka message.

reject

Reject the Kafka message.

Source code in faststream/kafka/message.py
def __init__(\n    self,\n    *args: Any,\n    consumer: aiokafka.AIOKafkaConsumer,\n    is_manual: bool = False,\n    **kwargs: Any,\n) -> None:\n    super().__init__(*args, **kwargs)\n\n    self.is_manual = is_manual\n    self.consumer = consumer\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.consumer","title":"consumer instance-attribute","text":"
consumer = consumer\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.is_manual","title":"is_manual instance-attribute","text":"
is_manual = is_manual\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.ack","title":"ack async","text":"
ack(**kwargs: Any) -> None\n

Acknowledge the Kafka message.

PARAMETER DESCRIPTION **kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

This method does not return a value.

TYPE: None

Source code in faststream/kafka/message.py
async def ack(self, **kwargs: Any) -> None:\n    \"\"\"\n    Acknowledge the Kafka message.\n\n    Args:\n        **kwargs (Any): Additional keyword arguments.\n\n    Returns:\n        None: This method does not return a value.\n    \"\"\"\n    if self.is_manual and not self.commited:\n        await self.consumer.commit()\n        await super().ack()\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.nack","title":"nack async","text":"
nack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def nack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.reject","title":"reject async","text":"
reject(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def reject(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/","title":"AioKafkaParser","text":"","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/#faststream.kafka.parser.AioKafkaParser","title":"faststream.kafka.parser.AioKafkaParser","text":"","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/#faststream.kafka.parser.AioKafkaParser.decode_message","title":"decode_message async staticmethod","text":"
decode_message(\n    msg: StreamMessage[ConsumerRecord],\n) -> DecodedMessage\n

Decodes a message.

PARAMETER DESCRIPTION msg

The message to be decoded.

TYPE: StreamMessage[ConsumerRecord]

RETURNS DESCRIPTION DecodedMessage

The decoded message.

Source code in faststream/kafka/parser.py
@staticmethod\nasync def decode_message(msg: StreamMessage[ConsumerRecord]) -> DecodedMessage:\n    \"\"\"Decodes a message.\n\n    Args:\n        msg: The message to be decoded.\n\n    Returns:\n        The decoded message.\n\n    \"\"\"\n    return decode_message(msg)\n
","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/#faststream.kafka.parser.AioKafkaParser.decode_message_batch","title":"decode_message_batch async classmethod","text":"
decode_message_batch(\n    msg: StreamMessage[Tuple[ConsumerRecord, ...]]\n) -> List[DecodedMessage]\n

Decode a batch of messages.

PARAMETER DESCRIPTION msg

A stream message containing a tuple of consumer records.

TYPE: StreamMessage[Tuple[ConsumerRecord, ...]]

RETURNS DESCRIPTION List[DecodedMessage]

A list of decoded messages.

Source code in faststream/kafka/parser.py
@classmethod\nasync def decode_message_batch(\n    cls, msg: StreamMessage[Tuple[ConsumerRecord, ...]]\n) -> List[DecodedMessage]:\n    \"\"\"Decode a batch of messages.\n\n    Args:\n        msg: A stream message containing a tuple of consumer records.\n\n    Returns:\n        A list of decoded messages.\n\n    \"\"\"\n    return [decode_message(await cls.parse_message(m)) for m in msg.raw_message]\n
","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/#faststream.kafka.parser.AioKafkaParser.parse_message","title":"parse_message async staticmethod","text":"
parse_message(\n    message: ConsumerRecord,\n) -> StreamMessage[ConsumerRecord]\n

Parses a Kafka message.

PARAMETER DESCRIPTION message

The Kafka message to parse.

TYPE: ConsumerRecord

RETURNS DESCRIPTION StreamMessage[ConsumerRecord]

A StreamMessage object representing the parsed message.

Source code in faststream/kafka/parser.py
@staticmethod\nasync def parse_message(\n    message: ConsumerRecord,\n) -> StreamMessage[ConsumerRecord]:\n    \"\"\"Parses a Kafka message.\n\n    Args:\n        message: The Kafka message to parse.\n\n    Returns:\n        A StreamMessage object representing the parsed message.\n\n    \"\"\"\n    headers = {i: j.decode() for i, j in message.headers}\n    handler = context.get_local(\"handler_\")\n    return KafkaMessage(\n        body=message.value,\n        headers=headers,\n        reply_to=headers.get(\"reply_to\", \"\"),\n        content_type=headers.get(\"content-type\"),\n        message_id=f\"{message.offset}-{message.timestamp}\",\n        correlation_id=headers.get(\"correlation_id\", str(uuid4())),\n        raw_message=message,\n        consumer=handler.consumer,\n        is_manual=handler.is_manual,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/#faststream.kafka.parser.AioKafkaParser.parse_message_batch","title":"parse_message_batch async staticmethod","text":"
parse_message_batch(\n    message: Tuple[ConsumerRecord, ...]\n) -> KafkaMessage\n

Parses a batch of messages from a Kafka consumer.

PARAMETER DESCRIPTION message

A tuple of ConsumerRecord objects representing the messages to parse.

RETURNS DESCRIPTION KafkaMessage

A StreamMessage object containing the parsed messages.

RAISES DESCRIPTION NotImplementedError

If any of the messages are silent (i.e., have no sound).

Static Method

This method is a static method. It does not require an instance of the class to be called.

Source code in faststream/kafka/parser.py
@staticmethod\nasync def parse_message_batch(\n    message: Tuple[ConsumerRecord, ...],\n) -> KafkaMessage:\n    \"\"\"Parses a batch of messages from a Kafka consumer.\n\n    Args:\n        message : A tuple of ConsumerRecord objects representing the messages to parse.\n\n    Returns:\n        A StreamMessage object containing the parsed messages.\n\n    Raises:\n        NotImplementedError: If any of the messages are silent (i.e., have no sound).\n\n    Static Method:\n        This method is a static method. It does not require an instance of the class to be called.\n\n    \"\"\"\n    first = message[0]\n    last = message[-1]\n    headers = {i: j.decode() for i, j in first.headers}\n    handler = context.get_local(\"handler_\")\n    return KafkaMessage(\n        body=[m.value for m in message],\n        headers=headers,\n        reply_to=headers.get(\"reply_to\", \"\"),\n        content_type=headers.get(\"content-type\"),\n        message_id=f\"{first.offset}-{last.offset}-{first.timestamp}\",\n        correlation_id=headers.get(\"correlation_id\", str(uuid4())),\n        raw_message=message,\n        consumer=handler.consumer,\n        is_manual=handler.is_manual,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/producer/AioKafkaFastProducer/","title":"AioKafkaFastProducer","text":"","boost":0.5},{"location":"api/faststream/kafka/producer/AioKafkaFastProducer/#faststream.kafka.producer.AioKafkaFastProducer","title":"faststream.kafka.producer.AioKafkaFastProducer","text":"
AioKafkaFastProducer(producer: AIOKafkaProducer)\n

A class to represent a fast Kafka producer.

METHOD DESCRIPTION publish

Publishes a message to a Kafka topic.

stop

Stops the Kafka producer.

publish_batch

Publishes a batch of messages to a Kafka topic.

Initialize the class.

PARAMETER DESCRIPTION producer

An instance of AIOKafkaProducer.

TYPE: AIOKafkaProducer

Source code in faststream/kafka/producer.py
def __init__(\n    self,\n    producer: AIOKafkaProducer,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        producer: An instance of AIOKafkaProducer.\n\n    \"\"\"\n    self._producer = producer\n
","boost":0.5},{"location":"api/faststream/kafka/producer/AioKafkaFastProducer/#faststream.kafka.producer.AioKafkaFastProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\"\n) -> None\n

Publish a message to a topic.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

topic

The topic to publish the message to.

TYPE: str

key

The key associated with the message.

TYPE: Optional[bytes] DEFAULT: None

partition

The partition to which the message should be sent.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

The timestamp of the message in milliseconds.

TYPE: Optional[int] DEFAULT: None

headers

Additional headers to be included with the message.

TYPE: Optional[Dict[str, str]] DEFAULT: None

correlation_id

The correlation ID of the message.

TYPE: Optional[str] DEFAULT: None

reply_to

The topic to which the reply should be sent.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION AssertionError

If the broker is not connected.

Source code in faststream/kafka/producer.py
async def publish(\n    self,\n    message: SendableMessage,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\",\n) -> None:\n    \"\"\"Publish a message to a topic.\n\n    Args:\n        message: The message to be published.\n        topic: The topic to publish the message to.\n        key: The key associated with the message.\n        partition: The partition to which the message should be sent.\n        timestamp_ms: The timestamp of the message in milliseconds.\n        headers: Additional headers to be included with the message.\n        correlation_id: The correlation ID of the message.\n        reply_to: The topic to which the reply should be sent.\n\n    Returns:\n        None\n\n    Raises:\n        AssertionError: If the broker is not connected.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n\n    message, content_type = encode_message(message)\n\n    headers_to_send = {\n        \"content-type\": content_type or \"\",\n        \"correlation_id\": correlation_id or str(uuid4()),\n        **(headers or {}),\n    }\n\n    if reply_to:\n        headers_to_send.update({\"reply_to\": reply_to})\n\n    await self._producer.send(\n        topic=topic,\n        value=message,\n        key=key,\n        partition=partition,\n        timestamp_ms=timestamp_ms,\n        headers=[(i, (j or \"\").encode()) for i, j in headers_to_send.items()],\n    )\n\n    return None\n
","boost":0.5},{"location":"api/faststream/kafka/producer/AioKafkaFastProducer/#faststream.kafka.producer.AioKafkaFastProducer.publish_batch","title":"publish_batch async","text":"
publish_batch(\n    *msgs: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None\n) -> None\n

Publish a batch of messages to a topic.

PARAMETER DESCRIPTION *msgs

Variable length argument list of messages to be sent.

TYPE: SendableMessage DEFAULT: ()

topic

The topic to which the messages should be published.

TYPE: str

partition

The partition to which the messages should be sent. Defaults to None.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

The timestamp to be associated with the messages. Defaults to None.

TYPE: Optional[int] DEFAULT: None

headers

Additional headers to be included with the messages. Defaults to None.

TYPE: Optional[Dict[str, str]] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION AssertionError

If the broker is not connected.

Source code in faststream/kafka/producer.py
async def publish_batch(\n    self,\n    *msgs: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n) -> None:\n    \"\"\"Publish a batch of messages to a topic.\n\n    Args:\n        *msgs: Variable length argument list of messages to be sent.\n        topic: The topic to which the messages should be published.\n        partition: The partition to which the messages should be sent. Defaults to None.\n        timestamp_ms: The timestamp to be associated with the messages. Defaults to None.\n        headers: Additional headers to be included with the messages. Defaults to None.\n\n    Returns:\n        None\n\n    Raises:\n        AssertionError: If the broker is not connected.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n\n    batch = self._producer.create_batch()\n\n    for msg in msgs:\n        message, content_type = encode_message(msg)\n\n        headers_to_send = {\n            \"content-type\": content_type or \"\",\n            **(headers or {}),\n        }\n\n        batch.append(\n            key=None,\n            value=message,\n            timestamp=timestamp_ms,\n            headers=[(i, j.encode()) for i, j in headers_to_send.items()],\n        )\n\n    await self._producer.send_batch(batch, topic, partition=partition)\n
","boost":0.5},{"location":"api/faststream/kafka/producer/AioKafkaFastProducer/#faststream.kafka.producer.AioKafkaFastProducer.stop","title":"stop async","text":"
stop() -> None\n
Source code in faststream/kafka/producer.py
async def stop(self) -> None:\n    if self._producer is not None:  # pragma: no branch\n        await self._producer.stop()\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/","title":"LogicPublisher","text":"","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher","title":"faststream.kafka.publisher.LogicPublisher dataclass","text":"

Bases: ABCPublisher[ConsumerRecord]

A class to publish messages to a Kafka topic.

METHOD DESCRIPTION publish

Publishes messages to the Kafka topic

RAISES DESCRIPTION AssertionError

If _producer is not set up or if multiple messages are sent without the batch flag

","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = field(default=False)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.client_id","title":"client_id class-attribute instance-attribute","text":"
client_id: str = field(default='faststream-' + __version__)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.key","title":"key class-attribute instance-attribute","text":"
key: Optional[bytes] = None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.partition","title":"partition class-attribute instance-attribute","text":"
partition: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = ''\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.timestamp_ms","title":"timestamp_ms class-attribute instance-attribute","text":"
timestamp_ms: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.topic","title":"topic class-attribute instance-attribute","text":"
topic: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.publish","title":"publish async","text":"
publish(\n    *messages: SendableMessage,\n    message: SendableMessage = \"\",\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None\n) -> None\n

Publish messages to a topic.

PARAMETER DESCRIPTION *messages

Variable length argument list of SendableMessage objects.

TYPE: SendableMessage DEFAULT: ()

message

A SendableMessage object. Default is an empty string.

TYPE: SendableMessage DEFAULT: ''

key

Optional bytes object representing the message key.

TYPE: Optional[bytes] DEFAULT: None

partition

Optional integer representing the partition to publish the message to.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

Optional integer representing the timestamp of the message in milliseconds.

TYPE: Optional[int] DEFAULT: None

headers

Optional dictionary of header key-value pairs.

TYPE: Optional[Dict[str, str]] DEFAULT: None

correlation_id

Optional string representing the correlation ID of the message.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION AssertionError

If _producer is not set up.

AssertionError

If batch flag is not set and there are multiple messages.

ValueError

If message is not a sequence when messages is empty.

Source code in faststream/kafka/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *messages: SendableMessage,\n    message: SendableMessage = \"\",\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n) -> None:\n    \"\"\"Publish messages to a topic.\n\n    Args:\n        *messages: Variable length argument list of SendableMessage objects.\n        message: A SendableMessage object. Default is an empty string.\n        key: Optional bytes object representing the message key.\n        partition: Optional integer representing the partition to publish the message to.\n        timestamp_ms: Optional integer representing the timestamp of the message in milliseconds.\n        headers: Optional dictionary of header key-value pairs.\n        correlation_id: Optional string representing the correlation ID of the message.\n\n    Returns:\n        None\n\n    Raises:\n        AssertionError: If `_producer` is not set up.\n        AssertionError: If `batch` flag is not set and there are multiple messages.\n        ValueError: If `message` is not a sequence when `messages` is empty.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    assert (  # nosec B101\n        self.batch or len(messages) < 2\n    ), \"You can't send multiple messages without `batch` flag\"\n    assert self.topic, \"You have to specify outgoing topic\"  # nosec B101\n\n    if not self.batch:\n        return await self._producer.publish(\n            message=next(iter(messages), message),\n            topic=self.topic,\n            key=key or self.key,\n            partition=partition or self.partition,\n            timestamp_ms=timestamp_ms or self.timestamp_ms,\n            correlation_id=correlation_id,\n            headers=headers or self.headers,\n            reply_to=self.reply_to or \"\",\n        )\n    else:\n        to_send: Sequence[SendableMessage]\n        if not messages:\n            if not isinstance(message, Sequence):\n                raise ValueError(\n                    f\"Message: {message} should be Sequence type to send in batch\"\n                )\n            else:\n                to_send = message\n        else:\n            to_send = messages\n\n        await self._producer.publish_batch(\n            *to_send,\n            topic=self.topic,\n            partition=partition or self.partition,\n            timestamp_ms=timestamp_ms or self.timestamp_ms,\n            headers=headers or self.headers,\n        )\n        return None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/","title":"KafkaRouter","text":"","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter","title":"faststream.kafka.router.KafkaRouter","text":"
KafkaRouter(\n    prefix: str = \"\",\n    handlers: Sequence[KafkaRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[aiokafka.ConsumerRecord, KafkaMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[KafkaMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: KafkaRouter

A class to represent a Kafka router.

METHOD DESCRIPTION _get_publisher_key

Get the key for a publisher

_update_publisher_prefix

Update the prefix of a publisher

publisher

Create a new publisher

Source code in faststream/kafka/router.py
        publisher: The publisher object.\n\n    Returns:\n        The publisher key.\n\n    \"\"\"\n    return publisher.topic\n\n@override\n@staticmethod\ndef _update_publisher_prefix(  # type: ignore[override]\n    prefix: str,\n    publisher: Publisher,\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.publisher","title":"publisher","text":"
publisher(\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n

Publishes a message to a topic.

PARAMETER DESCRIPTION topic

The topic to publish the message to.

TYPE: str

key

The key associated with the message.

TYPE: bytes DEFAULT: None

partition

The partition to publish the message to.

TYPE: int DEFAULT: None

timestamp_ms

The timestamp of the message in milliseconds.

TYPE: int DEFAULT: None

headers

Additional headers for the message.

TYPE: Dict[str, str] DEFAULT: None

reply_to

The topic to reply to.

TYPE: str DEFAULT: ''

batch

Whether to publish the message as part of a batch.

TYPE: bool DEFAULT: False

title

The title of the message.

TYPE: str DEFAULT: None

description

The description of the message.

TYPE: str DEFAULT: None

RETURNS DESCRIPTION Publisher

The publisher object used to publish the message.

TYPE: Publisher

Source code in faststream/kafka/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"Publishes a message to a topic.\n\n    Args:\n        topic (str): The topic to publish the message to.\n        key (bytes, optional): The key associated with the message.\n        partition (int, optional): The partition to publish the message to.\n        timestamp_ms (int, optional): The timestamp of the message in milliseconds.\n        headers (Dict[str, str], optional): Additional headers for the message.\n        reply_to (str, optional): The topic to reply to.\n        batch (bool, optional): Whether to publish the message as part of a batch.\n        title (str, optional): The title of the message.\n        description (str, optional): The description of the message.\n\n    Returns:\n        Publisher: The publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            topic=topic,\n            key=key,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            batch=batch,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.subscriber","title":"subscriber","text":"
subscriber(\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    value_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\", \"earliest\", \"none\"\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[\n        AbstractPartitionAssignor\n    ] = (RoundRobinPartitionAssignor),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\", \"read_committed\"\n    ] = \"read_uncommitted\",\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[aiokafka.ConsumerRecord, KafkaMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[KafkaMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Filter[KafkaMessage] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    retry: Union[bool, int] = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aiokafka.ConsumerRecord,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n
Source code in faststream/kafka/router.py
    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"Publishes a message to a topic.\n\n    Args:\n        topic (str): The topic to publish the message to.\n        key (bytes, optional): The key associated with the message.\n        partition (int, optional): The partition to publish the message to.\n        timestamp_ms (int, optional): The timestamp of the message in milliseconds.\n        headers (Dict[str, str], optional): Additional headers for the message.\n        reply_to (str, optional): The topic to reply to.\n        batch (bool, optional): Whether to publish the message as part of a batch.\n        title (str, optional): The title of the message.\n        description (str, optional): The description of the message.\n\n    Returns:\n        Publisher: The publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            topic=topic,\n            key=key,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            batch=batch,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/security/parse_security/","title":"parse_security","text":"","boost":0.5},{"location":"api/faststream/kafka/security/parse_security/#faststream.kafka.security.parse_security","title":"faststream.kafka.security.parse_security","text":"
parse_security(security: Optional[BaseSecurity]) -> AnyDict\n
Source code in faststream/kafka/security.py
def parse_security(security: Optional[BaseSecurity]) -> AnyDict:\n    if security is None:\n        return {}\n    elif type(security) == BaseSecurity:\n        return _parse_base_security(security)\n    elif type(security) == SASLPlaintext:\n        return _parse_sasl_plaintext(security)\n    elif type(security) == SASLScram256:\n        return _parse_sasl_scram256(security)\n    elif type(security) == SASLScram512:\n        return _parse_sasl_scram512(security)\n    else:\n        raise NotImplementedError(f\"KafkaBroker does not support {type(security)}\")\n
","boost":0.5},{"location":"api/faststream/kafka/shared/logging/KafkaLoggingMixin/","title":"KafkaLoggingMixin","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/logging/KafkaLoggingMixin/#faststream.kafka.shared.logging.KafkaLoggingMixin","title":"faststream.kafka.shared.logging.KafkaLoggingMixin","text":"
KafkaLoggingMixin(\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any\n)\n

Bases: LoggingMixin

A class that provides logging functionality for Kafka.

METHOD DESCRIPTION __init__

initializes the KafkaLoggingMixin object

_get_log_context

returns the log context for a given message and topics

fmt

returns the log format string

_setup_log_context

sets up the log context for a given list of topics

Initialize the class.

PARAMETER DESCRIPTION *args

Variable length argument list

TYPE: Any DEFAULT: ()

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: access_logger

log_level

Log level (default: logging.INFO)

TYPE: int DEFAULT: INFO

log_fmt

Optional log format string

TYPE: Optional[str] DEFAULT: None

**kwargs

Arbitrary keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None

Source code in faststream/kafka/shared/logging.py
def __init__(\n    self,\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        *args: Variable length argument list\n        logger: Optional logger object\n        log_level: Log level (default: logging.INFO)\n        log_fmt: Optional log format string\n        **kwargs: Arbitrary keyword arguments\n\n    Returns:\n        None\n\n    \"\"\"\n    super().__init__(\n        *args,\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n        **kwargs,\n    )\n    self._max_topic_len = 4\n    self._max_group_len = 0\n
","boost":0.5},{"location":"api/faststream/kafka/shared/logging/KafkaLoggingMixin/#faststream.kafka.shared.logging.KafkaLoggingMixin.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/logging/KafkaLoggingMixin/#faststream.kafka.shared.logging.KafkaLoggingMixin.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/kafka/shared/logging/KafkaLoggingMixin/#faststream.kafka.shared.logging.KafkaLoggingMixin.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/","title":"ABCPublisher","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher","title":"faststream.kafka.shared.publisher.ABCPublisher dataclass","text":"

Bases: ABC, BasePublisher[MsgType]

A class representing an ABCPublisher.

","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = None\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.key","title":"key class-attribute instance-attribute","text":"
key: Optional[bytes] = None\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.partition","title":"partition class-attribute instance-attribute","text":"
partition: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = ''\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.timestamp_ms","title":"timestamp_ms class-attribute instance-attribute","text":"
timestamp_ms: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.topic","title":"topic class-attribute instance-attribute","text":"
topic: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.publish","title":"publish abstractmethod async","text":"
publish(\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

correlation_id

Optional correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/publisher.py
@abstractmethod\nasync def publish(\n    self,\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        correlation_id: Optional correlation ID for the message.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/","title":"BrokerRouter","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter","title":"faststream.broker.router.BrokerRouter","text":"
BrokerRouter(\n    prefix: str = \"\",\n    handlers: Sequence[\n        BrokerRoute[MsgType, SendableMessage]\n    ] = (),\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    include_in_schema: Optional[bool] = None,\n)\n

Bases: Generic[PublisherKeyType, MsgType]

A generic class representing a broker router.

METHOD DESCRIPTION _get_publisher_key

abstract method to get the publisher key

_update_publisher_prefix

abstract method to update the publisher prefix

__init__

constructor method

subscriber

abstract method to define a subscriber

_wrap_subscriber

method to wrap a subscriber function

publisher

abstract method to define a publisher

include_router

method to include a router

include_routers

method to include multiple routers

Initialize a class object.

PARAMETER DESCRIPTION prefix

Prefix for the object.

TYPE: str DEFAULT: ''

handlers

Handlers for the object.

TYPE: Sequence[BrokerRoute[MsgType, SendableMessage]] DEFAULT: ()

dependencies

Dependencies for the object.

TYPE: Sequence[Depends] DEFAULT: ()

middlewares

Middlewares for the object.

TYPE: Optional[Sequence[Callable[[StreamMessage[MsgType]], AsyncContextManager[None]]]] DEFAULT: None

parser

Parser for the object.

TYPE: Optional[CustomParser[MsgType]] DEFAULT: None

decoder

Decoder for the object.

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

Source code in faststream/broker/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[BrokerRoute[MsgType, SendableMessage]] = (),\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    include_in_schema: Optional[bool] = None,\n) -> None:\n    \"\"\"Initialize a class object.\n\n    Args:\n        prefix (str): Prefix for the object.\n        handlers (Sequence[BrokerRoute[MsgType, SendableMessage]]): Handlers for the object.\n        dependencies (Sequence[Depends]): Dependencies for the object.\n        middlewares (Optional[Sequence[Callable[[StreamMessage[MsgType]], AsyncContextManager[None]]]]): Middlewares for the object.\n        parser (Optional[CustomParser[MsgType]]): Parser for the object.\n        decoder (Optional[CustomDecoder[StreamMessage[MsgType]]]): Decoder for the object.\n\n    \"\"\"\n    self.prefix = prefix\n    self.include_in_schema = include_in_schema\n    self._handlers = list(handlers)\n    self._publishers = {}\n    self._dependencies = dependencies\n    self._middlewares = middlewares\n    self._parser = parser\n    self._decoder = decoder\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.subscriber","title":"subscriber abstractmethod","text":"
subscriber(\n    subj: str,\n    *args: Any,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    include_in_schema: Optional[bool] = None,\n    **kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function to subscribe to a subject.

PARAMETER DESCRIPTION subj

subject to subscribe to

*args

additional arguments

DEFAULT: ()

dependencies

sequence of dependencies

DEFAULT: ()

middlewares

optional sequence of middlewares

DEFAULT: None

parser

optional custom parser

DEFAULT: None

decoder

optional custom decoder

DEFAULT: None

**kwargs

additional keyword arguments

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable handler function

RAISES DESCRIPTION NotImplementedError

If the function is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef subscriber(\n    self,\n    subj: str,\n    *args: Any,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    include_in_schema: Optional[bool] = None,\n    **kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function to subscribe to a subject.\n\n    Args:\n        subj : subject to subscribe to\n        *args : additional arguments\n        dependencies : sequence of dependencies\n        middlewares : optional sequence of middlewares\n        parser : optional custom parser\n        decoder : optional custom decoder\n        **kwargs : additional keyword arguments\n\n    Returns:\n        A callable handler function\n\n    Raises:\n        NotImplementedError: If the function is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRoute/","title":"KafkaRoute","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/","title":"KafkaRouter","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter","title":"faststream.kafka.shared.router.KafkaRouter","text":"
KafkaRouter(\n    prefix: str = \"\",\n    handlers: Sequence[\n        KafkaRoute[ConsumerRecord, SendableMessage]\n    ] = (),\n    **kwargs: Any\n)\n

Bases: BrokerRouter[str, ConsumerRecord]

A class to represent a Kafka router.

METHOD DESCRIPTION subscriber

decorator for subscribing to topics and handling messages

Initialize the class.

PARAMETER DESCRIPTION prefix

Prefix string.

TYPE: str DEFAULT: ''

handlers

Sequence of KafkaRoute objects.

TYPE: Sequence[BrokerRoute[ConsumerRecord, SendableMessage]] DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/kafka/shared/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[KafkaRoute[ConsumerRecord, SendableMessage]] = (),\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        prefix (str): Prefix string.\n        handlers (Sequence[KafkaRoute[ConsumerRecord, SendableMessage]]): Sequence of KafkaRoute objects.\n        **kwargs (Any): Additional keyword arguments.\n\n    \"\"\"\n    for h in handlers:\n        h.args = tuple(prefix + x for x in h.args)\n    super().__init__(prefix, handlers, **kwargs)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.subscriber","title":"subscriber","text":"
subscriber(\n    *topics: str, **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        ConsumerRecord, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function to subscribe to topics.

PARAMETER DESCRIPTION *topics

variable number of topic names

DEFAULT: ()

**broker_kwargs

keyword arguments for the broker

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn]]

A callable function that wraps the handler function

Source code in faststream/kafka/shared/router.py
def subscriber(\n    self,\n    *topics: str,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function to subscribe to topics.\n\n    Args:\n        *topics : variable number of topic names\n        **broker_kwargs : keyword arguments for the broker\n\n    Returns:\n        A callable function that wraps the handler function\n\n    \"\"\"\n    return self._wrap_subscriber(\n        *(self.prefix + x for x in topics),\n        **broker_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/","title":"ConsumerConnectionParams","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams","title":"faststream.kafka.shared.schemas.ConsumerConnectionParams","text":"

Bases: TypedDict

A class to represent the connection parameters for a consumer.

","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.api_version","title":"api_version instance-attribute","text":"
api_version: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.bootstrap_servers","title":"bootstrap_servers instance-attribute","text":"
bootstrap_servers: Required[Union[str, List[str]]]\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.client_id","title":"client_id instance-attribute","text":"
client_id: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.connections_max_idle_ms","title":"connections_max_idle_ms instance-attribute","text":"
connections_max_idle_ms: int\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.loop","title":"loop instance-attribute","text":"
loop: Optional[AbstractEventLoop]\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.metadata_max_age_ms","title":"metadata_max_age_ms instance-attribute","text":"
metadata_max_age_ms: int\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.request_timeout_ms","title":"request_timeout_ms instance-attribute","text":"
request_timeout_ms: int\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.retry_backoff_ms","title":"retry_backoff_ms instance-attribute","text":"
retry_backoff_ms: int\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_kerberos_domain_name","title":"sasl_kerberos_domain_name instance-attribute","text":"
sasl_kerberos_domain_name: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_kerberos_service_name","title":"sasl_kerberos_service_name instance-attribute","text":"
sasl_kerberos_service_name: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_mechanism","title":"sasl_mechanism instance-attribute","text":"
sasl_mechanism: Literal[\n    \"PLAIN\",\n    \"GSSAPI\",\n    \"SCRAM-SHA-256\",\n    \"SCRAM-SHA-512\",\n    \"OAUTHBEARER\",\n]\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_oauth_token_provider","title":"sasl_oauth_token_provider instance-attribute","text":"
sasl_oauth_token_provider: AbstractTokenProvider\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_plain_password","title":"sasl_plain_password instance-attribute","text":"
sasl_plain_password: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_plain_username","title":"sasl_plain_username instance-attribute","text":"
sasl_plain_username: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.security_protocol","title":"security_protocol instance-attribute","text":"
security_protocol: Literal['SSL', 'PLAINTEXT']\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context: ssl.SSLContext\n
","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/","title":"FakeProducer","text":"","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/#faststream.kafka.test.FakeProducer","title":"faststream.kafka.test.FakeProducer","text":"
FakeProducer(broker: KafkaBroker)\n

Bases: AioKafkaFastProducer

A fake Kafka producer for testing purposes.

This class extends AioKafkaFastProducer and is used to simulate Kafka message publishing during tests.

Initialize the FakeProducer.

PARAMETER DESCRIPTION broker

The KafkaBroker instance to associate with this FakeProducer.

TYPE: KafkaBroker

Source code in faststream/kafka/test.py
def __init__(self, broker: KafkaBroker) -> None:\n    \"\"\"\n    Initialize the FakeProducer.\n\n    Args:\n        broker (KafkaBroker): The KafkaBroker instance to associate with this FakeProducer.\n    \"\"\"\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/#faststream.kafka.test.FakeProducer.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/#faststream.kafka.test.FakeProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\",\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False\n) -> Optional[SendableMessage]\n

Publish a message to the Kafka broker.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

topic

The Kafka topic to publish the message to.

TYPE: str

key

The message key. Defaults to None.

TYPE: Optional[bytes] DEFAULT: None

partition

The Kafka partition to use. Defaults to None.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

The message timestamp in milliseconds. Defaults to None.

TYPE: Optional[int] DEFAULT: None

headers

Additional headers for the message. Defaults to None.

TYPE: Optional[Dict[str, str]] DEFAULT: None

correlation_id

The correlation ID for the message. Defaults to None.

TYPE: Optional[str] DEFAULT: None

reply_to

The topic to which responses should be sent. Defaults to \"\".

TYPE: str DEFAULT: ''

rpc

If True, treat the message as an RPC request. Defaults to False.

TYPE: bool DEFAULT: False

rpc_timeout

Timeout for RPC requests. Defaults to None.

TYPE: Optional[float] DEFAULT: None

raise_timeout

If True, raise an exception on timeout. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION Optional[SendableMessage]

Optional[SendableMessage]: The response message, if this was an RPC request, otherwise None.

Source code in faststream/kafka/test.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\",\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False,\n) -> Optional[SendableMessage]:\n    \"\"\"\n    Publish a message to the Kafka broker.\n\n    Args:\n        message (SendableMessage): The message to be published.\n        topic (str): The Kafka topic to publish the message to.\n        key (Optional[bytes], optional): The message key. Defaults to None.\n        partition (Optional[int], optional): The Kafka partition to use. Defaults to None.\n        timestamp_ms (Optional[int], optional): The message timestamp in milliseconds. Defaults to None.\n        headers (Optional[Dict[str, str]], optional): Additional headers for the message. Defaults to None.\n        correlation_id (Optional[str], optional): The correlation ID for the message. Defaults to None.\n        reply_to (str, optional): The topic to which responses should be sent. Defaults to \"\".\n        rpc (bool, optional): If True, treat the message as an RPC request. Defaults to False.\n        rpc_timeout (Optional[float], optional): Timeout for RPC requests. Defaults to None.\n        raise_timeout (bool, optional): If True, raise an exception on timeout. Defaults to False.\n\n    Returns:\n        Optional[SendableMessage]: The response message, if this was an RPC request, otherwise None.\n    \"\"\"\n    incoming = build_message(\n        message=message,\n        topic=topic,\n        key=key,\n        partition=partition,\n        timestamp_ms=timestamp_ms,\n        headers=headers,\n        correlation_id=correlation_id,\n        reply_to=reply_to,\n    )\n\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        if topic in handler.topics:\n            return await call_handler(\n                handler=handler,\n                message=[incoming] if handler.batch else incoming,\n                rpc=rpc,\n                rpc_timeout=rpc_timeout,\n                raise_timeout=raise_timeout,\n            )\n\n    return None\n
","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/#faststream.kafka.test.FakeProducer.publish_batch","title":"publish_batch async","text":"
publish_batch(\n    *msgs: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None\n) -> None\n

Publish a batch of messages to the Kafka broker.

PARAMETER DESCRIPTION *msgs

Variable number of messages to be published.

TYPE: SendableMessage DEFAULT: ()

topic

The Kafka topic to publish the messages to.

TYPE: str

partition

The Kafka partition to use. Defaults to None.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

The message timestamp in milliseconds. Defaults to None.

TYPE: Optional[int] DEFAULT: None

headers

Additional headers for the messages. Defaults to None.

TYPE: Optional[Dict[str, str]] DEFAULT: None

RETURNS DESCRIPTION None

This method does not return a value.

TYPE: None

Source code in faststream/kafka/test.py
async def publish_batch(\n    self,\n    *msgs: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n) -> None:\n    \"\"\"\n    Publish a batch of messages to the Kafka broker.\n\n    Args:\n        *msgs (SendableMessage): Variable number of messages to be published.\n        topic (str): The Kafka topic to publish the messages to.\n        partition (Optional[int], optional): The Kafka partition to use. Defaults to None.\n        timestamp_ms (Optional[int], optional): The message timestamp in milliseconds. Defaults to None.\n        headers (Optional[Dict[str, str]], optional): Additional headers for the messages. Defaults to None.\n\n    Returns:\n        None: This method does not return a value.\n    \"\"\"\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        if topic in handler.topics:\n            await call_handler(\n                handler=handler,\n                message=[\n                    build_message(\n                        message=message,\n                        topic=topic,\n                        partition=partition,\n                        timestamp_ms=timestamp_ms,\n                        headers=headers,\n                    )\n                    for message in msgs\n                ],\n            )\n\n    return None\n
","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/#faststream.kafka.test.FakeProducer.stop","title":"stop async","text":"
stop() -> None\n
Source code in faststream/kafka/producer.py
async def stop(self) -> None:\n    if self._producer is not None:  # pragma: no branch\n        await self._producer.stop()\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/","title":"TestKafkaBroker","text":"","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker","title":"faststream.kafka.test.TestKafkaBroker","text":"
TestKafkaBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[KafkaBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/kafka/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: KafkaBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(  # type: ignore[call-overload,misc]\n        publisher.topic,\n        batch=publisher.batch,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f  # type: ignore[no-any-return]\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: KafkaBroker, publisher: Any\n) -> None\n
Source code in faststream/kafka/test.py
@staticmethod\ndef patch_publisher(broker: KafkaBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> None\n
Source code in faststream/kafka/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> None:\n    broker.handlers.pop(publisher.topic, None)\n
","boost":0.5},{"location":"api/faststream/kafka/test/build_message/","title":"build_message","text":"","boost":0.5},{"location":"api/faststream/kafka/test/build_message/#faststream.kafka.test.build_message","title":"faststream.kafka.test.build_message","text":"
build_message(\n    message: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    key: Optional[bytes] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\"\n) -> ConsumerRecord\n

Build a Kafka ConsumerRecord for a sendable message.

PARAMETER DESCRIPTION message

The sendable message to be encoded.

TYPE: SendableMessage

topic

The Kafka topic for the message.

TYPE: str

partition

The Kafka partition for the message. Defaults to None.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

The message timestamp in milliseconds. Defaults to None.

TYPE: Optional[int] DEFAULT: None

key

The message key. Defaults to None.

TYPE: Optional[bytes] DEFAULT: None

headers

Additional headers for the message. Defaults to None.

TYPE: Optional[Dict[str, str]] DEFAULT: None

correlation_id

The correlation ID for the message. Defaults to None.

TYPE: Optional[str] DEFAULT: None

reply_to

The topic to which responses should be sent. Defaults to \"\".

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION ConsumerRecord

A Kafka ConsumerRecord object.

TYPE: ConsumerRecord

Source code in faststream/kafka/test.py
def build_message(\n    message: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    key: Optional[bytes] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\",\n) -> ConsumerRecord:\n    \"\"\"\n    Build a Kafka ConsumerRecord for a sendable message.\n\n    Args:\n        message (SendableMessage): The sendable message to be encoded.\n        topic (str): The Kafka topic for the message.\n        partition (Optional[int], optional): The Kafka partition for the message. Defaults to None.\n        timestamp_ms (Optional[int], optional): The message timestamp in milliseconds. Defaults to None.\n        key (Optional[bytes], optional): The message key. Defaults to None.\n        headers (Optional[Dict[str, str]], optional): Additional headers for the message. Defaults to None.\n        correlation_id (Optional[str], optional): The correlation ID for the message. Defaults to None.\n        reply_to (str, optional): The topic to which responses should be sent. Defaults to \"\".\n\n    Returns:\n        ConsumerRecord: A Kafka ConsumerRecord object.\n    \"\"\"\n    msg, content_type = encode_message(message)\n    k = key or b\"\"\n    headers = {\n        \"content-type\": content_type or \"\",\n        \"correlation_id\": correlation_id or str(uuid4()),\n        \"reply_to\": reply_to,\n        **(headers or {}),\n    }\n\n    return ConsumerRecord(\n        value=msg,\n        topic=topic,\n        partition=partition or 0,\n        timestamp=timestamp_ms or int(datetime.now().timestamp()),\n        timestamp_type=0,\n        key=k,\n        serialized_key_size=len(k),\n        serialized_value_size=len(msg),\n        checksum=sum(msg),\n        offset=0,\n        headers=[(i, j.encode()) for i, j in headers.items()],\n    )\n
","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/","title":"ColourizedFormatter","text":"","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/#faststream.log.formatter.ColourizedFormatter","title":"faststream.log.formatter.ColourizedFormatter","text":"
ColourizedFormatter(\n    fmt: Optional[str] = None,\n    datefmt: Optional[str] = None,\n    style: Literal[\"%\", \"{\", \"$\"] = \"%\",\n    use_colors: Optional[bool] = None,\n)\n

Bases: Formatter

A class to format log messages with colorized level names.

METHOD DESCRIPTION __init__

Initialize the formatter with specified format strings.

color_level_name

Colorize the level name based on the log level.

formatMessage

Format the log record message with colorized level name.

Initialize the formatter with specified format strings.

Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.

Use a style parameter of '%', '{' or '$' to specify that you want to use one of %-formatting, :meth:str.format ({}) formatting or :class:string.Template formatting in your format string.

Source code in faststream/log/formatter.py
def __init__(\n    self,\n    fmt: Optional[str] = None,\n    datefmt: Optional[str] = None,\n    style: Literal[\"%\", \"{\", \"$\"] = \"%\",\n    use_colors: Optional[bool] = None,\n) -> None:\n    \"\"\"\n    Initialize the formatter with specified format strings.\n\n    Initialize the formatter either with the specified format string, or a\n    default as described above. Allow for specialized date formatting with\n    the optional datefmt argument. If datefmt is omitted, you get an\n    ISO8601-like (or RFC 3339-like) format.\n\n    Use a style parameter of '%', '{' or '$' to specify that you want to\n    use one of %-formatting, :meth:`str.format` (``{}``) formatting or\n    :class:`string.Template` formatting in your format string.\n    \"\"\"\n    if use_colors in (True, False):\n        self.use_colors = use_colors\n    else:\n        self.use_colors = sys.stdout.isatty()\n    super().__init__(fmt=fmt, datefmt=datefmt, style=style)\n
","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/#faststream.log.formatter.ColourizedFormatter.level_name_colors","title":"level_name_colors class-attribute instance-attribute","text":"
level_name_colors: DefaultDict[\n    str, Callable[[str], str]\n] = defaultdict(\n    lambda: str,\n    **{\n        str(logging.DEBUG): lambda: click.style(\n            str(level_name), fg=\"cyan\"\n        ),\n        str(logging.INFO): lambda: click.style(\n            str(level_name), fg=\"green\"\n        ),\n        str(logging.WARNING): lambda: click.style(\n            str(level_name), fg=\"yellow\"\n        ),\n        str(logging.ERROR): lambda: click.style(\n            str(level_name), fg=\"red\"\n        ),\n        str(logging.CRITICAL): lambda: click.style(\n            str(level_name), fg=\"bright_red\"\n        ),\n    }\n)\n
","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/#faststream.log.formatter.ColourizedFormatter.use_colors","title":"use_colors instance-attribute","text":"
use_colors = use_colors\n
","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/#faststream.log.formatter.ColourizedFormatter.color_level_name","title":"color_level_name","text":"
color_level_name(level_name: str, level_no: int) -> str\n

Returns the colored level name.

PARAMETER DESCRIPTION level_name

The name of the level.

TYPE: str

level_no

The number of the level.

TYPE: int

RETURNS DESCRIPTION str

The colored level name.

RAISES DESCRIPTION KeyError

If the level number is not found in the level name colors dictionary.

Source code in faststream/log/formatter.py
def color_level_name(self, level_name: str, level_no: int) -> str:\n    \"\"\"Returns the colored level name.\n\n    Args:\n        level_name: The name of the level.\n        level_no: The number of the level.\n\n    Returns:\n        The colored level name.\n\n    Raises:\n        KeyError: If the level number is not found in the level name colors dictionary.\n\n    \"\"\"\n    return self.level_name_colors[str(level_no)](level_name)\n
","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/#faststream.log.formatter.ColourizedFormatter.formatMessage","title":"formatMessage","text":"
formatMessage(record: logging.LogRecord) -> str\n

Formats the log message.

PARAMETER DESCRIPTION record

The log record to format.

TYPE: LogRecord

RETURNS DESCRIPTION str

The formatted log message.

TYPE: str

Source code in faststream/log/formatter.py
def formatMessage(self, record: logging.LogRecord) -> str:\n    \"\"\"Formats the log message.\n\n    Args:\n        record (logging.LogRecord): The log record to format.\n\n    Returns:\n        str: The formatted log message.\n\n    \"\"\"\n    levelname = expand_log_field(record.levelname, 8)\n    if self.use_colors is True:  # pragma: no cover\n        levelname = self.color_level_name(levelname, record.levelno)\n    record.__dict__[\"levelname\"] = levelname\n    return super().formatMessage(record)\n
","boost":0.5},{"location":"api/faststream/log/formatter/expand_log_field/","title":"expand_log_field","text":"","boost":0.5},{"location":"api/faststream/log/formatter/expand_log_field/#faststream.log.formatter.expand_log_field","title":"faststream.log.formatter.expand_log_field","text":"
expand_log_field(field: str, symbols: int) -> str\n

Expands a log field by adding spaces.

PARAMETER DESCRIPTION field

The log field to expand.

TYPE: str

symbols

The desired length of the expanded field.

TYPE: int

RETURNS DESCRIPTION str

The expanded log field.

Source code in faststream/log/formatter.py
def expand_log_field(field: str, symbols: int) -> str:\n    \"\"\"Expands a log field by adding spaces.\n\n    Args:\n        field: The log field to expand.\n        symbols: The desired length of the expanded field.\n\n    Returns:\n        The expanded log field.\n\n    \"\"\"\n    return field + (\" \" * (symbols - len(field)))\n
","boost":0.5},{"location":"api/faststream/log/formatter/make_record_with_extra/","title":"make_record_with_extra","text":"","boost":0.5},{"location":"api/faststream/log/formatter/make_record_with_extra/#faststream.log.formatter.make_record_with_extra","title":"faststream.log.formatter.make_record_with_extra","text":"
make_record_with_extra(\n    self: logging.Logger,\n    name: str,\n    level: int,\n    fn: str,\n    lno: int,\n    msg: str,\n    args: Tuple[str],\n    exc_info: Optional[\n        Union[\n            Tuple[\n                Type[BaseException],\n                BaseException,\n                Optional[TracebackType],\n            ],\n            Tuple[None, None, None],\n        ]\n    ],\n    func: Optional[str] = None,\n    extra: Optional[Mapping[str, object]] = None,\n    sinfo: Optional[str] = None,\n) -> logging.LogRecord\n

Creates a log record with additional information.

PARAMETER DESCRIPTION self

The logger object.

TYPE: Logger

name

The name of the logger.

TYPE: str

level

The logging level.

TYPE: int

fn

The filename where the log message originated.

TYPE: str

lno

The line number where the log message originated.

TYPE: int

msg

The log message.

TYPE: str

args

The arguments for the log message.

TYPE: Tuple[str]

exc_info

Information about an exception.

TYPE: Optional[Union[Tuple[Type[BaseException], BaseException, Optional[TracebackType]], Tuple[None, None, None]]]

func

The name of the function where the log message originated.

TYPE: Optional[str] DEFAULT: None

extra

Additional information to include in the log record.

TYPE: Optional[Mapping[str, object]] DEFAULT: None

sinfo

Stack information.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION LogRecord

The log record.

Note

If extra is None, it will be set to the value of context.get_local(\"log_context\").

Source code in faststream/log/formatter.py
def make_record_with_extra(\n    self: logging.Logger,\n    name: str,\n    level: int,\n    fn: str,\n    lno: int,\n    msg: str,\n    args: Tuple[str],\n    exc_info: Optional[\n        Union[\n            Tuple[Type[BaseException], BaseException, Optional[TracebackType]],\n            Tuple[None, None, None],\n        ]\n    ],\n    func: Optional[str] = None,\n    extra: Optional[Mapping[str, object]] = None,\n    sinfo: Optional[str] = None,\n) -> logging.LogRecord:\n    \"\"\"Creates a log record with additional information.\n\n    Args:\n        self: The logger object.\n        name: The name of the logger.\n        level: The logging level.\n        fn: The filename where the log message originated.\n        lno: The line number where the log message originated.\n        msg: The log message.\n        args: The arguments for the log message.\n        exc_info: Information about an exception.\n        func: The name of the function where the log message originated.\n        extra: Additional information to include in the log record.\n        sinfo: Stack information.\n\n    Returns:\n        The log record.\n\n    Note:\n        If `extra` is `None`, it will be set to the value of `context.get_local(\"log_context\")`.\n\n    \"\"\"\n    if extra is None:\n        extra = context.get_local(\n            \"log_context\", default=context.get(\"default_log_context\")\n        )\n\n    record = original_makeRecord(\n        self,\n        name,\n        level,\n        fn,\n        lno,\n        msg,\n        args,\n        exc_info,\n        func,\n        extra,\n        sinfo,\n    )\n\n    return record\n
","boost":0.5},{"location":"api/faststream/log/logging/configure_formatter/","title":"configure_formatter","text":"","boost":0.5},{"location":"api/faststream/log/logging/configure_formatter/#faststream.log.logging.configure_formatter","title":"faststream.log.logging.configure_formatter","text":"
configure_formatter(\n    formatter: Type[logging.Formatter],\n    *args: Any,\n    **kwargs: Any\n) -> logging.Formatter\n

Configures a logging formatter.

PARAMETER DESCRIPTION formatter

The type of logging formatter to configure.

TYPE: Type[Formatter]

*args

Additional positional arguments to pass to the formatter constructor.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments to pass to the formatter constructor.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Formatter

An instance of the configured logging formatter.

Source code in faststream/log/logging.py
def configure_formatter(\n    formatter: Type[logging.Formatter], *args: Any, **kwargs: Any\n) -> logging.Formatter:\n    \"\"\"Configures a logging formatter.\n\n    Args:\n        formatter: The type of logging formatter to configure.\n        *args: Additional positional arguments to pass to the formatter constructor.\n        **kwargs: Additional keyword arguments to pass to the formatter constructor.\n\n    Returns:\n        An instance of the configured logging formatter.\n\n    \"\"\"\n    return formatter(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/nats/AckPolicy/","title":"AckPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/AckPolicy/#nats.js.api.AckPolicy","title":"nats.js.api.AckPolicy","text":"

Bases: str, Enum

Policies defining how messages should be acknowledged.

If an ack is required but is not received within the AckWait window, the message will be redelivered.

References ","boost":0.5},{"location":"api/faststream/nats/AckPolicy/#nats.js.api.AckPolicy.ALL","title":"ALL class-attribute instance-attribute","text":"
ALL = 'all'\n
","boost":0.5},{"location":"api/faststream/nats/AckPolicy/#nats.js.api.AckPolicy.EXPLICIT","title":"EXPLICIT class-attribute instance-attribute","text":"
EXPLICIT = 'explicit'\n
","boost":0.5},{"location":"api/faststream/nats/AckPolicy/#nats.js.api.AckPolicy.NONE","title":"NONE class-attribute instance-attribute","text":"
NONE = 'none'\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/","title":"ConsumerConfig","text":"","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig","title":"nats.js.api.ConsumerConfig dataclass","text":"

Bases: Base

Consumer configuration.

References ","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.ack_policy","title":"ack_policy class-attribute instance-attribute","text":"
ack_policy: Optional[AckPolicy] = AckPolicy.EXPLICIT\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.ack_wait","title":"ack_wait class-attribute instance-attribute","text":"
ack_wait: Optional[float] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.deliver_group","title":"deliver_group class-attribute instance-attribute","text":"
deliver_group: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.deliver_policy","title":"deliver_policy class-attribute instance-attribute","text":"
deliver_policy: Optional[DeliverPolicy] = DeliverPolicy.ALL\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.deliver_subject","title":"deliver_subject class-attribute instance-attribute","text":"
deliver_subject: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.durable_name","title":"durable_name class-attribute instance-attribute","text":"
durable_name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.filter_subject","title":"filter_subject class-attribute instance-attribute","text":"
filter_subject: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.flow_control","title":"flow_control class-attribute instance-attribute","text":"
flow_control: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.headers_only","title":"headers_only class-attribute instance-attribute","text":"
headers_only: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.idle_heartbeat","title":"idle_heartbeat class-attribute instance-attribute","text":"
idle_heartbeat: Optional[float] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.inactive_threshold","title":"inactive_threshold class-attribute instance-attribute","text":"
inactive_threshold: Optional[float] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.max_ack_pending","title":"max_ack_pending class-attribute instance-attribute","text":"
max_ack_pending: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.max_deliver","title":"max_deliver class-attribute instance-attribute","text":"
max_deliver: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.max_waiting","title":"max_waiting class-attribute instance-attribute","text":"
max_waiting: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.mem_storage","title":"mem_storage class-attribute instance-attribute","text":"
mem_storage: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.num_replicas","title":"num_replicas class-attribute instance-attribute","text":"
num_replicas: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.opt_start_seq","title":"opt_start_seq class-attribute instance-attribute","text":"
opt_start_seq: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.opt_start_time","title":"opt_start_time class-attribute instance-attribute","text":"
opt_start_time: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.rate_limit_bps","title":"rate_limit_bps class-attribute instance-attribute","text":"
rate_limit_bps: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.replay_policy","title":"replay_policy class-attribute instance-attribute","text":"
replay_policy: Optional[ReplayPolicy] = ReplayPolicy.INSTANT\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.sample_freq","title":"sample_freq class-attribute instance-attribute","text":"
sample_freq: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n
Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    result = super().as_dict()\n    result['ack_wait'] = self._to_nanoseconds(self.ack_wait)\n    result['idle_heartbeat'] = self._to_nanoseconds(self.idle_heartbeat)\n    result['inactive_threshold'] = self._to_nanoseconds(\n        self.inactive_threshold\n    )\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any])\n
Source code in nats/js/api.py
@classmethod\ndef from_response(cls, resp: Dict[str, Any]):\n    cls._convert_nanoseconds(resp, 'ack_wait')\n    cls._convert_nanoseconds(resp, 'idle_heartbeat')\n    cls._convert_nanoseconds(resp, 'inactive_threshold')\n    return super().from_response(resp)\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/","title":"DeliverPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy","title":"nats.js.api.DeliverPolicy","text":"

Bases: str, Enum

When a consumer is first created, it can specify where in the stream it wants to start receiving messages.

This is the DeliverPolicy, and this enumeration defines allowed values.

References ","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.ALL","title":"ALL class-attribute instance-attribute","text":"
ALL = 'all'\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.BY_START_SEQUENCE","title":"BY_START_SEQUENCE class-attribute instance-attribute","text":"
BY_START_SEQUENCE = 'by_start_sequence'\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.BY_START_TIME","title":"BY_START_TIME class-attribute instance-attribute","text":"
BY_START_TIME = 'by_start_time'\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.LAST","title":"LAST class-attribute instance-attribute","text":"
LAST = 'last'\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.LAST_PER_SUBJECT","title":"LAST_PER_SUBJECT class-attribute instance-attribute","text":"
LAST_PER_SUBJECT = 'last_per_subject'\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.NEW","title":"NEW class-attribute instance-attribute","text":"
NEW = 'new'\n
","boost":0.5},{"location":"api/faststream/nats/DiscardPolicy/","title":"DiscardPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/DiscardPolicy/#nats.js.api.DiscardPolicy","title":"nats.js.api.DiscardPolicy","text":"

Bases: str, Enum

Discard policy when a stream reaches its limits

","boost":0.5},{"location":"api/faststream/nats/DiscardPolicy/#nats.js.api.DiscardPolicy.NEW","title":"NEW class-attribute instance-attribute","text":"
NEW = 'new'\n
","boost":0.5},{"location":"api/faststream/nats/DiscardPolicy/#nats.js.api.DiscardPolicy.OLD","title":"OLD class-attribute instance-attribute","text":"
OLD = 'old'\n
","boost":0.5},{"location":"api/faststream/nats/ExternalStream/","title":"ExternalStream","text":"","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream","title":"nats.js.api.ExternalStream dataclass","text":"

Bases: Base

","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream.api","title":"api instance-attribute","text":"
api: str\n
","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream.deliver","title":"deliver class-attribute instance-attribute","text":"
deliver: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/JStream/","title":"JStream","text":"","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream","title":"faststream.nats.JStream","text":"
JStream(\n    name: str,\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any\n)\n

Bases: NameRequired

Source code in faststream/nats/js_stream.py
def __init__(\n    self,\n    name: str,\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any,\n) -> None:\n    super().__init__(\n        name=name,\n        declare=declare,\n        subjects=[],\n        config=StreamConfig(\n            *args,\n            name=name,\n            **kwargs,  # type: ignore[misc]\n        ),\n    )\n
","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream.config","title":"config instance-attribute","text":"
config: StreamConfig\n
","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream.declare","title":"declare class-attribute instance-attribute","text":"
declare: bool = Field(default=True)\n
","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream.subjects","title":"subjects class-attribute instance-attribute","text":"
subjects: List[str] = Field(default_factory=list)\n
","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/","title":"NatsBroker","text":"","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker","title":"faststream.nats.NatsBroker","text":"
NatsBroker(\n    servers: Union[str, Sequence[str]] = (\n        \"nats://localhost:4222\"\n    ),\n    *,\n    security: Optional[BaseSecurity] = None,\n    protocol: str = \"nats\",\n    protocol_version: Optional[str] = \"custom\",\n    **kwargs: Any\n)\n

Bases: NatsLoggingMixin, BrokerAsyncUsecase[Msg, Client]

Source code in faststream/nats/broker.py
def __init__(\n    self,\n    servers: Union[str, Sequence[str]] = (\"nats://localhost:4222\",),  # noqa: B006\n    *,\n    security: Optional[BaseSecurity] = None,\n    protocol: str = \"nats\",\n    protocol_version: Optional[str] = \"custom\",\n    **kwargs: Any,\n) -> None:\n    kwargs.update(parse_security(security))\n\n    if kwargs.get(\"tls\"):  # pragma: no cover\n        warnings.warn(\n            (\n                \"\\nNATS `tls` option was deprecated and will be removed in 0.4.0\"\n                \"\\nPlease, use `security` with `BaseSecurity` or `SASLPlaintext` instead\"\n            ),\n            DeprecationWarning,\n            stacklevel=2,\n        )\n\n    super().__init__(\n        url=([servers] if isinstance(servers, str) else list(servers)),\n        protocol=protocol,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n    )\n\n    self.__is_connected = False\n    self._producer = None\n\n    # JS options\n    self.stream = None\n    self._js_producer = None\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[Subject, Handler]\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.stream","title":"stream instance-attribute","text":"
stream: Optional[JetStreamContext] = None\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.url","title":"url instance-attribute","text":"
url: List[str]\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.connect","title":"connect async","text":"
connect(*args: Any, **kwargs: Any) -> Client\n
Source code in faststream/nats/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Client:\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        self.__set_publisher_producer(p)\n    return connection\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, stream: Optional[str] = None, **kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    stream: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[DecodedMessage]:\n    if stream is None:\n        assert self._producer, NOT_CONNECTED_YET  # nosec B101\n        return await self._producer.publish(*args, **kwargs)\n    else:\n        assert self._js_producer, NOT_CONNECTED_YET  # nosec B101\n        return await self._js_producer.publish(\n            *args,\n            stream=stream,\n            **kwargs,  # type: ignore[misc]\n        )\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.publisher","title":"publisher","text":"
publisher(\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    stream: Union[str, JStream, None] = None,\n    timeout: Optional[float] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/nats/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    # Core\n    reply_to: str = \"\",\n    # JS\n    stream: Union[str, JStream, None] = None,\n    timeout: Optional[float] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    if (stream := stream_builder.stream(stream)) is not None:\n        stream.subjects.append(subject)\n\n    publisher = self._publishers.get(\n        subject,\n        Publisher(\n            subject=subject,\n            headers=headers,\n            # Core\n            reply_to=reply_to,\n            # JS\n            timeout=timeout,\n            stream=stream,\n            # AsyncAPI\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(subject, publisher)\n    self.__set_publisher_producer(publisher)\n    return publisher\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.start","title":"start async","text":"
start() -> None\n
Source code in faststream/nats/broker.py
async def start(self) -> None:\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n    assert (\n        self._connection and self.stream\n    ), \"Broker should be started already\"  # nosec B101\n\n    for handler in self.handlers.values():\n        stream = handler.stream\n\n        if (is_js := stream is not None) and stream.declare:\n            try:  # pragma: no branch\n                await self.stream.add_stream(\n                    config=stream.config,\n                    subjects=stream.subjects,\n                )\n\n            except nats.js.errors.BadRequestError as e:\n                old_config = (await self.stream.stream_info(stream.name)).config\n\n                c = self._get_log_context(None, \"\")\n                if (\n                    e.description\n                    == \"stream name already in use with a different configuration\"\n                ):\n                    self._log(str(e), logging.WARNING, c)\n                    await self.stream.update_stream(\n                        config=stream.config,\n                        subjects=tuple(\n                            set(old_config.subjects or ()).union(stream.subjects)\n                        ),\n                    )\n\n                else:  # pragma: no cover\n                    self._log(str(e), logging.ERROR, c, exc_info=e)\n\n            finally:\n                # prevent from double declaration\n                stream.declare = False\n\n        c = self._get_log_context(\n            None,\n            subject=handler.subject,\n            queue=handler.queue,\n            stream=stream.name if stream else \"\",\n        )\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self.stream if is_js else self._connection)\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/nats/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    # Core arguments\n    max_msgs: int = 0,\n    # JS arguments\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    # pull arguments\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    # custom\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[Sequence[Callable[[Msg], BaseMiddleware]]] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],\n]:\n    stream = stream_builder.stream(stream)\n\n    if pull_sub is not None and stream is None:\n        raise ValueError(\"Pull subscriber can be used only with a stream\")\n\n    self._setup_log_context(\n        queue=queue,\n        subject=subject,\n        stream=stream.name if stream else None,\n    )\n    super().subscriber()\n\n    extra_options: AnyDict = {\n        \"pending_msgs_limit\": pending_msgs_limit\n        or (\n            DEFAULT_JS_SUB_PENDING_MSGS_LIMIT\n            if stream\n            else DEFAULT_SUB_PENDING_MSGS_LIMIT\n        ),\n        \"pending_bytes_limit\": pending_bytes_limit\n        or (\n            DEFAULT_JS_SUB_PENDING_BYTES_LIMIT\n            if stream\n            else DEFAULT_SUB_PENDING_BYTES_LIMIT\n        ),\n    }\n\n    if stream:\n        extra_options.update(\n            {\n                \"durable\": durable,\n                \"stream\": stream.name,\n                \"config\": config,\n            }\n        )\n\n        if pull_sub is not None:\n            extra_options.update({\"inbox_prefix\": inbox_prefix})\n\n        else:\n            extra_options.update(\n                {\n                    \"ordered_consumer\": ordered_consumer,\n                    \"idle_heartbeat\": idle_heartbeat,\n                    \"flow_control\": flow_control,\n                    \"deliver_policy\": deliver_policy,\n                    \"headers_only\": headers_only,\n                    \"manual_ack\": not ack_first,\n                }\n            )\n\n    else:\n        extra_options.update(\n            {\n                \"max_msgs\": max_msgs,\n            }\n        )\n\n    key = Handler.get_routing_hash(subject)\n    handler = self.handlers[key] = self.handlers.get(\n        key,\n        Handler(\n            subject=subject,\n            queue=queue,\n            stream=stream,\n            pull_sub=pull_sub,\n            extra_options=extra_options,\n            title=title,\n            description=description,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n            log_context_builder=partial(\n                self._get_log_context,\n                stream=stream.name if stream else \"\",\n                subject=subject,\n                queue=queue,\n            ),\n        ),\n    )\n\n    if stream:\n        stream.subjects.append(handler.subject)\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn,]:\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/nats/NatsRoute/","title":"NatsRoute","text":"","boost":0.5},{"location":"api/faststream/nats/NatsRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/nats/NatsRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/nats/NatsRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/nats/NatsRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/","title":"NatsRouter","text":"","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter","title":"faststream.nats.NatsRouter","text":"
NatsRouter(\n    prefix: str = \"\",\n    handlers: Sequence[NatsRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: NatsRouter

Source code in faststream/nats/router.py
    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.publisher","title":"publisher","text":"
publisher(\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/nats/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            subject=subject,\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    retry: bool = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
","boost":0.5},{"location":"api/faststream/nats/Placement/","title":"Placement","text":"","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement","title":"nats.js.api.Placement dataclass","text":"

Bases: Base

Placement directives to consider when placing replicas of this stream

","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement.cluster","title":"cluster class-attribute instance-attribute","text":"
cluster: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/PullSub/","title":"PullSub","text":"","boost":0.5},{"location":"api/faststream/nats/PullSub/#faststream.nats.PullSub","title":"faststream.nats.PullSub","text":"
PullSub(\n    batch_size: int = 1,\n    timeout: Optional[float] = 5.0,\n    batch: bool = False,\n)\n

Bases: BaseModel

Source code in faststream/nats/pull_sub.py
def __init__(\n    self,\n    batch_size: int = 1,\n    timeout: Optional[float] = 5.0,\n    batch: bool = False,\n) -> None:\n    super().__init__(\n        batch_size=batch_size,\n        timeout=timeout,\n        batch=batch,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/PullSub/#faststream.nats.PullSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = Field(default=False)\n
","boost":0.5},{"location":"api/faststream/nats/PullSub/#faststream.nats.PullSub.batch_size","title":"batch_size class-attribute instance-attribute","text":"
batch_size: int = Field(default=1)\n
","boost":0.5},{"location":"api/faststream/nats/PullSub/#faststream.nats.PullSub.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: Optional[float] = Field(default=5.0)\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/","title":"RePublish","text":"","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish","title":"nats.js.api.RePublish dataclass","text":"

Bases: Base

RePublish is for republishing messages once committed to a stream. The original subject cis remapped from the subject pattern to the destination pattern.

","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.dest","title":"dest class-attribute instance-attribute","text":"
dest: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.headers_only","title":"headers_only class-attribute instance-attribute","text":"
headers_only: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.src","title":"src class-attribute instance-attribute","text":"
src: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/ReplayPolicy/","title":"ReplayPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/ReplayPolicy/#nats.js.api.ReplayPolicy","title":"nats.js.api.ReplayPolicy","text":"

Bases: str, Enum

The replay policy applies when the DeliverPolicy is one of

since those deliver policies begin reading the stream at a position other than the end.

References ","boost":0.5},{"location":"api/faststream/nats/ReplayPolicy/#nats.js.api.ReplayPolicy.INSTANT","title":"INSTANT class-attribute instance-attribute","text":"
INSTANT = 'instant'\n
","boost":0.5},{"location":"api/faststream/nats/ReplayPolicy/#nats.js.api.ReplayPolicy.ORIGINAL","title":"ORIGINAL class-attribute instance-attribute","text":"
ORIGINAL = 'original'\n
","boost":0.5},{"location":"api/faststream/nats/RetentionPolicy/","title":"RetentionPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/RetentionPolicy/#nats.js.api.RetentionPolicy","title":"nats.js.api.RetentionPolicy","text":"

Bases: str, Enum

How message retention is considered

","boost":0.5},{"location":"api/faststream/nats/RetentionPolicy/#nats.js.api.RetentionPolicy.INTEREST","title":"INTEREST class-attribute instance-attribute","text":"
INTEREST = 'interest'\n
","boost":0.5},{"location":"api/faststream/nats/RetentionPolicy/#nats.js.api.RetentionPolicy.LIMITS","title":"LIMITS class-attribute instance-attribute","text":"
LIMITS = 'limits'\n
","boost":0.5},{"location":"api/faststream/nats/RetentionPolicy/#nats.js.api.RetentionPolicy.WORK_QUEUE","title":"WORK_QUEUE class-attribute instance-attribute","text":"
WORK_QUEUE = 'workqueue'\n
","boost":0.5},{"location":"api/faststream/nats/StorageType/","title":"StorageType","text":"","boost":0.5},{"location":"api/faststream/nats/StorageType/#nats.js.api.StorageType","title":"nats.js.api.StorageType","text":"

Bases: str, Enum

The type of storage backend

","boost":0.5},{"location":"api/faststream/nats/StorageType/#nats.js.api.StorageType.FILE","title":"FILE class-attribute instance-attribute","text":"
FILE = 'file'\n
","boost":0.5},{"location":"api/faststream/nats/StorageType/#nats.js.api.StorageType.MEMORY","title":"MEMORY class-attribute instance-attribute","text":"
MEMORY = 'memory'\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/","title":"StreamConfig","text":"","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig","title":"nats.js.api.StreamConfig dataclass","text":"

Bases: Base

StreamConfig represents the configuration of a stream.

","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.allow_direct","title":"allow_direct class-attribute instance-attribute","text":"
allow_direct: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.allow_rollup_hdrs","title":"allow_rollup_hdrs class-attribute instance-attribute","text":"
allow_rollup_hdrs: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.deny_delete","title":"deny_delete class-attribute instance-attribute","text":"
deny_delete: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.deny_purge","title":"deny_purge class-attribute instance-attribute","text":"
deny_purge: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.discard","title":"discard class-attribute instance-attribute","text":"
discard: Optional[DiscardPolicy] = DiscardPolicy.OLD\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.duplicate_window","title":"duplicate_window class-attribute instance-attribute","text":"
duplicate_window: float = 0\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_age","title":"max_age class-attribute instance-attribute","text":"
max_age: Optional[float] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_bytes","title":"max_bytes class-attribute instance-attribute","text":"
max_bytes: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_consumers","title":"max_consumers class-attribute instance-attribute","text":"
max_consumers: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_msg_size","title":"max_msg_size class-attribute instance-attribute","text":"
max_msg_size: Optional[int] = -1\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_msgs","title":"max_msgs class-attribute instance-attribute","text":"
max_msgs: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_msgs_per_subject","title":"max_msgs_per_subject class-attribute instance-attribute","text":"
max_msgs_per_subject: int = -1\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.mirror","title":"mirror class-attribute instance-attribute","text":"
mirror: Optional[StreamSource] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.mirror_direct","title":"mirror_direct class-attribute instance-attribute","text":"
mirror_direct: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.no_ack","title":"no_ack class-attribute instance-attribute","text":"
no_ack: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.num_replicas","title":"num_replicas class-attribute instance-attribute","text":"
num_replicas: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.placement","title":"placement class-attribute instance-attribute","text":"
placement: Optional[Placement] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.republish","title":"republish class-attribute instance-attribute","text":"
republish: Optional[RePublish] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.retention","title":"retention class-attribute instance-attribute","text":"
retention: Optional[RetentionPolicy] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.sealed","title":"sealed class-attribute instance-attribute","text":"
sealed: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.sources","title":"sources class-attribute instance-attribute","text":"
sources: Optional[List[StreamSource]] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.storage","title":"storage class-attribute instance-attribute","text":"
storage: Optional[StorageType] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.subjects","title":"subjects class-attribute instance-attribute","text":"
subjects: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.template_owner","title":"template_owner class-attribute instance-attribute","text":"
template_owner: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n
Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    result = super().as_dict()\n    result['duplicate_window'] = self._to_nanoseconds(\n        self.duplicate_window\n    )\n    result['max_age'] = self._to_nanoseconds(self.max_age)\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any])\n
Source code in nats/js/api.py
@classmethod\ndef from_response(cls, resp: Dict[str, Any]):\n    cls._convert_nanoseconds(resp, 'max_age')\n    cls._convert_nanoseconds(resp, 'duplicate_window')\n    cls._convert(resp, 'placement', Placement)\n    cls._convert(resp, 'mirror', StreamSource)\n    cls._convert(resp, 'sources', StreamSource)\n    cls._convert(resp, 'republish', RePublish)\n    return super().from_response(resp)\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/","title":"StreamSource","text":"","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource","title":"nats.js.api.StreamSource dataclass","text":"

Bases: Base

","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.external","title":"external class-attribute instance-attribute","text":"
external: Optional[ExternalStream] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.filter_subject","title":"filter_subject class-attribute instance-attribute","text":"
filter_subject: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.opt_start_seq","title":"opt_start_seq class-attribute instance-attribute","text":"
opt_start_seq: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any])\n
Source code in nats/js/api.py
@classmethod\ndef from_response(cls, resp: Dict[str, Any]):\n    cls._convert(resp, 'external', ExternalStream)\n    return super().from_response(resp)\n
","boost":0.5},{"location":"api/faststream/nats/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/nats/TestApp/#faststream.broker.test.TestApp","title":"faststream.broker.test.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/nats/TestApp/#faststream.broker.test.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/","title":"TestNatsBroker","text":"","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker","title":"faststream.nats.TestNatsBroker","text":"
TestNatsBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[NatsBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/nats/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: NatsBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(publisher.subject, _raw=True)\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(broker: NatsBroker, publisher: Any) -> None\n
Source code in faststream/nats/test.py
@staticmethod\ndef patch_publisher(broker: NatsBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> None\n
Source code in faststream/nats/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> None:\n    broker.handlers.pop(Handler.get_routing_hash(publisher.subject), None)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/","title":"Handler","text":"","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler","title":"faststream.nats.asyncapi.Handler","text":"
Handler(\n    subject: str,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    queue: str = \"\",\n    stream: Optional[JStream] = None,\n    pull_sub: Optional[PullSub] = None,\n    extra_options: Optional[AnyDict] = None,\n    graceful_timeout: Optional[float] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n)\n

Bases: LogicNatsHandler

Source code in faststream/nats/handler.py
def __init__(\n    self,\n    subject: str,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    queue: str = \"\",\n    stream: Optional[JStream] = None,\n    pull_sub: Optional[PullSub] = None,\n    extra_options: Optional[AnyDict] = None,\n    graceful_timeout: Optional[float] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    reg, path = compile_path(subject, replace_symbol=\"*\")\n    self.subject = path\n    self.path_regex = reg\n\n    self.queue = queue\n\n    self.stream = stream\n    self.pull_sub = pull_sub\n    self.extra_options = extra_options or {}\n\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        include_in_schema=include_in_schema,\n        title=title,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.task = None\n    self.subscription = None\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.extra_options","title":"extra_options instance-attribute","text":"
extra_options = extra_options or {}\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.path_regex","title":"path_regex instance-attribute","text":"
path_regex = reg\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.pull_sub","title":"pull_sub instance-attribute","text":"
pull_sub = pull_sub\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.queue","title":"queue instance-attribute","text":"
queue = queue\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.stream","title":"stream instance-attribute","text":"
stream = stream\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.subject","title":"subject instance-attribute","text":"
subject = path\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.subscription","title":"subscription instance-attribute","text":"
subscription: Union[\n    None,\n    Subscription,\n    JetStreamContext.PushSubscription,\n    JetStreamContext.PullSubscription,\n] = None\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.task","title":"task class-attribute instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[Msg, NatsMessage]],\n    decoder: Optional[CustomDecoder[NatsMessage]],\n    filter: Filter[NatsMessage],\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ]\n) -> None\n
Source code in faststream/nats/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[Msg, NatsMessage]],\n    decoder: Optional[CustomDecoder[NatsMessage]],\n    filter: Filter[NatsMessage],\n    middlewares: Optional[Sequence[Callable[[Msg], BaseMiddleware]]],\n) -> None:\n    parser_ = Parser if self.stream is None else JsParser\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, parser_.parse_message),\n        decoder=resolve_custom_func(decoder, parser_.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/nats/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.subscription is not None:\n        await self.subscription.unsubscribe()\n        self.subscription = None\n\n    if self.task is not None:\n        self.task.cancel()\n        self.task = None\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(subject: str) -> str\n
Source code in faststream/nats/handler.py
@staticmethod\ndef get_routing_hash(subject: str) -> str:\n    return subject\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/nats/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n    handler_name = self._title or f\"{self.subject}:{self.call_name}\"\n    return {\n        handler_name: Channel(\n            description=self.description,\n            subscribe=Operation(\n                message=Message(\n                    title=f\"{handler_name}:Message\",\n                    payload=resolve_payloads(payloads),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                nats=nats.ChannelBinding(\n                    subject=self.subject,\n                    queue=self.queue or None,\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.start","title":"start async","text":"
start(connection: Union[Client, JetStreamContext]) -> None\n
Source code in faststream/nats/handler.py
@override\nasync def start(self, connection: Union[Client, JetStreamContext]) -> None:  # type: ignore[override]\n    if self.pull_sub is not None:\n        connection = cast(JetStreamContext, connection)\n\n        if self.stream is None:\n            raise ValueError(\"Pull subscriber can be used only with a stream\")\n\n        self.subscription = await connection.pull_subscribe(\n            subject=self.subject,\n            **self.extra_options,\n        )\n        self.task = asyncio.create_task(self._consume())\n\n    else:\n        self.subscription = await connection.subscribe(\n            subject=self.subject,\n            queue=self.queue,\n            cb=self.consume,  # type: ignore[arg-type]\n            **self.extra_options,\n        )\n\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/","title":"Publisher","text":"","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher","title":"faststream.nats.asyncapi.Publisher","text":"

Bases: LogicPublisher

","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.name","title":"name property","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.stream","title":"stream class-attribute instance-attribute","text":"
stream: Optional[JStream] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.subject","title":"subject class-attribute instance-attribute","text":"
subject: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: Optional[float] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.publish","title":"publish async","text":"
publish(\n    message: SendableMessage = \"\",\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[Dict[str, str]] = None,\n    **producer_kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage = \"\",\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[Dict[str, str]] = None,\n    **producer_kwargs: Any,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    assert self.subject, \"You have to specify outgoing subject\"  # nosec B101\n\n    extra: AnyDict = {\n        \"reply_to\": reply_to or self.reply_to,\n    }\n    if self.stream is not None:\n        extra.update(\n            {\n                \"stream\": self.stream.name,\n                \"timeout\": self.timeout,\n            }\n        )\n\n    return await self._producer.publish(\n        message=message,\n        subject=self.subject,\n        headers=headers or self.headers,\n        correlation_id=correlation_id,\n        **extra,\n        **producer_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/nats/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    return {\n        self.name: Channel(\n            description=self.description,\n            publish=Operation(\n                message=Message(\n                    title=f\"{self.name}:Message\",\n                    payload=resolve_payloads(payloads, \"Publisher\"),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                nats=nats.ChannelBinding(\n                    subject=self.subject,\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/","title":"NatsBroker","text":"","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker","title":"faststream.nats.broker.NatsBroker","text":"
NatsBroker(\n    servers: Union[str, Sequence[str]] = (\n        \"nats://localhost:4222\"\n    ),\n    *,\n    security: Optional[BaseSecurity] = None,\n    protocol: str = \"nats\",\n    protocol_version: Optional[str] = \"custom\",\n    **kwargs: Any\n)\n

Bases: NatsLoggingMixin, BrokerAsyncUsecase[Msg, Client]

Source code in faststream/nats/broker.py
def __init__(\n    self,\n    servers: Union[str, Sequence[str]] = (\"nats://localhost:4222\",),  # noqa: B006\n    *,\n    security: Optional[BaseSecurity] = None,\n    protocol: str = \"nats\",\n    protocol_version: Optional[str] = \"custom\",\n    **kwargs: Any,\n) -> None:\n    kwargs.update(parse_security(security))\n\n    if kwargs.get(\"tls\"):  # pragma: no cover\n        warnings.warn(\n            (\n                \"\\nNATS `tls` option was deprecated and will be removed in 0.4.0\"\n                \"\\nPlease, use `security` with `BaseSecurity` or `SASLPlaintext` instead\"\n            ),\n            DeprecationWarning,\n            stacklevel=2,\n        )\n\n    super().__init__(\n        url=([servers] if isinstance(servers, str) else list(servers)),\n        protocol=protocol,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n    )\n\n    self.__is_connected = False\n    self._producer = None\n\n    # JS options\n    self.stream = None\n    self._js_producer = None\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[Subject, Handler]\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.stream","title":"stream instance-attribute","text":"
stream: Optional[JetStreamContext] = None\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.url","title":"url instance-attribute","text":"
url: List[str]\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.connect","title":"connect async","text":"
connect(*args: Any, **kwargs: Any) -> Client\n
Source code in faststream/nats/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Client:\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        self.__set_publisher_producer(p)\n    return connection\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, stream: Optional[str] = None, **kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    stream: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[DecodedMessage]:\n    if stream is None:\n        assert self._producer, NOT_CONNECTED_YET  # nosec B101\n        return await self._producer.publish(*args, **kwargs)\n    else:\n        assert self._js_producer, NOT_CONNECTED_YET  # nosec B101\n        return await self._js_producer.publish(\n            *args,\n            stream=stream,\n            **kwargs,  # type: ignore[misc]\n        )\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.publisher","title":"publisher","text":"
publisher(\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    stream: Union[str, JStream, None] = None,\n    timeout: Optional[float] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/nats/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    # Core\n    reply_to: str = \"\",\n    # JS\n    stream: Union[str, JStream, None] = None,\n    timeout: Optional[float] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    if (stream := stream_builder.stream(stream)) is not None:\n        stream.subjects.append(subject)\n\n    publisher = self._publishers.get(\n        subject,\n        Publisher(\n            subject=subject,\n            headers=headers,\n            # Core\n            reply_to=reply_to,\n            # JS\n            timeout=timeout,\n            stream=stream,\n            # AsyncAPI\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(subject, publisher)\n    self.__set_publisher_producer(publisher)\n    return publisher\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.start","title":"start async","text":"
start() -> None\n
Source code in faststream/nats/broker.py
async def start(self) -> None:\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n    assert (\n        self._connection and self.stream\n    ), \"Broker should be started already\"  # nosec B101\n\n    for handler in self.handlers.values():\n        stream = handler.stream\n\n        if (is_js := stream is not None) and stream.declare:\n            try:  # pragma: no branch\n                await self.stream.add_stream(\n                    config=stream.config,\n                    subjects=stream.subjects,\n                )\n\n            except nats.js.errors.BadRequestError as e:\n                old_config = (await self.stream.stream_info(stream.name)).config\n\n                c = self._get_log_context(None, \"\")\n                if (\n                    e.description\n                    == \"stream name already in use with a different configuration\"\n                ):\n                    self._log(str(e), logging.WARNING, c)\n                    await self.stream.update_stream(\n                        config=stream.config,\n                        subjects=tuple(\n                            set(old_config.subjects or ()).union(stream.subjects)\n                        ),\n                    )\n\n                else:  # pragma: no cover\n                    self._log(str(e), logging.ERROR, c, exc_info=e)\n\n            finally:\n                # prevent from double declaration\n                stream.declare = False\n\n        c = self._get_log_context(\n            None,\n            subject=handler.subject,\n            queue=handler.queue,\n            stream=stream.name if stream else \"\",\n        )\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self.stream if is_js else self._connection)\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/nats/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    # Core arguments\n    max_msgs: int = 0,\n    # JS arguments\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    # pull arguments\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    # custom\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[Sequence[Callable[[Msg], BaseMiddleware]]] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],\n]:\n    stream = stream_builder.stream(stream)\n\n    if pull_sub is not None and stream is None:\n        raise ValueError(\"Pull subscriber can be used only with a stream\")\n\n    self._setup_log_context(\n        queue=queue,\n        subject=subject,\n        stream=stream.name if stream else None,\n    )\n    super().subscriber()\n\n    extra_options: AnyDict = {\n        \"pending_msgs_limit\": pending_msgs_limit\n        or (\n            DEFAULT_JS_SUB_PENDING_MSGS_LIMIT\n            if stream\n            else DEFAULT_SUB_PENDING_MSGS_LIMIT\n        ),\n        \"pending_bytes_limit\": pending_bytes_limit\n        or (\n            DEFAULT_JS_SUB_PENDING_BYTES_LIMIT\n            if stream\n            else DEFAULT_SUB_PENDING_BYTES_LIMIT\n        ),\n    }\n\n    if stream:\n        extra_options.update(\n            {\n                \"durable\": durable,\n                \"stream\": stream.name,\n                \"config\": config,\n            }\n        )\n\n        if pull_sub is not None:\n            extra_options.update({\"inbox_prefix\": inbox_prefix})\n\n        else:\n            extra_options.update(\n                {\n                    \"ordered_consumer\": ordered_consumer,\n                    \"idle_heartbeat\": idle_heartbeat,\n                    \"flow_control\": flow_control,\n                    \"deliver_policy\": deliver_policy,\n                    \"headers_only\": headers_only,\n                    \"manual_ack\": not ack_first,\n                }\n            )\n\n    else:\n        extra_options.update(\n            {\n                \"max_msgs\": max_msgs,\n            }\n        )\n\n    key = Handler.get_routing_hash(subject)\n    handler = self.handlers[key] = self.handlers.get(\n        key,\n        Handler(\n            subject=subject,\n            queue=queue,\n            stream=stream,\n            pull_sub=pull_sub,\n            extra_options=extra_options,\n            title=title,\n            description=description,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n            log_context_builder=partial(\n                self._get_log_context,\n                stream=stream.name if stream else \"\",\n                subject=subject,\n                queue=queue,\n            ),\n        ),\n    )\n\n    if stream:\n        stream.subjects.append(handler.subject)\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn,]:\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/nats/fastapi/Context/#faststream.broker.fastapi.context.Context","title":"faststream.broker.fastapi.context.Context","text":"
Context(name: str) -> Any\n
Source code in faststream/broker/fastapi/context.py
def Context(name: str) -> Any:\n    return params.Depends(\n        lambda: context.resolve(name),\n        use_cache=True,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/","title":"NatsRouter","text":"","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter","title":"faststream.nats.fastapi.NatsRouter","text":"
NatsRouter(\n    servers: Union[str, Sequence[str]] = (\n        \"nats://localhost:4222\"\n    ),\n    *,\n    error_cb: Optional[ErrorCallback] = None,\n    disconnected_cb: Optional[Callback] = None,\n    closed_cb: Optional[Callback] = None,\n    discovered_server_cb: Optional[Callback] = None,\n    reconnected_cb: Optional[Callback] = None,\n    name: Optional[str] = None,\n    pedantic: bool = False,\n    verbose: bool = False,\n    allow_reconnect: bool = True,\n    connect_timeout: int = DEFAULT_CONNECT_TIMEOUT,\n    reconnect_time_wait: int = DEFAULT_RECONNECT_TIME_WAIT,\n    max_reconnect_attempts: int = DEFAULT_MAX_RECONNECT_ATTEMPTS,\n    ping_interval: int = DEFAULT_PING_INTERVAL,\n    max_outstanding_pings: int = DEFAULT_MAX_OUTSTANDING_PINGS,\n    dont_randomize: bool = False,\n    flusher_queue_size: int = DEFAULT_MAX_FLUSHER_QUEUE_SIZE,\n    no_echo: bool = False,\n    tls: Optional[ssl.SSLContext] = None,\n    tls_hostname: Optional[str] = None,\n    user: Optional[str] = None,\n    password: Optional[str] = None,\n    token: Optional[str] = None,\n    drain_timeout: int = DEFAULT_DRAIN_TIMEOUT,\n    signature_cb: Optional[SignatureCallback] = None,\n    user_jwt_cb: Optional[JWTCallback] = None,\n    user_credentials: Optional[Credentials] = None,\n    nkeys_seed: Optional[str] = None,\n    inbox_prefix: Union[str, bytes] = DEFAULT_INBOX_PREFIX,\n    pending_size: int = DEFAULT_PENDING_SIZE,\n    flush_timeout: Optional[float] = None,\n    graceful_timeout: Optional[float] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    asyncapi_url: Union[str, List[str], None] = None,\n    protocol: str = \"nats\",\n    protocol_version: Optional[str] = \"0.9.1\",\n    description: Optional[str] = None,\n    asyncapi_tags: Optional[Sequence[asyncapi.Tag]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    setup_state: bool = True,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n)\n

Bases: StreamRouter[Msg]

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.broker","title":"broker instance-attribute","text":"
broker: NatsBroker\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.broker_class","title":"broker_class class-attribute instance-attribute","text":"
broker_class = NB\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    subject: str,\n    *,\n    endpoint: Callable[..., T_HandlerReturn],\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    retry: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    **__service_kwargs: Any\n) -> Callable[[Msg, bool], Awaitable[T_HandlerReturn]]\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.publisher","title":"publisher","text":"
publisher(\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    stream: Union[str, JStream, None] = None,\n    timeout: Optional[float] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    retry: bool = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/","title":"LogicNatsHandler","text":"","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler","title":"faststream.nats.handler.LogicNatsHandler","text":"
LogicNatsHandler(\n    subject: str,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    queue: str = \"\",\n    stream: Optional[JStream] = None,\n    pull_sub: Optional[PullSub] = None,\n    extra_options: Optional[AnyDict] = None,\n    graceful_timeout: Optional[float] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n)\n

Bases: AsyncHandler[Msg]

Source code in faststream/nats/handler.py
def __init__(\n    self,\n    subject: str,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    queue: str = \"\",\n    stream: Optional[JStream] = None,\n    pull_sub: Optional[PullSub] = None,\n    extra_options: Optional[AnyDict] = None,\n    graceful_timeout: Optional[float] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    reg, path = compile_path(subject, replace_symbol=\"*\")\n    self.subject = path\n    self.path_regex = reg\n\n    self.queue = queue\n\n    self.stream = stream\n    self.pull_sub = pull_sub\n    self.extra_options = extra_options or {}\n\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        include_in_schema=include_in_schema,\n        title=title,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.task = None\n    self.subscription = None\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.extra_options","title":"extra_options instance-attribute","text":"
extra_options = extra_options or {}\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.path_regex","title":"path_regex instance-attribute","text":"
path_regex = reg\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.pull_sub","title":"pull_sub instance-attribute","text":"
pull_sub = pull_sub\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.queue","title":"queue instance-attribute","text":"
queue = queue\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.stream","title":"stream instance-attribute","text":"
stream = stream\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.subject","title":"subject instance-attribute","text":"
subject = path\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.subscription","title":"subscription instance-attribute","text":"
subscription: Union[\n    None,\n    Subscription,\n    JetStreamContext.PushSubscription,\n    JetStreamContext.PullSubscription,\n] = None\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.task","title":"task class-attribute instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[Msg, NatsMessage]],\n    decoder: Optional[CustomDecoder[NatsMessage]],\n    filter: Filter[NatsMessage],\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ]\n) -> None\n
Source code in faststream/nats/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[Msg, NatsMessage]],\n    decoder: Optional[CustomDecoder[NatsMessage]],\n    filter: Filter[NatsMessage],\n    middlewares: Optional[Sequence[Callable[[Msg], BaseMiddleware]]],\n) -> None:\n    parser_ = Parser if self.stream is None else JsParser\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, parser_.parse_message),\n        decoder=resolve_custom_func(decoder, parser_.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/nats/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.subscription is not None:\n        await self.subscription.unsubscribe()\n        self.subscription = None\n\n    if self.task is not None:\n        self.task.cancel()\n        self.task = None\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(subject: str) -> str\n
Source code in faststream/nats/handler.py
@staticmethod\ndef get_routing_hash(subject: str) -> str:\n    return subject\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.start","title":"start async","text":"
start(connection: Union[Client, JetStreamContext]) -> None\n
Source code in faststream/nats/handler.py
@override\nasync def start(self, connection: Union[Client, JetStreamContext]) -> None:  # type: ignore[override]\n    if self.pull_sub is not None:\n        connection = cast(JetStreamContext, connection)\n\n        if self.stream is None:\n            raise ValueError(\"Pull subscriber can be used only with a stream\")\n\n        self.subscription = await connection.pull_subscribe(\n            subject=self.subject,\n            **self.extra_options,\n        )\n        self.task = asyncio.create_task(self._consume())\n\n    else:\n        self.subscription = await connection.subscribe(\n            subject=self.subject,\n            queue=self.queue,\n            cb=self.consume,  # type: ignore[arg-type]\n            **self.extra_options,\n        )\n\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/nats/helpers/StreamBuilder/","title":"StreamBuilder","text":"","boost":0.5},{"location":"api/faststream/nats/helpers/StreamBuilder/#faststream.nats.helpers.StreamBuilder","title":"faststream.nats.helpers.StreamBuilder","text":"
StreamBuilder()\n
Source code in faststream/nats/helpers.py
def __init__(self) -> None:\n    self.streams = {}\n
","boost":0.5},{"location":"api/faststream/nats/helpers/StreamBuilder/#faststream.nats.helpers.StreamBuilder.streams","title":"streams instance-attribute","text":"
streams: Dict[str, JStream] = {}\n
","boost":0.5},{"location":"api/faststream/nats/helpers/StreamBuilder/#faststream.nats.helpers.StreamBuilder.stream","title":"stream","text":"
stream(\n    name: Union[str, JStream, None],\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any\n) -> Optional[JStream]\n
Source code in faststream/nats/helpers.py
def stream(\n    self,\n    name: Union[str, JStream, None],\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any,\n) -> Optional[JStream]:\n    stream = JStream.validate(name)\n\n    if stream is not None:\n        stream = self.streams[stream.name] = self.streams.get(stream.name, stream)\n\n    return stream\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/DiscardPolicy/","title":"DiscardPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/DiscardPolicy/#nats.js.api.DiscardPolicy","title":"nats.js.api.DiscardPolicy","text":"

Bases: str, Enum

Discard policy when a stream reaches its limits

","boost":0.5},{"location":"api/faststream/nats/js_stream/DiscardPolicy/#nats.js.api.DiscardPolicy.NEW","title":"NEW class-attribute instance-attribute","text":"
NEW = 'new'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/DiscardPolicy/#nats.js.api.DiscardPolicy.OLD","title":"OLD class-attribute instance-attribute","text":"
OLD = 'old'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/","title":"ExternalStream","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream","title":"nats.js.api.ExternalStream dataclass","text":"

Bases: Base

","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream.api","title":"api instance-attribute","text":"
api: str\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream.deliver","title":"deliver class-attribute instance-attribute","text":"
deliver: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/","title":"JStream","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream","title":"faststream.nats.js_stream.JStream","text":"
JStream(\n    name: str,\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any\n)\n

Bases: NameRequired

Source code in faststream/nats/js_stream.py
def __init__(\n    self,\n    name: str,\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any,\n) -> None:\n    super().__init__(\n        name=name,\n        declare=declare,\n        subjects=[],\n        config=StreamConfig(\n            *args,\n            name=name,\n            **kwargs,  # type: ignore[misc]\n        ),\n    )\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream.config","title":"config instance-attribute","text":"
config: StreamConfig\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream.declare","title":"declare class-attribute instance-attribute","text":"
declare: bool = Field(default=True)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream.subjects","title":"subjects class-attribute instance-attribute","text":"
subjects: List[str] = Field(default_factory=list)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/","title":"Placement","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement","title":"nats.js.api.Placement dataclass","text":"

Bases: Base

Placement directives to consider when placing replicas of this stream

","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement.cluster","title":"cluster class-attribute instance-attribute","text":"
cluster: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/","title":"RePublish","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish","title":"nats.js.api.RePublish dataclass","text":"

Bases: Base

RePublish is for republishing messages once committed to a stream. The original subject cis remapped from the subject pattern to the destination pattern.

","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.dest","title":"dest class-attribute instance-attribute","text":"
dest: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.headers_only","title":"headers_only class-attribute instance-attribute","text":"
headers_only: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.src","title":"src class-attribute instance-attribute","text":"
src: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RetentionPolicy/","title":"RetentionPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/RetentionPolicy/#nats.js.api.RetentionPolicy","title":"nats.js.api.RetentionPolicy","text":"

Bases: str, Enum

How message retention is considered

","boost":0.5},{"location":"api/faststream/nats/js_stream/RetentionPolicy/#nats.js.api.RetentionPolicy.INTEREST","title":"INTEREST class-attribute instance-attribute","text":"
INTEREST = 'interest'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RetentionPolicy/#nats.js.api.RetentionPolicy.LIMITS","title":"LIMITS class-attribute instance-attribute","text":"
LIMITS = 'limits'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RetentionPolicy/#nats.js.api.RetentionPolicy.WORK_QUEUE","title":"WORK_QUEUE class-attribute instance-attribute","text":"
WORK_QUEUE = 'workqueue'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StorageType/","title":"StorageType","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/StorageType/#nats.js.api.StorageType","title":"nats.js.api.StorageType","text":"

Bases: str, Enum

The type of storage backend

","boost":0.5},{"location":"api/faststream/nats/js_stream/StorageType/#nats.js.api.StorageType.FILE","title":"FILE class-attribute instance-attribute","text":"
FILE = 'file'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StorageType/#nats.js.api.StorageType.MEMORY","title":"MEMORY class-attribute instance-attribute","text":"
MEMORY = 'memory'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/","title":"StreamSource","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource","title":"nats.js.api.StreamSource dataclass","text":"

Bases: Base

","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.external","title":"external class-attribute instance-attribute","text":"
external: Optional[ExternalStream] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.filter_subject","title":"filter_subject class-attribute instance-attribute","text":"
filter_subject: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.opt_start_seq","title":"opt_start_seq class-attribute instance-attribute","text":"
opt_start_seq: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any])\n
Source code in nats/js/api.py
@classmethod\ndef from_response(cls, resp: Dict[str, Any]):\n    cls._convert(resp, 'external', ExternalStream)\n    return super().from_response(resp)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/","title":"NatsMessage","text":"","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage","title":"faststream.nats.message.NatsMessage dataclass","text":"

Bases: StreamMessage[Msg]

","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.is_js","title":"is_js class-attribute instance-attribute","text":"
is_js: bool = True\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.ack","title":"ack async","text":"
ack(**kwargs: Any) -> None\n
Source code in faststream/nats/message.py
async def ack(self, **kwargs: Any) -> None:\n    await super().ack()\n    if self.is_js:\n        if not isinstance(self.raw_message, list):\n            if not self.raw_message._ackd:\n                await self.raw_message.ack()\n\n        else:\n            for m in filter(\n                lambda m: not m._ackd,\n                self.raw_message,\n            ):\n                await m.ack()\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.in_progress","title":"in_progress async","text":"
in_progress(**kwargs: Any) -> None\n
Source code in faststream/nats/message.py
async def in_progress(self, **kwargs: Any) -> None:\n    if self.is_js:\n        if not isinstance(self.raw_message, list):\n            if not self.raw_message._ackd:\n                await self.raw_message.in_progress()\n\n        else:\n            for m in filter(\n                lambda m: not m._ackd,\n                self.raw_message,\n            ):\n                await m.in_progress()\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.nack","title":"nack async","text":"
nack(**kwargs: Any) -> None\n
Source code in faststream/nats/message.py
async def nack(self, **kwargs: Any) -> None:\n    await super().nack()\n    if self.is_js:\n        if not isinstance(self.raw_message, list):\n            if not self.raw_message._ackd:\n                await self.raw_message.nak(**kwargs)\n\n        else:\n            for m in filter(\n                lambda m: not m._ackd,\n                self.raw_message,\n            ):\n                await m.nak(**kwargs)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.reject","title":"reject async","text":"
reject(**kwargs: Any) -> None\n
Source code in faststream/nats/message.py
async def reject(self, **kwargs: Any) -> None:\n    await super().reject()\n    if self.is_js:\n        if not isinstance(self.raw_message, list):\n            if not self.raw_message._ackd:\n                await self.raw_message.term()\n\n        else:\n            for m in filter(\n                lambda m: not m._ackd,\n                self.raw_message,\n            ):\n                await m.term()\n
","boost":0.5},{"location":"api/faststream/nats/parser/NatsParser/","title":"NatsParser","text":"","boost":0.5},{"location":"api/faststream/nats/parser/NatsParser/#faststream.nats.parser.NatsParser","title":"faststream.nats.parser.NatsParser","text":"
NatsParser(is_js: bool)\n
Source code in faststream/nats/parser.py
def __init__(self, is_js: bool) -> None:\n    self.is_js = is_js\n
","boost":0.5},{"location":"api/faststream/nats/parser/NatsParser/#faststream.nats.parser.NatsParser.is_js","title":"is_js instance-attribute","text":"
is_js = is_js\n
","boost":0.5},{"location":"api/faststream/nats/parser/NatsParser/#faststream.nats.parser.NatsParser.decode_message","title":"decode_message async","text":"
decode_message(\n    msg: Union[StreamMessage[Msg], StreamMessage[List[Msg]]]\n) -> DecodedMessage\n
Source code in faststream/nats/parser.py
async def decode_message(\n    self,\n    msg: Union[\n        StreamMessage[Msg],\n        StreamMessage[List[Msg]],\n    ],\n) -> DecodedMessage:\n    if isinstance(msg.raw_message, list):\n        data = []\n\n        path: Optional[AnyDict] = None\n        for m in msg.raw_message:\n            msg = await self.parse_message(m, path=path)\n            path = msg.path\n\n            data.append(decode_message(msg))\n\n        return data\n\n    else:\n        return decode_message(msg)\n
","boost":0.5},{"location":"api/faststream/nats/parser/NatsParser/#faststream.nats.parser.NatsParser.parse_message","title":"parse_message async","text":"
parse_message(\n    message: Union[Msg, List[Msg]],\n    *,\n    path: Optional[AnyDict] = None\n) -> Union[StreamMessage[Msg], StreamMessage[List[Msg]]]\n
Source code in faststream/nats/parser.py
async def parse_message(\n    self, message: Union[Msg, List[Msg]], *, path: Optional[AnyDict] = None\n) -> Union[StreamMessage[Msg], StreamMessage[List[Msg]],]:\n    if isinstance(message, list):\n        return NatsMessage(\n            is_js=self.is_js,\n            raw_message=message,  # type: ignore[arg-type]\n            body=[m.data for m in message],\n        )\n\n    else:\n        path_re: Optional[Pattern[str]]\n        if (\n            path is None\n            and (handler := context.get_local(\"handler_\"))\n            and (path_re := handler.path_regex) is not None\n            and (match := path_re.match(message.subject)) is not None\n        ):\n            path = match.groupdict()\n\n        headers = message.header or {}\n\n        return NatsMessage(\n            is_js=self.is_js,\n            raw_message=message,\n            body=message.data,\n            path=path or {},\n            reply_to=headers.get(\"reply_to\", \"\") if self.is_js else message.reply,\n            headers=headers,\n            content_type=headers.get(\"content-type\", \"\"),\n            message_id=headers.get(\"message_id\", str(uuid4())),\n            correlation_id=headers.get(\"correlation_id\", str(uuid4())),\n        )\n
","boost":0.5},{"location":"api/faststream/nats/producer/NatsFastProducer/","title":"NatsFastProducer","text":"","boost":0.5},{"location":"api/faststream/nats/producer/NatsFastProducer/#faststream.nats.producer.NatsFastProducer","title":"faststream.nats.producer.NatsFastProducer","text":"
NatsFastProducer(\n    connection: Client,\n    parser: Optional[AsyncCustomParser[Msg, NatsMessage]],\n    decoder: Optional[AsyncCustomDecoder[NatsMessage]],\n)\n
Source code in faststream/nats/producer.py
def __init__(\n    self,\n    connection: Client,\n    parser: Optional[AsyncCustomParser[Msg, NatsMessage]],\n    decoder: Optional[AsyncCustomDecoder[NatsMessage]],\n) -> None:\n    self._connection = connection\n    self._parser = resolve_custom_func(parser, Parser.parse_message)\n    self._decoder = resolve_custom_func(decoder, Parser.decode_message)\n
","boost":0.5},{"location":"api/faststream/nats/producer/NatsFastProducer/#faststream.nats.producer.NatsFastProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    subject: str,\n    reply_to: str = \"\",\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/producer.py
async def publish(\n    self,\n    message: SendableMessage,\n    subject: str,\n    reply_to: str = \"\",\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    payload, content_type = encode_message(message)\n\n    headers_to_send = {\n        \"content-type\": content_type or \"\",\n        \"correlation_id\": correlation_id or str(uuid4()),\n        **(headers or {}),\n    }\n\n    client = self._connection\n\n    if rpc:\n        if reply_to:\n            raise WRONG_PUBLISH_ARGS\n\n        token = client._nuid.next()\n        token.extend(token_hex(2).encode())\n        reply_to = token.decode()\n\n        future: asyncio.Future[Msg] = asyncio.Future()\n        sub = await client.subscribe(reply_to, future=future, max_msgs=1)\n        await sub.unsubscribe(limit=1)\n\n    await client.publish(\n        subject=subject,\n        payload=payload,\n        reply=reply_to,\n        headers=headers_to_send,\n    )\n\n    if rpc:\n        msg: Any = None\n        with timeout_scope(rpc_timeout, raise_timeout):\n            msg = await future\n\n        if msg:  # pragma: no branch\n            if msg.headers:  # pragma: no cover\n                if (\n                    msg.headers.get(nats.js.api.Header.STATUS)\n                    == nats.aio.client.NO_RESPONDERS_STATUS\n                ):\n                    raise nats.errors.NoRespondersError\n            return await self._decoder(await self._parser(msg))\n\n    return None\n
","boost":0.5},{"location":"api/faststream/nats/producer/NatsJSFastProducer/","title":"NatsJSFastProducer","text":"","boost":0.5},{"location":"api/faststream/nats/producer/NatsJSFastProducer/#faststream.nats.producer.NatsJSFastProducer","title":"faststream.nats.producer.NatsJSFastProducer","text":"
NatsJSFastProducer(\n    connection: JetStreamContext,\n    parser: Optional[AsyncCustomParser[Msg, NatsMessage]],\n    decoder: Optional[AsyncCustomDecoder[NatsMessage]],\n)\n
Source code in faststream/nats/producer.py
def __init__(\n    self,\n    connection: JetStreamContext,\n    parser: Optional[AsyncCustomParser[Msg, NatsMessage]],\n    decoder: Optional[AsyncCustomDecoder[NatsMessage]],\n) -> None:\n    self._connection = connection\n    self._parser = resolve_custom_func(parser, Parser.parse_message)\n    self._decoder = resolve_custom_func(decoder, Parser.decode_message)\n
","boost":0.5},{"location":"api/faststream/nats/producer/NatsJSFastProducer/#faststream.nats.producer.NatsJSFastProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    stream: Optional[str] = None,\n    timeout: Optional[float] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/producer.py
async def publish(\n    self,\n    message: SendableMessage,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    stream: Optional[str] = None,\n    timeout: Optional[float] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    payload, content_type = encode_message(message)\n\n    headers_to_send = {\n        \"content-type\": content_type or \"\",\n        \"correlation_id\": correlation_id or str(uuid4()),\n        **(headers or {}),\n    }\n\n    if rpc:\n        if reply_to:\n            raise WRONG_PUBLISH_ARGS\n\n        reply_to = str(uuid4())\n        future: asyncio.Future[Msg] = asyncio.Future()\n        sub = await self._connection._nc.subscribe(\n            reply_to, future=future, max_msgs=1\n        )\n        await sub.unsubscribe(limit=1)\n\n    if reply_to:\n        headers_to_send.update({\"reply_to\": reply_to})\n\n    await self._connection.publish(\n        subject=subject,\n        payload=payload,\n        headers=headers_to_send,\n        stream=stream,\n        timeout=timeout,\n    )\n\n    if rpc:\n        msg: Any = None\n        with timeout_scope(rpc_timeout, raise_timeout):\n            msg = await future\n\n        if msg:  # pragma: no branch\n            if msg.headers:  # pragma: no cover\n                if (\n                    msg.headers.get(nats.js.api.Header.STATUS)\n                    == nats.aio.client.NO_RESPONDERS_STATUS\n                ):\n                    raise nats.errors.NoRespondersError\n            return await self._decoder(await self._parser(msg))\n\n    return None\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/","title":"LogicPublisher","text":"","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher","title":"faststream.nats.publisher.LogicPublisher dataclass","text":"

Bases: BasePublisher[Msg]

","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.stream","title":"stream class-attribute instance-attribute","text":"
stream: Optional[JStream] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.subject","title":"subject class-attribute instance-attribute","text":"
subject: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: Optional[float] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.publish","title":"publish async","text":"
publish(\n    message: SendableMessage = \"\",\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[Dict[str, str]] = None,\n    **producer_kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage = \"\",\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[Dict[str, str]] = None,\n    **producer_kwargs: Any,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    assert self.subject, \"You have to specify outgoing subject\"  # nosec B101\n\n    extra: AnyDict = {\n        \"reply_to\": reply_to or self.reply_to,\n    }\n    if self.stream is not None:\n        extra.update(\n            {\n                \"stream\": self.stream.name,\n                \"timeout\": self.timeout,\n            }\n        )\n\n    return await self._producer.publish(\n        message=message,\n        subject=self.subject,\n        headers=headers or self.headers,\n        correlation_id=correlation_id,\n        **extra,\n        **producer_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/nats/pull_sub/PullSub/","title":"PullSub","text":"","boost":0.5},{"location":"api/faststream/nats/pull_sub/PullSub/#faststream.nats.pull_sub.PullSub","title":"faststream.nats.pull_sub.PullSub","text":"
PullSub(\n    batch_size: int = 1,\n    timeout: Optional[float] = 5.0,\n    batch: bool = False,\n)\n

Bases: BaseModel

Source code in faststream/nats/pull_sub.py
def __init__(\n    self,\n    batch_size: int = 1,\n    timeout: Optional[float] = 5.0,\n    batch: bool = False,\n) -> None:\n    super().__init__(\n        batch_size=batch_size,\n        timeout=timeout,\n        batch=batch,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/pull_sub/PullSub/#faststream.nats.pull_sub.PullSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = Field(default=False)\n
","boost":0.5},{"location":"api/faststream/nats/pull_sub/PullSub/#faststream.nats.pull_sub.PullSub.batch_size","title":"batch_size class-attribute instance-attribute","text":"
batch_size: int = Field(default=1)\n
","boost":0.5},{"location":"api/faststream/nats/pull_sub/PullSub/#faststream.nats.pull_sub.PullSub.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: Optional[float] = Field(default=5.0)\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/","title":"NatsRouter","text":"","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter","title":"faststream.nats.router.NatsRouter","text":"
NatsRouter(\n    prefix: str = \"\",\n    handlers: Sequence[NatsRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: NatsRouter

Source code in faststream/nats/router.py
    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.publisher","title":"publisher","text":"
publisher(\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/nats/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            subject=subject,\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    retry: bool = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
","boost":0.5},{"location":"api/faststream/nats/security/parse_security/","title":"parse_security","text":"","boost":0.5},{"location":"api/faststream/nats/security/parse_security/#faststream.nats.security.parse_security","title":"faststream.nats.security.parse_security","text":"
parse_security(security: Optional[BaseSecurity]) -> AnyDict\n
Source code in faststream/nats/security.py
def parse_security(security: Optional[BaseSecurity]) -> AnyDict:\n    if security is None:\n        return {}\n    elif isinstance(security, SASLPlaintext):\n        return _parse_sasl_plaintext(security)\n    elif isinstance(security, BaseSecurity):\n        return _parse_base_security(security)\n    else:\n        raise NotImplementedError(f\"NatsBroker does not support {type(security)}\")\n
","boost":0.5},{"location":"api/faststream/nats/shared/logging/NatsLoggingMixin/","title":"NatsLoggingMixin","text":"","boost":0.5},{"location":"api/faststream/nats/shared/logging/NatsLoggingMixin/#faststream.nats.shared.logging.NatsLoggingMixin","title":"faststream.nats.shared.logging.NatsLoggingMixin","text":"
NatsLoggingMixin(\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any\n)\n

Bases: LoggingMixin

Source code in faststream/nats/shared/logging.py
def __init__(\n    self,\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any,\n) -> None:\n    super().__init__(\n        *args,\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n        **kwargs,\n    )\n    self._max_queue_len = 0\n    self._max_stream_len = 0\n    self._max_subject_len = 4\n
","boost":0.5},{"location":"api/faststream/nats/shared/logging/NatsLoggingMixin/#faststream.nats.shared.logging.NatsLoggingMixin.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/nats/shared/logging/NatsLoggingMixin/#faststream.nats.shared.logging.NatsLoggingMixin.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/nats/shared/logging/NatsLoggingMixin/#faststream.nats.shared.logging.NatsLoggingMixin.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRoute/","title":"NatsRoute","text":"","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/","title":"NatsRouter","text":"","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter","title":"faststream.nats.shared.router.NatsRouter","text":"
NatsRouter(\n    prefix: str = \"\",\n    handlers: Sequence[NatsRoute] = (),\n    **kwargs: Any\n)\n

Bases: BrokerRouter[str, Msg]

Source code in faststream/nats/shared/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[NatsRoute[Msg, SendableMessage]] = (),\n    **kwargs: Any,\n) -> None:\n    for h in handlers:\n        if not (subj := h.kwargs.pop(\"subject\", None)):\n            subj, h.args = h.args[0], h.args[1:]\n        h.args = (prefix + subj, *h.args)\n    super().__init__(prefix, handlers, **kwargs)\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str, **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/nats/shared/router.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    subject: str,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],\n]:\n    return self._wrap_subscriber(\n        self.prefix + subject,\n        **broker_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/test/FakeProducer/","title":"FakeProducer","text":"","boost":0.5},{"location":"api/faststream/nats/test/FakeProducer/#faststream.nats.test.FakeProducer","title":"faststream.nats.test.FakeProducer","text":"
FakeProducer(broker: NatsBroker)\n

Bases: NatsFastProducer

Source code in faststream/nats/test.py
def __init__(self, broker: NatsBroker) -> None:\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/nats/test/FakeProducer/#faststream.nats.test.FakeProducer.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/nats/test/FakeProducer/#faststream.nats.test.FakeProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    subject: str,\n    reply_to: str = \"\",\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    timeout: Optional[float] = None,\n    stream: Optional[str] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False\n) -> Optional[SendableMessage]\n
Source code in faststream/nats/test.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage,\n    subject: str,\n    reply_to: str = \"\",\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    # NatsJSFastProducer compatibility\n    timeout: Optional[float] = None,\n    stream: Optional[str] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False,\n) -> Optional[SendableMessage]:\n    incoming = build_message(\n        message=message,\n        subject=subject,\n        headers=headers,\n        correlation_id=correlation_id,\n        reply_to=reply_to,\n    )\n\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        call = False\n\n        if stream and getattr(handler.stream, \"name\", None) != stream:\n            continue\n\n        if subject == handler.subject:\n            call = True\n\n        else:\n            call = True\n\n            for current, base in zip_longest(\n                subject.split(\".\"),\n                handler.subject.split(\".\"),\n                fillvalue=None,\n            ):\n                if base == \">\":\n                    break\n\n                if base != \"*\" and current != base:\n                    call = False\n                    break\n\n        if call:\n            r = await call_handler(\n                handler=handler,\n                message=[incoming]\n                if getattr(handler.pull_sub, \"batch\", False)\n                else incoming,\n                rpc=rpc,\n                rpc_timeout=rpc_timeout,\n                raise_timeout=raise_timeout,\n            )\n\n            if rpc:\n                return r\n\n    return None\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/","title":"PatchedMessage","text":"","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage","title":"faststream.nats.test.PatchedMessage","text":"

Bases: Msg

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.data","title":"data class-attribute instance-attribute","text":"
data: bytes = b''\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.header","title":"header property","text":"
header: Optional[Dict[str, str]]\n

header returns the headers from a message.

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = None\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.metadata","title":"metadata property","text":"
metadata: Metadata\n

metadata returns the Metadata of a JetStream message.

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.reply","title":"reply class-attribute instance-attribute","text":"
reply: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.sid","title":"sid property","text":"
sid: int\n

sid returns the subscription ID from a message.

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.subject","title":"subject class-attribute instance-attribute","text":"
subject: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack","title":"Ack","text":"","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.AccHash","title":"AccHash class-attribute instance-attribute","text":"
AccHash = 3\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Ack","title":"Ack class-attribute instance-attribute","text":"
Ack = b'+ACK'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Consumer","title":"Consumer class-attribute instance-attribute","text":"
Consumer = 5\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.ConsumerSeq","title":"ConsumerSeq class-attribute instance-attribute","text":"
ConsumerSeq = 8\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Domain","title":"Domain class-attribute instance-attribute","text":"
Domain = 2\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Nak","title":"Nak class-attribute instance-attribute","text":"
Nak = b'-NAK'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.NumDelivered","title":"NumDelivered class-attribute instance-attribute","text":"
NumDelivered = 6\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.NumPending","title":"NumPending class-attribute instance-attribute","text":"
NumPending = 10\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Prefix0","title":"Prefix0 class-attribute instance-attribute","text":"
Prefix0 = '$JS'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Prefix1","title":"Prefix1 class-attribute instance-attribute","text":"
Prefix1 = 'ACK'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Progress","title":"Progress class-attribute instance-attribute","text":"
Progress = b'+WPI'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Stream","title":"Stream class-attribute instance-attribute","text":"
Stream = 4\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.StreamSeq","title":"StreamSeq class-attribute instance-attribute","text":"
StreamSeq = 7\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Term","title":"Term class-attribute instance-attribute","text":"
Term = b'+TERM'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Timestamp","title":"Timestamp class-attribute instance-attribute","text":"
Timestamp = 9\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata","title":"Metadata dataclass","text":"

Metadata is the metadata from a JetStream message.

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.consumer","title":"consumer instance-attribute","text":"
consumer: str\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.domain","title":"domain class-attribute instance-attribute","text":"
domain: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.num_delivered","title":"num_delivered instance-attribute","text":"
num_delivered: int\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.num_pending","title":"num_pending instance-attribute","text":"
num_pending: int\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.sequence","title":"sequence instance-attribute","text":"
sequence: SequencePair\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.stream","title":"stream instance-attribute","text":"
stream: str\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.timestamp","title":"timestamp instance-attribute","text":"
timestamp: datetime.datetime\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.SequencePair","title":"SequencePair dataclass","text":"

SequencePair represents a pair of consumer and stream sequence.

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.SequencePair.consumer","title":"consumer instance-attribute","text":"
consumer: int\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.SequencePair.stream","title":"stream instance-attribute","text":"
stream: int\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.ack","title":"ack async","text":"
ack() -> None\n
Source code in faststream/nats/test.py
async def ack(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.ack_sync","title":"ack_sync async","text":"
ack_sync(timeout: float = 1) -> PatchedMessage\n
Source code in faststream/nats/test.py
async def ack_sync(\n    self, timeout: float = 1\n) -> \"PatchedMessage\":  # pragma: no cover\n    return self\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.in_progress","title":"in_progress async","text":"
in_progress() -> None\n
Source code in faststream/nats/test.py
async def in_progress(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.nak","title":"nak async","text":"
nak(delay: Union[int, float, None] = None) -> None\n
Source code in faststream/nats/test.py
async def nak(self, delay: Union[int, float, None] = None) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.respond","title":"respond async","text":"
respond(data: bytes) -> None\n

respond replies to the inbox of the message if there is one.

Source code in nats/aio/msg.py
async def respond(self, data: bytes) -> None:\n    \"\"\"\n    respond replies to the inbox of the message if there is one.\n    \"\"\"\n    if not self.reply:\n        raise Error('no reply subject available')\n    if not self._client:\n        raise Error('client not set')\n\n    await self._client.publish(self.reply, data, headers=self.headers)\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.term","title":"term async","text":"
term() -> None\n
Source code in faststream/nats/test.py
async def term(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/","title":"TestNatsBroker","text":"","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker","title":"faststream.nats.test.TestNatsBroker","text":"
TestNatsBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[NatsBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/nats/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: NatsBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(publisher.subject, _raw=True)\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(broker: NatsBroker, publisher: Any) -> None\n
Source code in faststream/nats/test.py
@staticmethod\ndef patch_publisher(broker: NatsBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> None\n
Source code in faststream/nats/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> None:\n    broker.handlers.pop(Handler.get_routing_hash(publisher.subject), None)\n
","boost":0.5},{"location":"api/faststream/nats/test/build_message/","title":"build_message","text":"","boost":0.5},{"location":"api/faststream/nats/test/build_message/#faststream.nats.test.build_message","title":"faststream.nats.test.build_message","text":"
build_message(\n    message: SendableMessage,\n    subject: str,\n    *,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[AnyDict] = None\n) -> PatchedMessage\n
Source code in faststream/nats/test.py
def build_message(\n    message: SendableMessage,\n    subject: str,\n    *,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[AnyDict] = None,\n) -> \"PatchedMessage\":\n    msg, content_type = encode_message(message)\n    return PatchedMessage(\n        _client=None,  # type: ignore\n        subject=subject,\n        reply=reply_to,\n        data=msg,\n        headers={\n            \"content-type\": content_type or \"\",\n            \"correlation_id\": correlation_id or str(uuid4()),\n            **(headers or {}),\n        },\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/","title":"ExchangeType","text":"","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType","title":"faststream.rabbit.ExchangeType","text":"

Bases: str, Enum

A class to represent the exchange type.

","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.DIRECT","title":"DIRECT class-attribute instance-attribute","text":"
DIRECT = 'direct'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.FANOUT","title":"FANOUT class-attribute instance-attribute","text":"
FANOUT = 'fanout'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.HEADERS","title":"HEADERS class-attribute instance-attribute","text":"
HEADERS = 'headers'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.TOPIC","title":"TOPIC class-attribute instance-attribute","text":"
TOPIC = 'topic'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.X_CONSISTENT_HASH","title":"X_CONSISTENT_HASH class-attribute instance-attribute","text":"
X_CONSISTENT_HASH = 'x-consistent-hash'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.X_DELAYED_MESSAGE","title":"X_DELAYED_MESSAGE class-attribute instance-attribute","text":"
X_DELAYED_MESSAGE = 'x-delayed-message'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.X_MODULUS_HASH","title":"X_MODULUS_HASH class-attribute instance-attribute","text":"
X_MODULUS_HASH = 'x-modulus-hash'\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/","title":"RabbitBroker","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker","title":"faststream.rabbit.RabbitBroker","text":"
RabbitBroker(\n    url: Union[\n        str, URL, None\n    ] = \"amqp://guest:guest@localhost:5672/\",\n    *,\n    host: str = None,\n    port: int = None,\n    login: str = None,\n    password: str = None,\n    virtualhost: str = None,\n    ssl_options: Optional[aio_pika.abc.SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    max_consumers: Optional[int] = None,\n    protocol: str = None,\n    protocol_version: Optional[str] = \"0.9.1\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: RabbitLoggingMixin, BrokerAsyncUsecase[IncomingMessage, RobustConnection]

A RabbitMQ broker for FastAPI applications.

This class extends the base BrokerAsyncUsecase and provides asynchronous support for RabbitMQ as a message broker.

PARAMETER DESCRIPTION url

The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".

TYPE: Union[str, URL, None] DEFAULT: 'amqp://guest:guest@localhost:5672/'

max_consumers

Maximum number of consumers to limit message consumption. Defaults to None.

TYPE: Optional[int] DEFAULT: None

protocol

The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".

TYPE: str DEFAULT: None

protocol_version

The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".

TYPE: Optional[str] DEFAULT: '0.9.1'

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Initialize the RabbitBroker.

PARAMETER DESCRIPTION url

The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".

TYPE: Union[str, URL, None] DEFAULT: 'amqp://guest:guest@localhost:5672/'

max_consumers

Maximum number of consumers to limit message consumption. Defaults to None.

TYPE: Optional[int] DEFAULT: None

protocol

The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".

TYPE: str DEFAULT: None

protocol_version

The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".

TYPE: Optional[str] DEFAULT: '0.9.1'

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/rabbit/broker.py
def __init__(\n    self,\n    url: Union[str, URL, None] = \"amqp://guest:guest@localhost:5672/\",\n    *,\n    # connection args\n    host: Optional[str] = None,\n    port: Optional[int] = None,\n    login: Optional[str] = None,\n    password: Optional[str] = None,\n    virtualhost: Optional[str] = None,\n    ssl_options: Optional[SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    # broker args\n    max_consumers: Optional[int] = None,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"0.9.1\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Initialize the RabbitBroker.\n\n    Args:\n        url (Union[str, URL, None], optional): The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".\n        max_consumers (Optional[int], optional): Maximum number of consumers to limit message consumption. Defaults to None.\n        protocol (str, optional): The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".\n        protocol_version (Optional[str], optional): The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".\n        **kwargs: Additional keyword arguments.\n    \"\"\"\n    security_args = parse_security(security)\n\n    if (ssl := kwargs.get(\"ssl\")) or kwargs.get(\"ssl_context\"):  # pragma: no cover\n        warnings.warn(\n            (\n                f\"\\nRabbitMQ {'`ssl`' if ssl else '`ssl_context`'} option was deprecated and will be removed in 0.4.0\"\n                \"\\nPlease, use `security` with `BaseSecurity` or `SASLPlaintext` instead\"\n            ),\n            DeprecationWarning,\n            stacklevel=2,\n        )\n\n    amqp_url = build_url(\n        url,\n        host=host,\n        port=port,\n        login=security_args.get(\"login\", login),\n        password=security_args.get(\"password\", password),\n        virtualhost=virtualhost,\n        ssl=security_args.get(\"ssl\", kwargs.pop(\"ssl\", False)),\n        ssl_options=ssl_options,\n        client_properties=client_properties,\n    )\n\n    super().__init__(\n        url=str(amqp_url),\n        protocol_version=protocol_version,\n        security=security,\n        ssl_context=security_args.get(\n            \"ssl_context\",\n            kwargs.pop(\"ssl_context\", None),\n        ),\n        **kwargs,\n    )\n\n    # respect ascynapi_url argument scheme\n    asyncapi_url = build_url(self.url)\n    self.protocol = protocol or asyncapi_url.scheme\n    self.virtual_host = asyncapi_url.path\n\n    self._max_consumers = max_consumers\n\n    self._channel = None\n    self.declarer = None\n    self._producer = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.declarer","title":"declarer instance-attribute","text":"
declarer: Optional[RabbitDeclarer] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[int, Handler]\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol or asyncapi_url.scheme\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.virtual_host","title":"virtual_host instance-attribute","text":"
virtual_host = asyncapi_url.path\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.connect","title":"connect async","text":"
connect(\n    *args: Any, **kwargs: Any\n) -> aio_pika.RobustConnection\n

Connect to the RabbitMQ server.

PARAMETER DESCRIPTION *args

Additional positional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION RobustConnection

aio_pika.RobustConnection: The RabbitMQ connection instance.

Source code in faststream/rabbit/broker.py
async def connect(self, *args: Any, **kwargs: Any) -> aio_pika.RobustConnection:\n    \"\"\"\n    Connect to the RabbitMQ server.\n\n    Args:\n        *args: Additional positional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        aio_pika.RobustConnection: The RabbitMQ connection instance.\n    \"\"\"\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.declare_exchange","title":"declare_exchange async","text":"
declare_exchange(\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange\n

Declare a RabbitMQ exchange.

PARAMETER DESCRIPTION exchange

The RabbitMQ exchange to declare.

TYPE: RabbitExchange

RETURNS DESCRIPTION RobustExchange

aio_pika.RobustExchange: The declared RabbitMQ exchange.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def declare_exchange(\n    self,\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange:\n    \"\"\"\n    Declare a RabbitMQ exchange.\n\n    Args:\n        exchange (RabbitExchange): The RabbitMQ exchange to declare.\n\n    Returns:\n        aio_pika.RobustExchange: The declared RabbitMQ exchange.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n    return await self.declarer.declare_exchange(exchange)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.declare_queue","title":"declare_queue async","text":"
declare_queue(queue: RabbitQueue) -> aio_pika.RobustQueue\n

Declare a RabbitMQ queue.

PARAMETER DESCRIPTION queue

The RabbitMQ queue to declare.

TYPE: RabbitQueue

RETURNS DESCRIPTION RobustQueue

aio_pika.RobustQueue: The declared RabbitMQ queue.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def declare_queue(\n    self,\n    queue: RabbitQueue,\n) -> aio_pika.RobustQueue:\n    \"\"\"\n    Declare a RabbitMQ queue.\n\n    Args:\n        queue (RabbitQueue): The RabbitMQ queue to declare.\n\n    Returns:\n        aio_pika.RobustQueue: The declared RabbitMQ queue.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n    return await self.declarer.declare_queue(queue)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, **kwargs: Any\n) -> Union[\n    aiormq.abc.ConfirmationFrameType, SendableMessage\n]\n

Publish a message to the RabbitMQ broker.

PARAMETER DESCRIPTION *args

Additional positional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Union[ConfirmationFrameType, SendableMessage]

Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The confirmation frame or the response message.

Source code in faststream/rabbit/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Union[aiormq.abc.ConfirmationFrameType, SendableMessage]:\n    \"\"\"\n    Publish a message to the RabbitMQ broker.\n\n    Args:\n        *args: Additional positional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The confirmation frame or the response message.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.publisher","title":"publisher","text":"
publisher(\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Publisher\n

Define a message publisher.

PARAMETER DESCRIPTION queue

The name of the RabbitMQ queue. Defaults to \"\".

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The name of the RabbitMQ exchange. Defaults to None.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key for messages. Defaults to \"\".

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory. Defaults to True.

TYPE: bool DEFAULT: True

immediate

Whether the message should be sent immediately. Defaults to False.

TYPE: bool DEFAULT: False

timeout

Timeout for message publishing. Defaults to None.

TYPE: TimeoutType DEFAULT: None

persist

Whether to persist messages. Defaults to False.

TYPE: bool DEFAULT: False

reply_to

The reply-to queue name. Defaults to None.

TYPE: Optional[str] DEFAULT: None

title

Title for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

description

Description for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional message properties and content.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Publisher

A message publisher instance.

TYPE: Publisher

Source code in faststream/rabbit/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Publisher:\n    \"\"\"\n    Define a message publisher.\n\n    Args:\n        queue (Union[RabbitQueue, str], optional): The name of the RabbitMQ queue. Defaults to \"\".\n        exchange (Union[RabbitExchange, str, None], optional): The name of the RabbitMQ exchange. Defaults to None.\n        routing_key (str, optional): The routing key for messages. Defaults to \"\".\n        mandatory (bool, optional): Whether the message is mandatory. Defaults to True.\n        immediate (bool, optional): Whether the message should be sent immediately. Defaults to False.\n        timeout (TimeoutType, optional): Timeout for message publishing. Defaults to None.\n        persist (bool, optional): Whether to persist messages. Defaults to False.\n        reply_to (Optional[str], optional): The reply-to queue name. Defaults to None.\n        title (Optional[str]): Title for AsyncAPI docs.\n        description (Optional[str]): Description for AsyncAPI docs.\n        **message_kwargs (Any): Additional message properties and content.\n\n    Returns:\n        Publisher: A message publisher instance.\n    \"\"\"\n    q, ex = RabbitQueue.validate(queue), RabbitExchange.validate(exchange)\n\n    publisher = Publisher(\n        title=title,\n        queue=q,\n        exchange=ex,\n        routing_key=routing_key,\n        mandatory=mandatory,\n        immediate=immediate,\n        timeout=timeout,\n        persist=persist,\n        reply_to=reply_to,\n        priority=priority,\n        message_kwargs=message_kwargs,\n        _description=description,\n        _schema=schema,\n        virtual_host=self.virtual_host,\n        include_in_schema=include_in_schema,\n    )\n\n    key = publisher._get_routing_hash()\n    publisher = self._publishers.get(key, publisher)\n    super().publisher(key, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.start","title":"start async","text":"
start() -> None\n

Start the RabbitMQ broker.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def start(self) -> None:\n    \"\"\"\n    Start the RabbitMQ broker.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, RabbitQueue(\"\"), RabbitExchange(\"\")),\n    )\n\n    await super().start()\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n\n    for publisher in self._publishers.values():\n        if publisher.exchange is not None:\n            await self.declare_exchange(publisher.exchange)\n\n    for handler in self.handlers.values():\n        c = self._get_log_context(None, handler.queue, handler.exchange)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self.declarer)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Filter[RabbitMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n

Decorator to define a message subscriber.

PARAMETER DESCRIPTION queue

The name of the RabbitMQ queue.

TYPE: Union[str, RabbitQueue]

exchange

The name of the RabbitMQ exchange. Defaults to None.

TYPE: Union[str, RabbitExchange, None] DEFAULT: None

consume_args

Additional arguments for message consumption.

TYPE: Optional[AnyDict] DEFAULT: None

no_ack

Whether not to ack/nack/reject messages.

TYPE: bool DEFAULT: False

title

Title for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

description

Description for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION Callable

A decorator function for defining message subscribers.

TYPE: Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn]]

Source code in faststream/rabbit/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[aio_pika.IncomingMessage, RabbitMessage]] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[aio_pika.IncomingMessage], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RabbitMessage] = default_filter,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"\n    Decorator to define a message subscriber.\n\n    Args:\n        queue (Union[str, RabbitQueue]): The name of the RabbitMQ queue.\n        exchange (Union[str, RabbitExchange, None], optional): The name of the RabbitMQ exchange. Defaults to None.\n        consume_args (Optional[AnyDict], optional): Additional arguments for message consumption.\n        no_ack (bool): Whether not to ack/nack/reject messages.\n        title (Optional[str]): Title for AsyncAPI docs.\n        description (Optional[str]): Description for AsyncAPI docs.\n\n    Returns:\n        Callable: A decorator function for defining message subscribers.\n    \"\"\"\n    super().subscriber()\n\n    r_queue = RabbitQueue.validate(queue)\n    r_exchange = RabbitExchange.validate(exchange)\n\n    self._setup_log_context(r_queue, r_exchange)\n\n    key = get_routing_hash(r_queue, r_exchange)\n    handler = self.handlers.get(\n        key,\n        Handler(\n            log_context_builder=partial(\n                self._get_log_context, queue=r_queue, exchange=r_exchange\n            ),\n            queue=r_queue,\n            exchange=r_exchange,\n            consume_args=consume_args,\n            description=description,\n            title=title,\n            virtual_host=self.virtual_host,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n        ),\n    )\n\n    self.handlers[key] = handler\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[\n        aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn\n    ]:\n        \"\"\"Wraps a consumer function with additional functionality.\n\n        Args:\n            func: The consumer function to be wrapped.\n\n        Returns:\n            The wrapped consumer function.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            _process_kwargs={\n                \"reply_config\": reply_config,\n            },\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/","title":"RabbitExchange","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange","title":"faststream.rabbit.RabbitExchange","text":"
RabbitExchange(\n    name: str,\n    type: ExchangeType = ExchangeType.DIRECT,\n    durable: bool = False,\n    auto_delete: bool = False,\n    internal: bool = False,\n    passive: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_to: Optional[RabbitExchange] = None,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n)\n

Bases: NameRequired

A class to represent a RabbitMQ exchange.

METHOD DESCRIPTION __hash__

returns the hash value of the exchange

__init__

initializes the RabbitExchange object

Initialize a RabbitExchange object.

PARAMETER DESCRIPTION name

Name of the exchange.

TYPE: str

type

Type of the exchange. Defaults to ExchangeType.DIRECT.

TYPE: ExchangeType DEFAULT: DIRECT

durable

Whether the exchange should survive broker restarts. Defaults to False.

TYPE: bool DEFAULT: False

auto_delete

Whether the exchange should be deleted when no longer in use. Defaults to False.

TYPE: bool DEFAULT: False

internal

Whether the exchange is used for internal purposes and should not be published to directly. Defaults to False.

TYPE: bool DEFAULT: False

passive

Whether to check if the exchange exists before creating it. Defaults to False.

TYPE: bool DEFAULT: False

arguments

Additional arguments for the exchange. Defaults to None.

TYPE: Optional[AnyDict] DEFAULT: None

timeout

Timeout for the operation. Defaults to None.

TYPE: TimeoutType DEFAULT: None

robust

Whether to use robust mode for the exchange. Defaults to True.

TYPE: bool DEFAULT: True

bind_to

Exchange to bind to. Defaults to None.

TYPE: Optional[RabbitExchange] DEFAULT: None

bind_arguments

Arguments for the binding. Defaults to None.

TYPE: Optional[AnyDict] DEFAULT: None

routing_key

Routing key for the exchange. Defaults to \"\".

TYPE: str DEFAULT: ''

RAISES DESCRIPTION NotImplementedError Source code in faststream/rabbit/shared/schemas.py
def __init__(\n    self,\n    name: str,\n    type: ExchangeType = ExchangeType.DIRECT,\n    durable: bool = False,\n    auto_delete: bool = False,\n    internal: bool = False,\n    passive: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_to: Optional[\"RabbitExchange\"] = None,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n) -> None:\n    \"\"\"Initialize a RabbitExchange object.\n\n    Args:\n        name (str): Name of the exchange.\n        type (ExchangeType, optional): Type of the exchange. Defaults to ExchangeType.DIRECT.\n        durable (bool, optional): Whether the exchange should survive broker restarts. Defaults to False.\n        auto_delete (bool, optional): Whether the exchange should be deleted when no longer in use. Defaults to False.\n        internal (bool, optional): Whether the exchange is used for internal purposes and should not be published to directly. Defaults to False.\n        passive (bool, optional): Whether to check if the exchange exists before creating it. Defaults to False.\n        arguments (Optional[AnyDict], optional): Additional arguments for the exchange. Defaults to None.\n        timeout (TimeoutType, optional): Timeout for the operation. Defaults to None.\n        robust (bool, optional): Whether to use robust mode for the exchange. Defaults to True.\n        bind_to (Optional[\"RabbitExchange\"], optional): Exchange to bind to. Defaults to None.\n        bind_arguments (Optional[AnyDict], optional): Arguments for the binding. Defaults to None.\n        routing_key (str, optional): Routing key for the exchange. Defaults to \"\".\n\n    Raises:\n        NotImplementedError:\n\n    \"\"\"\n    if routing_key and bind_to is None:  # pragma: no cover\n        warnings.warn(\n            (\n                \"\\nRabbitExchange `routing_key` is using to bind exchange to another one\"\n                \"\\nIt can be used only with the `bind_to` argument, please setup it too\"\n            ),\n            category=RuntimeWarning,\n            stacklevel=1,\n        )\n\n    super().__init__(\n        name=name,\n        type=type.value,\n        durable=durable,\n        auto_delete=auto_delete,\n        routing_key=routing_key,\n        bind_to=bind_to,\n        bind_arguments=bind_arguments,\n        robust=robust,\n        internal=internal,\n        passive=passive,\n        timeout=timeout,\n        arguments=arguments,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.arguments","title":"arguments class-attribute instance-attribute","text":"
arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.auto_delete","title":"auto_delete class-attribute instance-attribute","text":"
auto_delete: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.bind_arguments","title":"bind_arguments class-attribute instance-attribute","text":"
bind_arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.bind_to","title":"bind_to class-attribute instance-attribute","text":"
bind_to: Optional[RabbitExchange] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.durable","title":"durable class-attribute instance-attribute","text":"
durable: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.internal","title":"internal class-attribute instance-attribute","text":"
internal: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.passive","title":"passive class-attribute instance-attribute","text":"
passive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.robust","title":"robust class-attribute instance-attribute","text":"
robust: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.type","title":"type class-attribute instance-attribute","text":"
type: str = ExchangeType.DIRECT.value\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/","title":"RabbitQueue","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue","title":"faststream.rabbit.RabbitQueue","text":"
RabbitQueue(\n    name: str,\n    durable: bool = False,\n    exclusive: bool = False,\n    passive: bool = False,\n    auto_delete: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n)\n

Bases: NameRequired

A class to represent a RabbitMQ queue.

METHOD DESCRIPTION __hash__

returns the hash value of the queue

routing

returns the routing key of the queue

__init__

initializes the RabbitQueue object with the given parameters

Initialize a class object.

PARAMETER DESCRIPTION name

The name of the object.

TYPE: str

durable

Whether the object is durable. Defaults to False.

TYPE: bool DEFAULT: False

exclusive

Whether the object is exclusive. Defaults to False.

TYPE: bool DEFAULT: False

passive

Whether the object is passive. Defaults to False.

TYPE: bool DEFAULT: False

auto_delete

Whether the object is auto delete. Defaults to False.

TYPE: bool DEFAULT: False

arguments

Additional arguments for the object. Defaults to None.

TYPE: dict DEFAULT: None

timeout

Timeout for the object. Defaults to None.

TYPE: TimeoutType DEFAULT: None

robust

Whether the object is robust. Defaults to True.

TYPE: bool DEFAULT: True

bind_arguments

Bind arguments for the object. Defaults to None.

TYPE: dict DEFAULT: None

routing_key

Routing key for the object. Defaults to \"\".

TYPE: str DEFAULT: ''

Source code in faststream/rabbit/shared/schemas.py
def __init__(\n    self,\n    name: str,\n    durable: bool = False,\n    exclusive: bool = False,\n    passive: bool = False,\n    auto_delete: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n) -> None:\n    \"\"\"Initialize a class object.\n\n    Args:\n        name (str): The name of the object.\n        durable (bool, optional): Whether the object is durable. Defaults to False.\n        exclusive (bool, optional): Whether the object is exclusive. Defaults to False.\n        passive (bool, optional): Whether the object is passive. Defaults to False.\n        auto_delete (bool, optional): Whether the object is auto delete. Defaults to False.\n        arguments (dict, optional): Additional arguments for the object. Defaults to None.\n        timeout (TimeoutType, optional): Timeout for the object. Defaults to None.\n        robust (bool, optional): Whether the object is robust. Defaults to True.\n        bind_arguments (dict, optional): Bind arguments for the object. Defaults to None.\n        routing_key (str, optional): Routing key for the object. Defaults to \"\".\n\n    \"\"\"\n    re, routing_key = compile_path(routing_key, replace_symbol=\"*\")\n    super().__init__(\n        name=name,\n        path_regex=re,\n        durable=durable,\n        exclusive=exclusive,\n        bind_arguments=bind_arguments,\n        routing_key=routing_key,\n        robust=robust,\n        passive=passive,\n        auto_delete=auto_delete,\n        arguments=arguments,\n        timeout=timeout,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.arguments","title":"arguments class-attribute instance-attribute","text":"
arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.auto_delete","title":"auto_delete class-attribute instance-attribute","text":"
auto_delete: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.bind_arguments","title":"bind_arguments class-attribute instance-attribute","text":"
bind_arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.durable","title":"durable class-attribute instance-attribute","text":"
durable: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.exclusive","title":"exclusive class-attribute instance-attribute","text":"
exclusive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'arbitrary_types_allowed': True}\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.name","title":"name class-attribute instance-attribute","text":"
name: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.passive","title":"passive class-attribute instance-attribute","text":"
passive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.path_regex","title":"path_regex class-attribute instance-attribute","text":"
path_regex: Optional[Pattern[str]] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.robust","title":"robust class-attribute instance-attribute","text":"
robust: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.routing","title":"routing property","text":"
routing: str\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.Config.arbitrary_types_allowed","title":"arbitrary_types_allowed class-attribute instance-attribute","text":"
arbitrary_types_allowed = True\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRoute/","title":"RabbitRoute","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/","title":"RabbitRouter","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter","title":"faststream.rabbit.RabbitRouter","text":"
RabbitRouter(\n    prefix: str = \"\",\n    handlers: Sequence[RabbitRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: RabbitRouter

A class representing a RabbitMQ router for publishing messages.

METHOD DESCRIPTION _get_publisher_key

Returns the key for a given Publisher object

_update_publisher_prefix

Updates the prefix of a given Publisher object

publisher

Publishes a message to RabbitMQ

Source code in faststream/rabbit/router.py
_publishers: Dict[int, Publisher]\n\n@staticmethod\ndef _get_publisher_key(publisher: Publisher) -> int:\n    \"\"\"Get the publisher key.\n\n    Args:\n        publisher: The publisher object.\n\n    Returns:\n        The publisher key as an integer.\n\n    \"\"\"\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.publisher","title":"publisher","text":"
publisher(\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Publisher\n

Publishes a message to a RabbitMQ queue or exchange.

PARAMETER DESCRIPTION queue

The RabbitMQ queue to publish the message to. Can be either a RabbitQueue object or a string representing the queue name.

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The RabbitMQ exchange to publish the message to. Can be either a RabbitExchange object, a string representing the exchange name, or None.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key to use when publishing the message.

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory or not.

TYPE: bool DEFAULT: True

immediate

Whether the message should be delivered immediately or not.

TYPE: bool DEFAULT: False

timeout

The timeout for the publish operation.

TYPE: TimeoutType DEFAULT: None

persist

Whether the message should be persisted or not.

TYPE: bool DEFAULT: False

reply_to

The reply-to address for the message.

TYPE: Optional[str] DEFAULT: None

title

The title of the message (AsyncAPI information).

TYPE: Optional[str] DEFAULT: None

description

The description of the message (AsyncAPI information).

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional keyword arguments to include in the message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Publisher

The Publisher object used to publish the message.

Source code in faststream/rabbit/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Publisher:\n    \"\"\"Publishes a message to a RabbitMQ queue or exchange.\n\n    Args:\n        queue: The RabbitMQ queue to publish the message to. Can be either a RabbitQueue object or a string representing the queue name.\n        exchange: The RabbitMQ exchange to publish the message to. Can be either a RabbitExchange object, a string representing the exchange name, or None.\n        routing_key: The routing key to use when publishing the message.\n        mandatory: Whether the message is mandatory or not.\n        immediate: Whether the message should be delivered immediately or not.\n        timeout: The timeout for the publish operation.\n        persist: Whether the message should be persisted or not.\n        reply_to: The reply-to address for the message.\n        title: The title of the message (AsyncAPI information).\n        description: The description of the message (AsyncAPI information).\n        **message_kwargs: Additional keyword arguments to include in the message.\n\n    Returns:\n        The Publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            queue=RabbitQueue.validate(queue),\n            exchange=RabbitExchange.validate(exchange),\n            routing_key=routing_key,\n            mandatory=mandatory,\n            immediate=immediate,\n            timeout=timeout,\n            persist=persist,\n            reply_to=reply_to,\n            priority=priority,\n            message_kwargs=message_kwargs,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[key] = self._publishers.get(key, new_publisher)\n    return publisher\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    dependencies: Sequence[Depends] = (),\n    filter: Filter[RabbitMessage] = default_filter,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    retry: Union[bool, int] = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n
Source code in faststream/rabbit/router.py
    Returns:\n        Publisher: The updated publisher object.\n\n    Note:\n        This function is intended to be used as a decorator.\n\n    \"\"\"\n    publisher.queue = model_copy(\n        publisher.queue, update={\"name\": prefix + publisher.queue.name}\n    )\n    return publisher\n\n@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n
","boost":0.5},{"location":"api/faststream/rabbit/ReplyConfig/","title":"ReplyConfig","text":"","boost":0.5},{"location":"api/faststream/rabbit/ReplyConfig/#faststream.rabbit.ReplyConfig","title":"faststream.rabbit.ReplyConfig","text":"

Bases: BaseModel

","boost":0.5},{"location":"api/faststream/rabbit/ReplyConfig/#faststream.rabbit.ReplyConfig.immediate","title":"immediate class-attribute instance-attribute","text":"
immediate: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/ReplyConfig/#faststream.rabbit.ReplyConfig.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/ReplyConfig/#faststream.rabbit.ReplyConfig.persist","title":"persist class-attribute instance-attribute","text":"
persist: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/rabbit/TestApp/#faststream.broker.test.TestApp","title":"faststream.broker.test.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/rabbit/TestApp/#faststream.broker.test.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/","title":"TestRabbitBroker","text":"","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker","title":"faststream.rabbit.TestRabbitBroker","text":"
TestRabbitBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[RabbitBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: RabbitBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: RabbitBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(\n        queue=publisher.queue,\n        exchange=publisher.exchange,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: RabbitBroker, publisher: Any\n) -> None\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef patch_publisher(broker: RabbitBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: RabbitBroker, publisher: Publisher\n) -> None\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: RabbitBroker,\n    publisher: Publisher,\n) -> None:\n    broker.handlers.pop(\n        publisher._get_routing_hash(),\n        None,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/","title":"Handler","text":"","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler","title":"faststream.rabbit.asyncapi.Handler","text":"
Handler(\n    queue: RabbitQueue,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    exchange: Optional[RabbitExchange] = None,\n    consume_args: Optional[AnyDict] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    virtual_host: str = \"/\",\n)\n

Bases: LogicHandler

A class that serves as a handler for RMQAsyncAPIChannel and LogicHandler.

METHOD DESCRIPTION - name

Returns the name of the handler.

- get_payloads

Returns a list of payloads.

Initialize a RabbitMQ consumer.

PARAMETER DESCRIPTION queue

RabbitQueue object representing the queue to consume from

TYPE: RabbitQueue

exchange

RabbitExchange object representing the exchange to bind the queue to (optional)

TYPE: Optional[RabbitExchange] DEFAULT: None

consume_args

Additional arguments for consuming from the queue (optional)

TYPE: Optional[AnyDict] DEFAULT: None

description

Description of the consumer (optional)

TYPE: Optional[str] DEFAULT: None

title

Title of the consumer (optional)

TYPE: Optional[str] DEFAULT: None

Source code in faststream/rabbit/handler.py
def __init__(\n    self,\n    queue: RabbitQueue,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # RMQ information\n    exchange: Optional[RabbitExchange] = None,\n    consume_args: Optional[AnyDict] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    virtual_host: str = \"/\",\n) -> None:\n    \"\"\"Initialize a RabbitMQ consumer.\n\n    Args:\n        queue: RabbitQueue object representing the queue to consume from\n        exchange: RabbitExchange object representing the exchange to bind the queue to (optional)\n        consume_args: Additional arguments for consuming from the queue (optional)\n        description: Description of the consumer (optional)\n        title: Title of the consumer (optional)\n\n    \"\"\"\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.queue = queue\n    self.exchange = exchange\n    self.virtual_host = virtual_host\n    self.consume_args = consume_args or {}\n\n    self._consumer_tag = None\n    self._queue_obj = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.consume_args","title":"consume_args instance-attribute","text":"
consume_args: AnyDict = consume_args or {}\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.exchange","title":"exchange instance-attribute","text":"
exchange: Optional[RabbitExchange] = exchange\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.queue","title":"queue instance-attribute","text":"
queue: RabbitQueue = queue\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.virtual_host","title":"virtual_host instance-attribute","text":"
virtual_host = virtual_host\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ],\n    decoder: Optional[CustomDecoder[RabbitMessage]],\n    filter: Filter[RabbitMessage],\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ]\n) -> None\n

Add a call to the handler.

PARAMETER DESCRIPTION handler

The handler for the call.

TYPE: HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn]

dependant

The dependant for the call.

TYPE: CallModel[P_HandlerParams, T_HandlerReturn]

parser

Optional custom parser for the call.

TYPE: Optional[CustomParser[IncomingMessage, RabbitMessage]]

decoder

Optional custom decoder for the call.

TYPE: Optional[CustomDecoder[RabbitMessage]]

filter

The filter for the call.

TYPE: Filter[RabbitMessage]

middlewares

Optional sequence of middlewares for the call.

TYPE: Optional[Sequence[Callable[[IncomingMessage], BaseMiddleware]]]

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[\n        aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[aio_pika.IncomingMessage, RabbitMessage]],\n    decoder: Optional[CustomDecoder[RabbitMessage]],\n    filter: Filter[RabbitMessage],\n    middlewares: Optional[\n        Sequence[Callable[[aio_pika.IncomingMessage], BaseMiddleware]]\n    ],\n) -> None:\n    \"\"\"Add a call to the handler.\n\n    Args:\n        handler: The handler for the call.\n        dependant: The dependant for the call.\n        parser: Optional custom parser for the call.\n        decoder: Optional custom decoder for the call.\n        filter: The filter for the call.\n        middlewares: Optional sequence of middlewares for the call.\n\n    Returns:\n        None\n\n    \"\"\"\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, AioPikaParser.parse_message),\n        decoder=resolve_custom_func(decoder, AioPikaParser.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/rabbit/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self._queue_obj is not None:\n        if self._consumer_tag is not None:  # pragma: no branch\n            await self._queue_obj.cancel(self._consumer_tag)\n            self._consumer_tag = None\n        self._queue_obj = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/rabbit/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    handler_name = (\n        self._title\n        or f\"{self.queue.name}:{getattr(self.exchange, 'name', '_')}:{self.call_name}\"\n    )\n\n    return {\n        handler_name: Channel(\n            description=self.description,  # type: ignore[attr-defined]\n            subscribe=Operation(\n                bindings=OperationBinding(\n                    amqp=amqp.OperationBinding(\n                        cc=self.queue.routing,\n                    ),\n                )\n                if _is_exchange(self.exchange)\n                else None,\n                message=Message(\n                    title=f\"{handler_name}:Message\",\n                    payload=resolve_payloads(payloads),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                amqp=amqp.ChannelBinding(\n                    **{\n                        \"is\": \"routingKey\",  # type: ignore\n                        \"queue\": amqp.Queue(\n                            name=self.queue.name,\n                            durable=self.queue.durable,\n                            exclusive=self.queue.exclusive,\n                            autoDelete=self.queue.auto_delete,\n                            vhost=self.virtual_host,\n                        )\n                        if _is_exchange(self.exchange)\n                        else None,\n                        \"exchange\": (\n                            amqp.Exchange(type=\"default\", vhost=self.virtual_host)\n                            if self.exchange is None\n                            else amqp.Exchange(\n                                type=self.exchange.type,  # type: ignore\n                                name=self.exchange.name,\n                                durable=self.exchange.durable,\n                                autoDelete=self.exchange.auto_delete,\n                                vhost=self.virtual_host,\n                            )\n                        ),\n                    }\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.start","title":"start async","text":"
start(declarer: RabbitDeclarer) -> None\n

Starts the consumer for the RabbitMQ queue.

PARAMETER DESCRIPTION declarer

RabbitDeclarer object used to declare the queue and exchange

TYPE: RabbitDeclarer

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/handler.py
@override\nasync def start(self, declarer: RabbitDeclarer) -> None:  # type: ignore[override]\n    \"\"\"Starts the consumer for the RabbitMQ queue.\n\n    Args:\n        declarer: RabbitDeclarer object used to declare the queue and exchange\n\n    Returns:\n        None\n\n    \"\"\"\n    self._queue_obj = queue = await declarer.declare_queue(self.queue)\n\n    if self.exchange is not None:\n        exchange = await declarer.declare_exchange(self.exchange)\n        await queue.bind(\n            exchange,\n            routing_key=self.queue.routing,\n            arguments=self.queue.bind_arguments,\n        )\n\n    self._consumer_tag = await queue.consume(\n        # NOTE: aio-pika expects AbstractIncomingMessage, not IncomingMessage\n        self.consume,  # type: ignore[arg-type]\n        arguments=self.consume_args,\n    )\n\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/","title":"Publisher","text":"","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher","title":"faststream.rabbit.asyncapi.Publisher","text":"

Bases: LogicPublisher

A class representing a publisher.

METHOD DESCRIPTION get_payloads

Get the payloads for the publisher

","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.exchange","title":"exchange class-attribute instance-attribute","text":"
exchange: Optional[RabbitExchange] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.immediate","title":"immediate class-attribute instance-attribute","text":"
immediate: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.message_kwargs","title":"message_kwargs class-attribute instance-attribute","text":"
message_kwargs: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.name","title":"name property","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.persist","title":"persist class-attribute instance-attribute","text":"
persist: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.priority","title":"priority class-attribute instance-attribute","text":"
priority: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.queue","title":"queue class-attribute instance-attribute","text":"
queue: RabbitQueue = field(default=RabbitQueue(''))\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.routing","title":"routing property","text":"
routing: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.virtual_host","title":"virtual_host class-attribute instance-attribute","text":"
virtual_host: str = '/'\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.publish","title":"publish async","text":"
publish(\n    message: AioPikaSendableMessage = \"\",\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    correlation_id: Optional[str] = None,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Union[\n    aiormq.abc.ConfirmationFrameType, SendableMessage\n]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: AioPikaSendableMessage DEFAULT: ''

rpc

Whether the message is for RPC (Remote Procedure Call).

TYPE: bool DEFAULT: False

rpc_timeout

Timeout for RPC.

TYPE: Optional[float] DEFAULT: 30.0

raise_timeout

Whether to raise an exception if timeout occurs.

TYPE: bool DEFAULT: False

correlation_id

Correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional keyword arguments for the message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Union[ConfirmationFrameType, SendableMessage]

ConfirmationFrameType or SendableMessage: The result of the publish operation.

RAISES DESCRIPTION AssertionError

If _producer is not set up.

Source code in faststream/rabbit/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: AioPikaSendableMessage = \"\",\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    correlation_id: Optional[str] = None,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Union[aiormq.abc.ConfirmationFrameType, SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        rpc: Whether the message is for RPC (Remote Procedure Call).\n        rpc_timeout: Timeout for RPC.\n        raise_timeout: Whether to raise an exception if timeout occurs.\n        correlation_id: Correlation ID for the message.\n        **message_kwargs: Additional keyword arguments for the message.\n\n    Returns:\n        ConfirmationFrameType or SendableMessage: The result of the publish operation.\n\n    Raises:\n        AssertionError: If `_producer` is not set up.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(\n        message=message,\n        exchange=self.exchange,\n        routing_key=self.routing,\n        mandatory=self.mandatory,\n        immediate=self.immediate,\n        timeout=self.timeout,\n        rpc=rpc,\n        rpc_timeout=rpc_timeout,\n        raise_timeout=raise_timeout,\n        persist=self.persist,\n        reply_to=self.reply_to,\n        correlation_id=correlation_id,\n        priority=priority or self.priority,\n        **self.message_kwargs,\n        **message_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/rabbit/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    return {\n        self.name: Channel(\n            description=self.description,  # type: ignore[attr-defined]\n            publish=Operation(\n                bindings=OperationBinding(\n                    amqp=amqp.OperationBinding(\n                        cc=self.routing or None,\n                        deliveryMode=2 if self.persist else 1,\n                        mandatory=self.mandatory,\n                        replyTo=self.reply_to,\n                        priority=self.priority,\n                    ),\n                )\n                if _is_exchange(self.exchange)\n                else None,\n                message=Message(\n                    title=f\"{self.name}:Message\",\n                    payload=resolve_payloads(\n                        payloads,\n                        \"Publisher\",\n                        served_words=2 if self.title is None else 1,\n                    ),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                amqp=amqp.ChannelBinding(\n                    **{\n                        \"is\": \"routingKey\",  # type: ignore\n                        \"queue\": amqp.Queue(\n                            name=self.queue.name,\n                            durable=self.queue.durable,\n                            exclusive=self.queue.exclusive,\n                            autoDelete=self.queue.auto_delete,\n                            vhost=self.virtual_host,\n                        )\n                        if _is_exchange(self.exchange) and self.queue.name\n                        else None,\n                        \"exchange\": (\n                            amqp.Exchange(type=\"default\", vhost=self.virtual_host)\n                            if self.exchange is None\n                            else amqp.Exchange(\n                                type=self.exchange.type,  # type: ignore\n                                name=self.exchange.name,\n                                durable=self.exchange.durable,\n                                autoDelete=self.exchange.auto_delete,\n                                vhost=self.virtual_host,\n                            )\n                        ),\n                    }\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/","title":"RabbitBroker","text":"","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker","title":"faststream.rabbit.broker.RabbitBroker","text":"
RabbitBroker(\n    url: Union[\n        str, URL, None\n    ] = \"amqp://guest:guest@localhost:5672/\",\n    *,\n    host: str = None,\n    port: int = None,\n    login: str = None,\n    password: str = None,\n    virtualhost: str = None,\n    ssl_options: Optional[aio_pika.abc.SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    max_consumers: Optional[int] = None,\n    protocol: str = None,\n    protocol_version: Optional[str] = \"0.9.1\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: RabbitLoggingMixin, BrokerAsyncUsecase[IncomingMessage, RobustConnection]

A RabbitMQ broker for FastAPI applications.

This class extends the base BrokerAsyncUsecase and provides asynchronous support for RabbitMQ as a message broker.

PARAMETER DESCRIPTION url

The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".

TYPE: Union[str, URL, None] DEFAULT: 'amqp://guest:guest@localhost:5672/'

max_consumers

Maximum number of consumers to limit message consumption. Defaults to None.

TYPE: Optional[int] DEFAULT: None

protocol

The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".

TYPE: str DEFAULT: None

protocol_version

The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".

TYPE: Optional[str] DEFAULT: '0.9.1'

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Initialize the RabbitBroker.

PARAMETER DESCRIPTION url

The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".

TYPE: Union[str, URL, None] DEFAULT: 'amqp://guest:guest@localhost:5672/'

max_consumers

Maximum number of consumers to limit message consumption. Defaults to None.

TYPE: Optional[int] DEFAULT: None

protocol

The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".

TYPE: str DEFAULT: None

protocol_version

The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".

TYPE: Optional[str] DEFAULT: '0.9.1'

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/rabbit/broker.py
def __init__(\n    self,\n    url: Union[str, URL, None] = \"amqp://guest:guest@localhost:5672/\",\n    *,\n    # connection args\n    host: Optional[str] = None,\n    port: Optional[int] = None,\n    login: Optional[str] = None,\n    password: Optional[str] = None,\n    virtualhost: Optional[str] = None,\n    ssl_options: Optional[SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    # broker args\n    max_consumers: Optional[int] = None,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"0.9.1\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Initialize the RabbitBroker.\n\n    Args:\n        url (Union[str, URL, None], optional): The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".\n        max_consumers (Optional[int], optional): Maximum number of consumers to limit message consumption. Defaults to None.\n        protocol (str, optional): The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".\n        protocol_version (Optional[str], optional): The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".\n        **kwargs: Additional keyword arguments.\n    \"\"\"\n    security_args = parse_security(security)\n\n    if (ssl := kwargs.get(\"ssl\")) or kwargs.get(\"ssl_context\"):  # pragma: no cover\n        warnings.warn(\n            (\n                f\"\\nRabbitMQ {'`ssl`' if ssl else '`ssl_context`'} option was deprecated and will be removed in 0.4.0\"\n                \"\\nPlease, use `security` with `BaseSecurity` or `SASLPlaintext` instead\"\n            ),\n            DeprecationWarning,\n            stacklevel=2,\n        )\n\n    amqp_url = build_url(\n        url,\n        host=host,\n        port=port,\n        login=security_args.get(\"login\", login),\n        password=security_args.get(\"password\", password),\n        virtualhost=virtualhost,\n        ssl=security_args.get(\"ssl\", kwargs.pop(\"ssl\", False)),\n        ssl_options=ssl_options,\n        client_properties=client_properties,\n    )\n\n    super().__init__(\n        url=str(amqp_url),\n        protocol_version=protocol_version,\n        security=security,\n        ssl_context=security_args.get(\n            \"ssl_context\",\n            kwargs.pop(\"ssl_context\", None),\n        ),\n        **kwargs,\n    )\n\n    # respect ascynapi_url argument scheme\n    asyncapi_url = build_url(self.url)\n    self.protocol = protocol or asyncapi_url.scheme\n    self.virtual_host = asyncapi_url.path\n\n    self._max_consumers = max_consumers\n\n    self._channel = None\n    self.declarer = None\n    self._producer = None\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.declarer","title":"declarer instance-attribute","text":"
declarer: Optional[RabbitDeclarer] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[int, Handler]\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol or asyncapi_url.scheme\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.virtual_host","title":"virtual_host instance-attribute","text":"
virtual_host = asyncapi_url.path\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.connect","title":"connect async","text":"
connect(\n    *args: Any, **kwargs: Any\n) -> aio_pika.RobustConnection\n

Connect to the RabbitMQ server.

PARAMETER DESCRIPTION *args

Additional positional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION RobustConnection

aio_pika.RobustConnection: The RabbitMQ connection instance.

Source code in faststream/rabbit/broker.py
async def connect(self, *args: Any, **kwargs: Any) -> aio_pika.RobustConnection:\n    \"\"\"\n    Connect to the RabbitMQ server.\n\n    Args:\n        *args: Additional positional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        aio_pika.RobustConnection: The RabbitMQ connection instance.\n    \"\"\"\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.declare_exchange","title":"declare_exchange async","text":"
declare_exchange(\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange\n

Declare a RabbitMQ exchange.

PARAMETER DESCRIPTION exchange

The RabbitMQ exchange to declare.

TYPE: RabbitExchange

RETURNS DESCRIPTION RobustExchange

aio_pika.RobustExchange: The declared RabbitMQ exchange.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def declare_exchange(\n    self,\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange:\n    \"\"\"\n    Declare a RabbitMQ exchange.\n\n    Args:\n        exchange (RabbitExchange): The RabbitMQ exchange to declare.\n\n    Returns:\n        aio_pika.RobustExchange: The declared RabbitMQ exchange.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n    return await self.declarer.declare_exchange(exchange)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.declare_queue","title":"declare_queue async","text":"
declare_queue(queue: RabbitQueue) -> aio_pika.RobustQueue\n

Declare a RabbitMQ queue.

PARAMETER DESCRIPTION queue

The RabbitMQ queue to declare.

TYPE: RabbitQueue

RETURNS DESCRIPTION RobustQueue

aio_pika.RobustQueue: The declared RabbitMQ queue.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def declare_queue(\n    self,\n    queue: RabbitQueue,\n) -> aio_pika.RobustQueue:\n    \"\"\"\n    Declare a RabbitMQ queue.\n\n    Args:\n        queue (RabbitQueue): The RabbitMQ queue to declare.\n\n    Returns:\n        aio_pika.RobustQueue: The declared RabbitMQ queue.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n    return await self.declarer.declare_queue(queue)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, **kwargs: Any\n) -> Union[\n    aiormq.abc.ConfirmationFrameType, SendableMessage\n]\n

Publish a message to the RabbitMQ broker.

PARAMETER DESCRIPTION *args

Additional positional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Union[ConfirmationFrameType, SendableMessage]

Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The confirmation frame or the response message.

Source code in faststream/rabbit/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Union[aiormq.abc.ConfirmationFrameType, SendableMessage]:\n    \"\"\"\n    Publish a message to the RabbitMQ broker.\n\n    Args:\n        *args: Additional positional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The confirmation frame or the response message.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.publisher","title":"publisher","text":"
publisher(\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Publisher\n

Define a message publisher.

PARAMETER DESCRIPTION queue

The name of the RabbitMQ queue. Defaults to \"\".

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The name of the RabbitMQ exchange. Defaults to None.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key for messages. Defaults to \"\".

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory. Defaults to True.

TYPE: bool DEFAULT: True

immediate

Whether the message should be sent immediately. Defaults to False.

TYPE: bool DEFAULT: False

timeout

Timeout for message publishing. Defaults to None.

TYPE: TimeoutType DEFAULT: None

persist

Whether to persist messages. Defaults to False.

TYPE: bool DEFAULT: False

reply_to

The reply-to queue name. Defaults to None.

TYPE: Optional[str] DEFAULT: None

title

Title for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

description

Description for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional message properties and content.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Publisher

A message publisher instance.

TYPE: Publisher

Source code in faststream/rabbit/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Publisher:\n    \"\"\"\n    Define a message publisher.\n\n    Args:\n        queue (Union[RabbitQueue, str], optional): The name of the RabbitMQ queue. Defaults to \"\".\n        exchange (Union[RabbitExchange, str, None], optional): The name of the RabbitMQ exchange. Defaults to None.\n        routing_key (str, optional): The routing key for messages. Defaults to \"\".\n        mandatory (bool, optional): Whether the message is mandatory. Defaults to True.\n        immediate (bool, optional): Whether the message should be sent immediately. Defaults to False.\n        timeout (TimeoutType, optional): Timeout for message publishing. Defaults to None.\n        persist (bool, optional): Whether to persist messages. Defaults to False.\n        reply_to (Optional[str], optional): The reply-to queue name. Defaults to None.\n        title (Optional[str]): Title for AsyncAPI docs.\n        description (Optional[str]): Description for AsyncAPI docs.\n        **message_kwargs (Any): Additional message properties and content.\n\n    Returns:\n        Publisher: A message publisher instance.\n    \"\"\"\n    q, ex = RabbitQueue.validate(queue), RabbitExchange.validate(exchange)\n\n    publisher = Publisher(\n        title=title,\n        queue=q,\n        exchange=ex,\n        routing_key=routing_key,\n        mandatory=mandatory,\n        immediate=immediate,\n        timeout=timeout,\n        persist=persist,\n        reply_to=reply_to,\n        priority=priority,\n        message_kwargs=message_kwargs,\n        _description=description,\n        _schema=schema,\n        virtual_host=self.virtual_host,\n        include_in_schema=include_in_schema,\n    )\n\n    key = publisher._get_routing_hash()\n    publisher = self._publishers.get(key, publisher)\n    super().publisher(key, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.start","title":"start async","text":"
start() -> None\n

Start the RabbitMQ broker.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def start(self) -> None:\n    \"\"\"\n    Start the RabbitMQ broker.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, RabbitQueue(\"\"), RabbitExchange(\"\")),\n    )\n\n    await super().start()\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n\n    for publisher in self._publishers.values():\n        if publisher.exchange is not None:\n            await self.declare_exchange(publisher.exchange)\n\n    for handler in self.handlers.values():\n        c = self._get_log_context(None, handler.queue, handler.exchange)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self.declarer)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Filter[RabbitMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n

Decorator to define a message subscriber.

PARAMETER DESCRIPTION queue

The name of the RabbitMQ queue.

TYPE: Union[str, RabbitQueue]

exchange

The name of the RabbitMQ exchange. Defaults to None.

TYPE: Union[str, RabbitExchange, None] DEFAULT: None

consume_args

Additional arguments for message consumption.

TYPE: Optional[AnyDict] DEFAULT: None

no_ack

Whether not to ack/nack/reject messages.

TYPE: bool DEFAULT: False

title

Title for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

description

Description for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION Callable

A decorator function for defining message subscribers.

TYPE: Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn]]

Source code in faststream/rabbit/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[aio_pika.IncomingMessage, RabbitMessage]] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[aio_pika.IncomingMessage], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RabbitMessage] = default_filter,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"\n    Decorator to define a message subscriber.\n\n    Args:\n        queue (Union[str, RabbitQueue]): The name of the RabbitMQ queue.\n        exchange (Union[str, RabbitExchange, None], optional): The name of the RabbitMQ exchange. Defaults to None.\n        consume_args (Optional[AnyDict], optional): Additional arguments for message consumption.\n        no_ack (bool): Whether not to ack/nack/reject messages.\n        title (Optional[str]): Title for AsyncAPI docs.\n        description (Optional[str]): Description for AsyncAPI docs.\n\n    Returns:\n        Callable: A decorator function for defining message subscribers.\n    \"\"\"\n    super().subscriber()\n\n    r_queue = RabbitQueue.validate(queue)\n    r_exchange = RabbitExchange.validate(exchange)\n\n    self._setup_log_context(r_queue, r_exchange)\n\n    key = get_routing_hash(r_queue, r_exchange)\n    handler = self.handlers.get(\n        key,\n        Handler(\n            log_context_builder=partial(\n                self._get_log_context, queue=r_queue, exchange=r_exchange\n            ),\n            queue=r_queue,\n            exchange=r_exchange,\n            consume_args=consume_args,\n            description=description,\n            title=title,\n            virtual_host=self.virtual_host,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n        ),\n    )\n\n    self.handlers[key] = handler\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[\n        aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn\n    ]:\n        \"\"\"Wraps a consumer function with additional functionality.\n\n        Args:\n            func: The consumer function to be wrapped.\n\n        Returns:\n            The wrapped consumer function.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            _process_kwargs={\n                \"reply_config\": reply_config,\n            },\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/rabbit/fastapi/Context/#faststream.broker.fastapi.context.Context","title":"faststream.broker.fastapi.context.Context","text":"
Context(name: str) -> Any\n
Source code in faststream/broker/fastapi/context.py
def Context(name: str) -> Any:\n    return params.Depends(\n        lambda: context.resolve(name),\n        use_cache=True,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/","title":"RabbitRouter","text":"","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter","title":"faststream.rabbit.fastapi.RabbitRouter","text":"
RabbitRouter(\n    url: Union[\n        str, URL, None\n    ] = \"amqp://guest:guest@localhost:5672/\",\n    *,\n    host: str = \"localhost\",\n    port: int = 5672,\n    login: str = \"guest\",\n    password: str = \"guest\",\n    virtualhost: str = \"/\",\n    ssl_options: Optional[aio_pika.abc.SSLOptions] = None,\n    timeout: aio_pika.abc.TimeoutType = None,\n    client_properties: Optional[FieldTable] = None,\n    security: Optional[BaseSecurity] = None,\n    max_consumers: Optional[int] = None,\n    graceful_timeout: Optional[float] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    asyncapi_url: Optional[str] = None,\n    protocol: str = \"amqp\",\n    protocol_version: Optional[str] = \"0.9.1\",\n    description: Optional[str] = None,\n    asyncapi_tags: Optional[Sequence[asyncapi.Tag]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    setup_state: bool = True,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n)\n

Bases: StreamRouter[IncomingMessage]

A class to represent a RabbitMQ router for incoming messages.

METHOD DESCRIPTION _setup_log_context

sets up the log context for the main broker and the including broker

Source code in faststream/rabbit/fastapi.py
main_broker._setup_log_context(h.queue, h.exchange)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.broker","title":"broker instance-attribute","text":"
broker: RabbitBroker\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.broker_class","title":"broker_class class-attribute instance-attribute","text":"
broker_class: Type[RabbitBroker] = RB\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    queue: Union[str, RabbitQueue],\n    *,\n    endpoint: Callable[..., T_HandlerReturn],\n    exchange: Union[str, RabbitExchange, None] = None,\n    consume_args: Optional[AnyDict] = None,\n    dependencies: Sequence[params.Depends] = (),\n    filter: Filter[RabbitMessage] = default_filter,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    retry: Union[bool, int] = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    **__service_kwargs: Any\n) -> Callable[\n    [IncomingMessage, bool], Awaitable[T_HandlerReturn]\n]\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.publisher","title":"publisher","text":"
publisher(\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    headers: Optional[aio_pika.abc.HeadersType] = None,\n    content_type: Optional[str] = None,\n    content_encoding: Optional[str] = None,\n    priority: Optional[int] = None,\n    correlation_id: Optional[str] = None,\n    expiration: Optional[aio_pika.abc.DateType] = None,\n    message_id: Optional[str] = None,\n    timestamp: Optional[aio_pika.abc.DateType] = None,\n    type: Optional[str] = None,\n    user_id: Optional[str] = None,\n    app_id: Optional[str] = None\n) -> Publisher\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    dependencies: Sequence[params.Depends] = (),\n    filter: Filter[RabbitMessage] = default_filter,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    retry: Union[bool, int] = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/","title":"LogicHandler","text":"","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler","title":"faststream.rabbit.handler.LogicHandler","text":"
LogicHandler(\n    queue: RabbitQueue,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    exchange: Optional[RabbitExchange] = None,\n    consume_args: Optional[AnyDict] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    virtual_host: str = \"/\",\n)\n

Bases: AsyncHandler[IncomingMessage], BaseRMQInformation

A class to handle logic for RabbitMQ message consumption.

METHOD DESCRIPTION __init__

Initializes the LogicHandler object

add_call

Adds a call to be handled by the LogicHandler

start

Starts consuming messages from the queue

close

Closes the consumer and cancels message consumption

Initialize a RabbitMQ consumer.

PARAMETER DESCRIPTION queue

RabbitQueue object representing the queue to consume from

TYPE: RabbitQueue

exchange

RabbitExchange object representing the exchange to bind the queue to (optional)

TYPE: Optional[RabbitExchange] DEFAULT: None

consume_args

Additional arguments for consuming from the queue (optional)

TYPE: Optional[AnyDict] DEFAULT: None

description

Description of the consumer (optional)

TYPE: Optional[str] DEFAULT: None

title

Title of the consumer (optional)

TYPE: Optional[str] DEFAULT: None

Source code in faststream/rabbit/handler.py
def __init__(\n    self,\n    queue: RabbitQueue,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # RMQ information\n    exchange: Optional[RabbitExchange] = None,\n    consume_args: Optional[AnyDict] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    virtual_host: str = \"/\",\n) -> None:\n    \"\"\"Initialize a RabbitMQ consumer.\n\n    Args:\n        queue: RabbitQueue object representing the queue to consume from\n        exchange: RabbitExchange object representing the exchange to bind the queue to (optional)\n        consume_args: Additional arguments for consuming from the queue (optional)\n        description: Description of the consumer (optional)\n        title: Title of the consumer (optional)\n\n    \"\"\"\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.queue = queue\n    self.exchange = exchange\n    self.virtual_host = virtual_host\n    self.consume_args = consume_args or {}\n\n    self._consumer_tag = None\n    self._queue_obj = None\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.consume_args","title":"consume_args instance-attribute","text":"
consume_args: AnyDict = consume_args or {}\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.exchange","title":"exchange instance-attribute","text":"
exchange: Optional[RabbitExchange] = exchange\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.queue","title":"queue instance-attribute","text":"
queue: RabbitQueue = queue\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.virtual_host","title":"virtual_host instance-attribute","text":"
virtual_host = virtual_host\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ],\n    decoder: Optional[CustomDecoder[RabbitMessage]],\n    filter: Filter[RabbitMessage],\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ]\n) -> None\n

Add a call to the handler.

PARAMETER DESCRIPTION handler

The handler for the call.

TYPE: HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn]

dependant

The dependant for the call.

TYPE: CallModel[P_HandlerParams, T_HandlerReturn]

parser

Optional custom parser for the call.

TYPE: Optional[CustomParser[IncomingMessage, RabbitMessage]]

decoder

Optional custom decoder for the call.

TYPE: Optional[CustomDecoder[RabbitMessage]]

filter

The filter for the call.

TYPE: Filter[RabbitMessage]

middlewares

Optional sequence of middlewares for the call.

TYPE: Optional[Sequence[Callable[[IncomingMessage], BaseMiddleware]]]

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[\n        aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[aio_pika.IncomingMessage, RabbitMessage]],\n    decoder: Optional[CustomDecoder[RabbitMessage]],\n    filter: Filter[RabbitMessage],\n    middlewares: Optional[\n        Sequence[Callable[[aio_pika.IncomingMessage], BaseMiddleware]]\n    ],\n) -> None:\n    \"\"\"Add a call to the handler.\n\n    Args:\n        handler: The handler for the call.\n        dependant: The dependant for the call.\n        parser: Optional custom parser for the call.\n        decoder: Optional custom decoder for the call.\n        filter: The filter for the call.\n        middlewares: Optional sequence of middlewares for the call.\n\n    Returns:\n        None\n\n    \"\"\"\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, AioPikaParser.parse_message),\n        decoder=resolve_custom_func(decoder, AioPikaParser.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/rabbit/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self._queue_obj is not None:\n        if self._consumer_tag is not None:  # pragma: no branch\n            await self._queue_obj.cancel(self._consumer_tag)\n            self._consumer_tag = None\n        self._queue_obj = None\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.start","title":"start async","text":"
start(declarer: RabbitDeclarer) -> None\n

Starts the consumer for the RabbitMQ queue.

PARAMETER DESCRIPTION declarer

RabbitDeclarer object used to declare the queue and exchange

TYPE: RabbitDeclarer

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/handler.py
@override\nasync def start(self, declarer: RabbitDeclarer) -> None:  # type: ignore[override]\n    \"\"\"Starts the consumer for the RabbitMQ queue.\n\n    Args:\n        declarer: RabbitDeclarer object used to declare the queue and exchange\n\n    Returns:\n        None\n\n    \"\"\"\n    self._queue_obj = queue = await declarer.declare_queue(self.queue)\n\n    if self.exchange is not None:\n        exchange = await declarer.declare_exchange(self.exchange)\n        await queue.bind(\n            exchange,\n            routing_key=self.queue.routing,\n            arguments=self.queue.bind_arguments,\n        )\n\n    self._consumer_tag = await queue.consume(\n        # NOTE: aio-pika expects AbstractIncomingMessage, not IncomingMessage\n        self.consume,  # type: ignore[arg-type]\n        arguments=self.consume_args,\n    )\n\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/","title":"RabbitDeclarer","text":"","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer","title":"faststream.rabbit.helpers.RabbitDeclarer","text":"
RabbitDeclarer(channel: aio_pika.RobustChannel)\n

Bases: Singleton

A class to declare RabbitMQ queues and exchanges.

METHOD DESCRIPTION declare_queue

RabbitQueue) -> aio_pika.RobustQueue Declares a queue and returns the declared queue object.

declare_exchange

RabbitExchange) -> aio_pika.RobustExchange Declares an exchange and returns the declared exchange object.

Initialize the class.

PARAMETER DESCRIPTION channel

Aio_pika RobustChannel object

TYPE: RobustChannel

Source code in faststream/rabbit/helpers.py
def __init__(self, channel: aio_pika.RobustChannel) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        channel: Aio_pika RobustChannel object\n\n    Attributes:\n        channel: Aio_pika RobustChannel object\n        queues: A dictionary to store queues\n        exchanges: A dictionary to store exchanges\n\n    \"\"\"\n    self.channel = channel\n    self.queues = {}\n    self.exchanges = {}\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer.channel","title":"channel instance-attribute","text":"
channel: aio_pika.RobustChannel = channel\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer.exchanges","title":"exchanges instance-attribute","text":"
exchanges: Dict[\n    Union[RabbitExchange, str], aio_pika.RobustExchange\n] = {}\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer.queues","title":"queues instance-attribute","text":"
queues: Dict[\n    Union[RabbitQueue, str], aio_pika.RobustQueue\n] = {}\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer.declare_exchange","title":"declare_exchange async","text":"
declare_exchange(\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange\n

Declare an exchange.

PARAMETER DESCRIPTION exchange

RabbitExchange object representing the exchange to be declared.

TYPE: RabbitExchange

RETURNS DESCRIPTION RobustExchange

aio_pika.RobustExchange: The declared exchange.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/rabbit/helpers.py
async def declare_exchange(\n    self,\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange:\n    \"\"\"Declare an exchange.\n\n    Args:\n        exchange: RabbitExchange object representing the exchange to be declared.\n\n    Returns:\n        aio_pika.RobustExchange: The declared exchange.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    exch = self.exchanges.get(exchange)\n\n    if exch is None:\n        exch = cast(\n            aio_pika.RobustExchange,\n            await self.channel.declare_exchange(\n                **model_to_dict(\n                    exchange,\n                    exclude={\n                        \"routing_key\",\n                        \"bind_arguments\",\n                        \"bind_to\",\n                    },\n                )\n            ),\n        )\n        self.exchanges[exchange] = exch\n\n    if exchange.bind_to is not None:\n        parent = await self.declare_exchange(exchange.bind_to)\n        await exch.bind(\n            exchange=parent,\n            routing_key=exchange.routing_key,\n            arguments=exchange.arguments,\n        )\n\n    return exch\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer.declare_queue","title":"declare_queue async","text":"
declare_queue(queue: RabbitQueue) -> aio_pika.RobustQueue\n

Declare a queue.

PARAMETER DESCRIPTION queue

RabbitQueue object representing the queue to be declared.

TYPE: RabbitQueue

RETURNS DESCRIPTION RobustQueue

aio_pika.RobustQueue: The declared queue.

Source code in faststream/rabbit/helpers.py
async def declare_queue(\n    self,\n    queue: RabbitQueue,\n) -> aio_pika.RobustQueue:\n    \"\"\"Declare a queue.\n\n    Args:\n        queue: RabbitQueue object representing the queue to be declared.\n\n    Returns:\n        aio_pika.RobustQueue: The declared queue.\n\n    \"\"\"\n    q = self.queues.get(queue)\n    if q is None:\n        q = cast(\n            aio_pika.RobustQueue,\n            await self.channel.declare_queue(\n                **model_to_dict(\n                    queue,\n                    exclude={\n                        \"routing_key\",\n                        \"path_regex\",\n                        \"bind_arguments\",\n                    },\n                )\n            ),\n        )\n        self.queues[queue] = q\n    return q\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/","title":"RabbitMessage","text":"","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage","title":"faststream.rabbit.message.RabbitMessage","text":"

Bases: StreamMessage[IncomingMessage]

A message class for working with RabbitMQ messages.

This class extends StreamMessage to provide additional functionality for acknowledging, rejecting, or nack-ing RabbitMQ messages.

METHOD DESCRIPTION ack

Acknowledge the RabbitMQ message.

nack

Negative Acknowledgment of the RabbitMQ message.

reject

Reject the RabbitMQ message.

","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.ack","title":"ack async","text":"
ack(**kwargs: Any) -> None\n

Acknowledge the RabbitMQ message.

Acknowledgment indicates that the message has been successfully processed.

PARAMETER DESCRIPTION **kwargs

Additional keyword arguments (not used).

TYPE: Any DEFAULT: {}

Source code in faststream/rabbit/message.py
async def ack(self, **kwargs: Any) -> None:\n    \"\"\"\n    Acknowledge the RabbitMQ message.\n\n    Acknowledgment indicates that the message has been successfully processed.\n\n    Args:\n        **kwargs (Any): Additional keyword arguments (not used).\n\n    \"\"\"\n    pika_message = self.raw_message\n    await super().ack()\n    if (\n        pika_message._IncomingMessage__processed  # type: ignore[attr-defined]\n        or pika_message._IncomingMessage__no_ack  # type: ignore[attr-defined]\n    ):\n        return\n    await pika_message.ack()\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.nack","title":"nack async","text":"
nack(**kwargs: Any) -> None\n

Negative Acknowledgment of the RabbitMQ message.

Nack-ing a message indicates that the message processing has failed and should be requeued.

PARAMETER DESCRIPTION **kwargs

Additional keyword arguments (not used).

TYPE: Any DEFAULT: {}

Source code in faststream/rabbit/message.py
async def nack(self, **kwargs: Any) -> None:\n    \"\"\"\n    Negative Acknowledgment of the RabbitMQ message.\n\n    Nack-ing a message indicates that the message processing has failed and should be requeued.\n\n    Args:\n        **kwargs (Any): Additional keyword arguments (not used).\n\n    \"\"\"\n    pika_message = self.raw_message\n    await super().nack()\n    if (\n        pika_message._IncomingMessage__processed  # type: ignore[attr-defined]\n        or pika_message._IncomingMessage__no_ack  # type: ignore[attr-defined]\n    ):\n        return\n    await pika_message.nack()\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.reject","title":"reject async","text":"
reject(**kwargs: Any) -> None\n

Reject the RabbitMQ message.

Rejecting a message indicates that the message processing has failed, and it should not be requeued.

PARAMETER DESCRIPTION **kwargs

Additional keyword arguments (not used).

TYPE: Any DEFAULT: {}

Source code in faststream/rabbit/message.py
async def reject(self, **kwargs: Any) -> None:\n    \"\"\"\n    Reject the RabbitMQ message.\n\n    Rejecting a message indicates that the message processing has failed, and it should not be requeued.\n\n    Args:\n        **kwargs (Any): Additional keyword arguments (not used).\n\n    \"\"\"\n    pika_message = self.raw_message\n    await super().reject()\n    if (\n        pika_message._IncomingMessage__processed  # type: ignore[attr-defined]\n        or pika_message._IncomingMessage__no_ack  # type: ignore[attr-defined]\n    ):\n        return\n    await pika_message.reject()\n
","boost":0.5},{"location":"api/faststream/rabbit/parser/AioPikaParser/","title":"AioPikaParser","text":"","boost":0.5},{"location":"api/faststream/rabbit/parser/AioPikaParser/#faststream.rabbit.parser.AioPikaParser","title":"faststream.rabbit.parser.AioPikaParser","text":"

A class for parsing, encoding, and decoding messages using aio-pika.

METHOD DESCRIPTION parse_message

aio_pika.IncomingMessage) -> StreamMessage[aio_pika.IncomingMessage]: Parses an incoming message and returns a StreamMessage object.

decode_message

StreamMessage[aio_pika.IncomingMessage]) -> DecodedMessage: Decodes a StreamMessage object and returns a DecodedMessage object.

encode_message

AioPikaSendableMessage, persist: bool = False, callback_queue: Optional[aio_pika.abc.AbstractRobustQueue] = None, reply_to: Optional[str] = None, **message_kwargs: Any) -> aio_pika.Message: Encodes a message into an aio_pika.Message object.

","boost":0.5},{"location":"api/faststream/rabbit/parser/AioPikaParser/#faststream.rabbit.parser.AioPikaParser.decode_message","title":"decode_message async staticmethod","text":"
decode_message(\n    msg: StreamMessage[aio_pika.IncomingMessage],\n) -> DecodedMessage\n

Decode a message.

PARAMETER DESCRIPTION msg

The message to decode.

TYPE: StreamMessage[IncomingMessage]

RETURNS DESCRIPTION DecodedMessage

The decoded message.

Source code in faststream/rabbit/parser.py
@staticmethod\nasync def decode_message(\n    msg: StreamMessage[aio_pika.IncomingMessage],\n) -> DecodedMessage:\n    \"\"\"Decode a message.\n\n    Args:\n        msg: The message to decode.\n\n    Returns:\n        The decoded message.\n\n    \"\"\"\n    return decode_message(msg)\n
","boost":0.5},{"location":"api/faststream/rabbit/parser/AioPikaParser/#faststream.rabbit.parser.AioPikaParser.encode_message","title":"encode_message staticmethod","text":"
encode_message(\n    message: AioPikaSendableMessage,\n    persist: bool = False,\n    callback_queue: Optional[\n        aio_pika.abc.AbstractRobustQueue\n    ] = None,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any\n) -> aio_pika.Message\n

Encodes a message for sending using AioPika.

PARAMETER DESCRIPTION message

The message to encode.

TYPE: AioPikaSendableMessage

persist

Whether to persist the message. Defaults to False.

TYPE: bool DEFAULT: False

callback_queue

The callback queue to use for replies. Defaults to None.

TYPE: AbstractRobustQueue DEFAULT: None

reply_to

The reply-to queue to use for replies. Defaults to None.

TYPE: str DEFAULT: None

**message_kwargs

Additional keyword arguments to include in the encoded message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Message

aio_pika.Message: The encoded message.

RAISES DESCRIPTION NotImplementedError

If the message is not an instance of aio_pika.Message.

Source code in faststream/rabbit/parser.py
@staticmethod\ndef encode_message(\n    message: AioPikaSendableMessage,\n    persist: bool = False,\n    callback_queue: Optional[aio_pika.abc.AbstractRobustQueue] = None,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any,\n) -> aio_pika.Message:\n    \"\"\"Encodes a message for sending using AioPika.\n\n    Args:\n        message (AioPikaSendableMessage): The message to encode.\n        persist (bool, optional): Whether to persist the message. Defaults to False.\n        callback_queue (aio_pika.abc.AbstractRobustQueue, optional): The callback queue to use for replies. Defaults to None.\n        reply_to (str, optional): The reply-to queue to use for replies. Defaults to None.\n        **message_kwargs (Any): Additional keyword arguments to include in the encoded message.\n\n    Returns:\n        aio_pika.Message: The encoded message.\n\n    Raises:\n        NotImplementedError: If the message is not an instance of aio_pika.Message.\n\n    \"\"\"\n    if isinstance(message, aio_pika.Message):\n        return message\n\n    else:\n        message, content_type = encode_message(message)\n\n        delivery_mode = (\n            DeliveryMode.PERSISTENT if persist else DeliveryMode.NOT_PERSISTENT\n        )\n\n        return aio_pika.Message(\n            message,\n            **{\n                \"delivery_mode\": delivery_mode,\n                \"content_type\": content_type,\n                \"reply_to\": callback_queue or reply_to,\n                \"correlation_id\": str(uuid4()),\n                **message_kwargs,\n            },\n        )\n
","boost":0.5},{"location":"api/faststream/rabbit/parser/AioPikaParser/#faststream.rabbit.parser.AioPikaParser.parse_message","title":"parse_message async staticmethod","text":"
parse_message(\n    message: aio_pika.IncomingMessage,\n) -> StreamMessage[aio_pika.IncomingMessage]\n

Parses an incoming message and returns a RabbitMessage object.

PARAMETER DESCRIPTION message

The incoming message to parse.

TYPE: IncomingMessage

RETURNS DESCRIPTION StreamMessage[IncomingMessage]

A StreamMessage object representing the parsed message.

Source code in faststream/rabbit/parser.py
@staticmethod\nasync def parse_message(\n    message: aio_pika.IncomingMessage,\n) -> StreamMessage[aio_pika.IncomingMessage]:\n    \"\"\"Parses an incoming message and returns a RabbitMessage object.\n\n    Args:\n        message: The incoming message to parse.\n\n    Returns:\n        A StreamMessage object representing the parsed message.\n\n    \"\"\"\n    handler = context.get_local(\"handler_\")\n    path: AnyDict = {}\n    path_re: Optional[Pattern[str]]\n    if (\n        handler\n        and (path_re := handler.queue.path_regex) is not None\n        and (match := path_re.match(message.routing_key or \"\")) is not None\n    ):\n        path = match.groupdict()\n\n    return RabbitMessage(\n        body=message.body,\n        headers=message.headers,\n        reply_to=message.reply_to or \"\",\n        content_type=message.content_type,\n        message_id=message.message_id or str(uuid4()),\n        correlation_id=message.correlation_id or str(uuid4()),\n        path=path,\n        raw_message=message,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/producer/AioPikaFastProducer/","title":"AioPikaFastProducer","text":"","boost":0.5},{"location":"api/faststream/rabbit/producer/AioPikaFastProducer/#faststream.rabbit.producer.AioPikaFastProducer","title":"faststream.rabbit.producer.AioPikaFastProducer","text":"
AioPikaFastProducer(\n    channel: aio_pika.RobustChannel,\n    declarer: RabbitDeclarer,\n    parser: Optional[\n        AsyncCustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ],\n    decoder: Optional[AsyncCustomDecoder[RabbitMessage]],\n)\n

A class for fast producing messages using aio-pika.

METHOD DESCRIPTION publish

Publishes a message to a queue or exchange.

_publish

Publishes a message to an exchange.

Note: This docstring is incomplete as it is difficult to understand the purpose and functionality of the class and its methods without more context.

Initialize a class instance.

PARAMETER DESCRIPTION channel

The aio_pika.RobustChannel object.

TYPE: RobustChannel

declarer

The RabbitDeclarer object.

TYPE: RabbitDeclarer

parser

An optional AsyncCustomParser object for parsing incoming messages.

TYPE: Optional[AsyncCustomParser[IncomingMessage, RabbitMessage]]

decoder

An optional AsyncCustomDecoder object for decoding incoming messages.

TYPE: Optional[AsyncCustomDecoder[RabbitMessage]]

Source code in faststream/rabbit/producer.py
def __init__(\n    self,\n    channel: aio_pika.RobustChannel,\n    declarer: RabbitDeclarer,\n    parser: Optional[AsyncCustomParser[aio_pika.IncomingMessage, RabbitMessage]],\n    decoder: Optional[AsyncCustomDecoder[RabbitMessage]],\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        channel: The aio_pika.RobustChannel object.\n        declarer: The RabbitDeclarer object.\n        parser: An optional AsyncCustomParser object for parsing incoming messages.\n        decoder: An optional AsyncCustomDecoder object for decoding incoming messages.\n\n    \"\"\"\n    self._channel = channel\n    self.declarer = declarer\n    self._parser = resolve_custom_func(parser, AioPikaParser.parse_message)\n    self._decoder = resolve_custom_func(decoder, AioPikaParser.decode_message)\n    self._rpc_lock = anyio.Lock()\n
","boost":0.5},{"location":"api/faststream/rabbit/producer/AioPikaFastProducer/#faststream.rabbit.producer.AioPikaFastProducer.declarer","title":"declarer instance-attribute","text":"
declarer: RabbitDeclarer = declarer\n
","boost":0.5},{"location":"api/faststream/rabbit/producer/AioPikaFastProducer/#faststream.rabbit.producer.AioPikaFastProducer.publish","title":"publish async","text":"
publish(\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any\n) -> Union[\n    aiormq.abc.ConfirmationFrameType, SendableMessage\n]\n

Publish a message to a RabbitMQ queue.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: AioPikaSendableMessage DEFAULT: ''

queue

The queue to publish the message to.

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The exchange to publish the message to.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key for the message.

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory.

TYPE: bool DEFAULT: True

immediate

Whether the message should be delivered immediately.

TYPE: bool DEFAULT: False

timeout

The timeout for the operation.

TYPE: TimeoutType DEFAULT: None

rpc

Whether the message is for RPC.

TYPE: bool DEFAULT: False

rpc_timeout

The timeout for RPC.

TYPE: Optional[float] DEFAULT: 30.0

raise_timeout

Whether to raise an exception on timeout.

TYPE: bool DEFAULT: False

persist

Whether the message should be persisted.

TYPE: bool DEFAULT: False

reply_to

The reply-to queue for RPC.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional keyword arguments for the message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Union[ConfirmationFrameType, SendableMessage]

Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The result of the publish operation.

RAISES DESCRIPTION WRONG_PUBLISH_ARGS

If reply_to is not None when rpc is True.

Source code in faststream/rabbit/producer.py
async def publish(\n    self,\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any,\n) -> Union[aiormq.abc.ConfirmationFrameType, SendableMessage]:\n    \"\"\"Publish a message to a RabbitMQ queue.\n\n    Args:\n        message (AioPikaSendableMessage): The message to be published.\n        queue (Union[RabbitQueue, str]): The queue to publish the message to.\n        exchange (Union[RabbitExchange, str, None]): The exchange to publish the message to.\n        routing_key (str): The routing key for the message.\n        mandatory (bool): Whether the message is mandatory.\n        immediate (bool): Whether the message should be delivered immediately.\n        timeout (TimeoutType): The timeout for the operation.\n        rpc (bool): Whether the message is for RPC.\n        rpc_timeout (Optional[float]): The timeout for RPC.\n        raise_timeout (bool): Whether to raise an exception on timeout.\n        persist (bool): Whether the message should be persisted.\n        reply_to (Optional[str]): The reply-to queue for RPC.\n        **message_kwargs (Any): Additional keyword arguments for the message.\n\n    Returns:\n        Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The result of the publish operation.\n\n    Raises:\n        WRONG_PUBLISH_ARGS: If reply_to is not None when rpc is True.\n\n    \"\"\"\n    p_queue = RabbitQueue.validate(queue)\n\n    context: AsyncContextManager[\n        Optional[MemoryObjectReceiveStream[aio_pika.IncomingMessage]]\n    ]\n    if rpc is True:\n        if reply_to is not None:\n            raise WRONG_PUBLISH_ARGS\n        else:\n            context = _RPCCallback(\n                self._rpc_lock,\n                self.declarer.queues[RABBIT_REPLY],\n            )\n    else:\n        context = fake_context()\n\n    async with context as response_queue:\n        r = await self._publish(\n            message=message,\n            exchange=exchange,\n            routing_key=routing_key or p_queue.routing or \"\",\n            mandatory=mandatory,\n            immediate=immediate,\n            timeout=timeout,\n            persist=persist,\n            reply_to=RABBIT_REPLY if response_queue else reply_to,\n            **message_kwargs,\n        )\n\n        if response_queue is None:\n            return r\n\n        else:\n            msg: Optional[aio_pika.IncomingMessage] = None\n            with timeout_scope(rpc_timeout, raise_timeout):\n                msg = await response_queue.receive()\n\n            if msg:  # pragma: no branch\n                return await self._decoder(await self._parser(msg))\n\n    return None\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/","title":"LogicPublisher","text":"","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher","title":"faststream.rabbit.publisher.LogicPublisher dataclass","text":"

Bases: ABCPublisher[IncomingMessage]

A class to publish messages for logic processing.

METHOD DESCRIPTION publish

Publishes a message for logic processing.

","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.exchange","title":"exchange class-attribute instance-attribute","text":"
exchange: Optional[RabbitExchange] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.immediate","title":"immediate class-attribute instance-attribute","text":"
immediate: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.message_kwargs","title":"message_kwargs class-attribute instance-attribute","text":"
message_kwargs: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.persist","title":"persist class-attribute instance-attribute","text":"
persist: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.priority","title":"priority class-attribute instance-attribute","text":"
priority: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.queue","title":"queue class-attribute instance-attribute","text":"
queue: RabbitQueue = field(default=RabbitQueue(''))\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.routing","title":"routing property","text":"
routing: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.virtual_host","title":"virtual_host class-attribute instance-attribute","text":"
virtual_host: str = '/'\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/rabbit/publisher.py
Methods:\n    publish : Publishes a message for logic processing.\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.publish","title":"publish async","text":"
publish(\n    message: AioPikaSendableMessage = \"\",\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    correlation_id: Optional[str] = None,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Union[\n    aiormq.abc.ConfirmationFrameType, SendableMessage\n]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: AioPikaSendableMessage DEFAULT: ''

rpc

Whether the message is for RPC (Remote Procedure Call).

TYPE: bool DEFAULT: False

rpc_timeout

Timeout for RPC.

TYPE: Optional[float] DEFAULT: 30.0

raise_timeout

Whether to raise an exception if timeout occurs.

TYPE: bool DEFAULT: False

correlation_id

Correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional keyword arguments for the message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Union[ConfirmationFrameType, SendableMessage]

ConfirmationFrameType or SendableMessage: The result of the publish operation.

RAISES DESCRIPTION AssertionError

If _producer is not set up.

Source code in faststream/rabbit/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: AioPikaSendableMessage = \"\",\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    correlation_id: Optional[str] = None,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Union[aiormq.abc.ConfirmationFrameType, SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        rpc: Whether the message is for RPC (Remote Procedure Call).\n        rpc_timeout: Timeout for RPC.\n        raise_timeout: Whether to raise an exception if timeout occurs.\n        correlation_id: Correlation ID for the message.\n        **message_kwargs: Additional keyword arguments for the message.\n\n    Returns:\n        ConfirmationFrameType or SendableMessage: The result of the publish operation.\n\n    Raises:\n        AssertionError: If `_producer` is not set up.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(\n        message=message,\n        exchange=self.exchange,\n        routing_key=self.routing,\n        mandatory=self.mandatory,\n        immediate=self.immediate,\n        timeout=self.timeout,\n        rpc=rpc,\n        rpc_timeout=rpc_timeout,\n        raise_timeout=raise_timeout,\n        persist=self.persist,\n        reply_to=self.reply_to,\n        correlation_id=correlation_id,\n        priority=priority or self.priority,\n        **self.message_kwargs,\n        **message_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/","title":"RabbitRouter","text":"","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter","title":"faststream.rabbit.router.RabbitRouter","text":"
RabbitRouter(\n    prefix: str = \"\",\n    handlers: Sequence[RabbitRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: RabbitRouter

A class representing a RabbitMQ router for publishing messages.

METHOD DESCRIPTION _get_publisher_key

Returns the key for a given Publisher object

_update_publisher_prefix

Updates the prefix of a given Publisher object

publisher

Publishes a message to RabbitMQ

Source code in faststream/rabbit/router.py
_publishers: Dict[int, Publisher]\n\n@staticmethod\ndef _get_publisher_key(publisher: Publisher) -> int:\n    \"\"\"Get the publisher key.\n\n    Args:\n        publisher: The publisher object.\n\n    Returns:\n        The publisher key as an integer.\n\n    \"\"\"\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.publisher","title":"publisher","text":"
publisher(\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Publisher\n

Publishes a message to a RabbitMQ queue or exchange.

PARAMETER DESCRIPTION queue

The RabbitMQ queue to publish the message to. Can be either a RabbitQueue object or a string representing the queue name.

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The RabbitMQ exchange to publish the message to. Can be either a RabbitExchange object, a string representing the exchange name, or None.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key to use when publishing the message.

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory or not.

TYPE: bool DEFAULT: True

immediate

Whether the message should be delivered immediately or not.

TYPE: bool DEFAULT: False

timeout

The timeout for the publish operation.

TYPE: TimeoutType DEFAULT: None

persist

Whether the message should be persisted or not.

TYPE: bool DEFAULT: False

reply_to

The reply-to address for the message.

TYPE: Optional[str] DEFAULT: None

title

The title of the message (AsyncAPI information).

TYPE: Optional[str] DEFAULT: None

description

The description of the message (AsyncAPI information).

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional keyword arguments to include in the message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Publisher

The Publisher object used to publish the message.

Source code in faststream/rabbit/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Publisher:\n    \"\"\"Publishes a message to a RabbitMQ queue or exchange.\n\n    Args:\n        queue: The RabbitMQ queue to publish the message to. Can be either a RabbitQueue object or a string representing the queue name.\n        exchange: The RabbitMQ exchange to publish the message to. Can be either a RabbitExchange object, a string representing the exchange name, or None.\n        routing_key: The routing key to use when publishing the message.\n        mandatory: Whether the message is mandatory or not.\n        immediate: Whether the message should be delivered immediately or not.\n        timeout: The timeout for the publish operation.\n        persist: Whether the message should be persisted or not.\n        reply_to: The reply-to address for the message.\n        title: The title of the message (AsyncAPI information).\n        description: The description of the message (AsyncAPI information).\n        **message_kwargs: Additional keyword arguments to include in the message.\n\n    Returns:\n        The Publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            queue=RabbitQueue.validate(queue),\n            exchange=RabbitExchange.validate(exchange),\n            routing_key=routing_key,\n            mandatory=mandatory,\n            immediate=immediate,\n            timeout=timeout,\n            persist=persist,\n            reply_to=reply_to,\n            priority=priority,\n            message_kwargs=message_kwargs,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[key] = self._publishers.get(key, new_publisher)\n    return publisher\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    dependencies: Sequence[Depends] = (),\n    filter: Filter[RabbitMessage] = default_filter,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    retry: Union[bool, int] = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n
Source code in faststream/rabbit/router.py
    Returns:\n        Publisher: The updated publisher object.\n\n    Note:\n        This function is intended to be used as a decorator.\n\n    \"\"\"\n    publisher.queue = model_copy(\n        publisher.queue, update={\"name\": prefix + publisher.queue.name}\n    )\n    return publisher\n\n@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n
","boost":0.5},{"location":"api/faststream/rabbit/security/parse_security/","title":"parse_security","text":"","boost":0.5},{"location":"api/faststream/rabbit/security/parse_security/#faststream.rabbit.security.parse_security","title":"faststream.rabbit.security.parse_security","text":"
parse_security(security: Optional[BaseSecurity]) -> AnyDict\n
Source code in faststream/rabbit/security.py
def parse_security(security: Optional[BaseSecurity]) -> AnyDict:\n    if security is None:\n        return {}\n    elif isinstance(security, SASLPlaintext):\n        return _parse_sasl_plaintext(security)\n    elif isinstance(security, BaseSecurity):\n        return _parse_base_security(security)\n    else:\n        raise NotImplementedError(f\"RabbitBroker does not support {type(security)}\")\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/","title":"ExchangeType","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType","title":"faststream.rabbit.shared.constants.ExchangeType","text":"

Bases: str, Enum

A class to represent the exchange type.

","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.DIRECT","title":"DIRECT class-attribute instance-attribute","text":"
DIRECT = 'direct'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.FANOUT","title":"FANOUT class-attribute instance-attribute","text":"
FANOUT = 'fanout'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.HEADERS","title":"HEADERS class-attribute instance-attribute","text":"
HEADERS = 'headers'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.TOPIC","title":"TOPIC class-attribute instance-attribute","text":"
TOPIC = 'topic'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.X_CONSISTENT_HASH","title":"X_CONSISTENT_HASH class-attribute instance-attribute","text":"
X_CONSISTENT_HASH = 'x-consistent-hash'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.X_DELAYED_MESSAGE","title":"X_DELAYED_MESSAGE class-attribute instance-attribute","text":"
X_DELAYED_MESSAGE = 'x-delayed-message'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.X_MODULUS_HASH","title":"X_MODULUS_HASH class-attribute instance-attribute","text":"
X_MODULUS_HASH = 'x-modulus-hash'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/logging/RabbitLoggingMixin/","title":"RabbitLoggingMixin","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/logging/RabbitLoggingMixin/#faststream.rabbit.shared.logging.RabbitLoggingMixin","title":"faststream.rabbit.shared.logging.RabbitLoggingMixin","text":"
RabbitLoggingMixin(\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any\n)\n

Bases: LoggingMixin

A class that extends the LoggingMixin class and adds additional functionality for logging RabbitMQ related information.

METHOD DESCRIPTION __init__

Initializes the RabbitLoggingMixin object.

_get_log_context

Overrides the _get_log_context method of the LoggingMixin class to include RabbitMQ related context information.

fmt

Returns the log format string.

_setup_log_context

Sets up the log context by updating the maximum lengths of the queue and exchange names.

Initialize the class.

PARAMETER DESCRIPTION *args

Variable length argument list

TYPE: Any DEFAULT: ()

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: access_logger

log_level

Logging level

TYPE: int DEFAULT: INFO

log_fmt

Optional log format

TYPE: Optional[str] DEFAULT: None

**kwargs

Arbitrary keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/shared/logging.py
def __init__(\n    self,\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        *args: Variable length argument list\n        logger: Optional logger object\n        log_level: Logging level\n        log_fmt: Optional log format\n        **kwargs: Arbitrary keyword arguments\n\n    Returns:\n        None\n\n    \"\"\"\n    super().__init__(\n        *args,\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n        **kwargs,\n    )\n    self._max_queue_len = 4\n    self._max_exchange_len = 4\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/logging/RabbitLoggingMixin/#faststream.rabbit.shared.logging.RabbitLoggingMixin.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/logging/RabbitLoggingMixin/#faststream.rabbit.shared.logging.RabbitLoggingMixin.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/logging/RabbitLoggingMixin/#faststream.rabbit.shared.logging.RabbitLoggingMixin.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/","title":"ABCPublisher","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher","title":"faststream.rabbit.shared.publisher.ABCPublisher dataclass","text":"

Bases: ABC, BasePublisher[MsgType], BaseRMQInformation

A class representing an ABCPublisher.

","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.exchange","title":"exchange class-attribute instance-attribute","text":"
exchange: Optional[RabbitExchange] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.immediate","title":"immediate class-attribute instance-attribute","text":"
immediate: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.message_kwargs","title":"message_kwargs class-attribute instance-attribute","text":"
message_kwargs: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.persist","title":"persist class-attribute instance-attribute","text":"
persist: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.priority","title":"priority class-attribute instance-attribute","text":"
priority: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.queue","title":"queue class-attribute instance-attribute","text":"
queue: RabbitQueue = field(default=RabbitQueue(''))\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.virtual_host","title":"virtual_host class-attribute instance-attribute","text":"
virtual_host: str = '/'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.publish","title":"publish abstractmethod async","text":"
publish(\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

correlation_id

Optional correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/publisher.py
@abstractmethod\nasync def publish(\n    self,\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        correlation_id: Optional correlation ID for the message.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRoute/","title":"RabbitRoute","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/","title":"RabbitRouter","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter","title":"faststream.rabbit.shared.router.RabbitRouter","text":"
RabbitRouter(\n    prefix: str = \"\",\n    handlers: Sequence[\n        RabbitRoute[IncomingMessage, SendableMessage]\n    ] = (),\n    **kwargs: Any\n)\n

Bases: BrokerRouter[int, IncomingMessage]

A class representing a RabbitMQ router for handling incoming messages.

METHOD DESCRIPTION __init__

initializes the RabbitRouter object

subscriber

decorator for subscribing to a queue and registering a handler function

Override the __init__ method of the parent class.

PARAMETER DESCRIPTION prefix

A prefix string

TYPE: str DEFAULT: ''

handlers

A sequence of RabbitRoute objects

TYPE: Sequence[BrokerRoute[IncomingMessage, SendableMessage]] DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported

Source code in faststream/rabbit/shared/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[RabbitRoute[IncomingMessage, SendableMessage]] = (),\n    **kwargs: Any,\n) -> None:\n    \"\"\"Override the `__init__` method of the parent class.\n\n    Args:\n        prefix: A prefix string\n        handlers: A sequence of RabbitRoute objects\n        **kwargs: Additional keyword arguments\n\n    Raises:\n        NotImplementedError: If silent animals are not supported\n\n    \"\"\"\n    for h in handlers:\n        if (q := h.kwargs.pop(\"queue\", None)) is None:\n            q, h.args = h.args[0], h.args[1:]\n        queue = RabbitQueue.validate(q)\n        new_q = model_copy(queue, update={\"name\": prefix + queue.name})\n        h.args = (new_q, *h.args)\n\n    super().__init__(prefix, handlers, **kwargs)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    *broker_args: Any,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        IncomingMessage, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function to subscribe to a RabbitMQ queue.

PARAMETER DESCRIPTION self

the instance of the class

queue

the queue to subscribe to, can be a string or a RabbitQueue object

*broker_args

additional arguments for the broker

DEFAULT: ()

**broker_kwargs

additional keyword arguments for the broker

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn]]

A callable object that wraps the handler function for the incoming messages from the queue.

RAISES DESCRIPTION TypeError

If the queue is not a string or a RabbitQueue object

Source code in faststream/rabbit/shared/router.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    queue: Union[str, RabbitQueue],\n    *broker_args: Any,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function to subscribe to a RabbitMQ queue.\n\n    Args:\n        self : the instance of the class\n        queue : the queue to subscribe to, can be a string or a RabbitQueue object\n        *broker_args : additional arguments for the broker\n        **broker_kwargs : additional keyword arguments for the broker\n\n    Returns:\n        A callable object that wraps the handler function for the incoming messages from the queue.\n\n    Raises:\n        TypeError: If the queue is not a string or a RabbitQueue object\n\n    \"\"\"\n    q = RabbitQueue.validate(queue)\n    new_q = model_copy(q, update={\"name\": self.prefix + q.name})\n    return self._wrap_subscriber(new_q, *broker_args, **broker_kwargs)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/BaseRMQInformation/","title":"BaseRMQInformation","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/BaseRMQInformation/#faststream.rabbit.shared.schemas.BaseRMQInformation","title":"faststream.rabbit.shared.schemas.BaseRMQInformation dataclass","text":"

BaseRMQInformation.

","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/BaseRMQInformation/#faststream.rabbit.shared.schemas.BaseRMQInformation.exchange","title":"exchange class-attribute instance-attribute","text":"
exchange: Optional[RabbitExchange] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/BaseRMQInformation/#faststream.rabbit.shared.schemas.BaseRMQInformation.queue","title":"queue class-attribute instance-attribute","text":"
queue: RabbitQueue = field(default=RabbitQueue(''))\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/BaseRMQInformation/#faststream.rabbit.shared.schemas.BaseRMQInformation.virtual_host","title":"virtual_host class-attribute instance-attribute","text":"
virtual_host: str = '/'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/","title":"RabbitExchange","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange","title":"faststream.rabbit.shared.schemas.RabbitExchange","text":"
RabbitExchange(\n    name: str,\n    type: ExchangeType = ExchangeType.DIRECT,\n    durable: bool = False,\n    auto_delete: bool = False,\n    internal: bool = False,\n    passive: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_to: Optional[RabbitExchange] = None,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n)\n

Bases: NameRequired

A class to represent a RabbitMQ exchange.

METHOD DESCRIPTION __hash__

returns the hash value of the exchange

__init__

initializes the RabbitExchange object

Initialize a RabbitExchange object.

PARAMETER DESCRIPTION name

Name of the exchange.

TYPE: str

type

Type of the exchange. Defaults to ExchangeType.DIRECT.

TYPE: ExchangeType DEFAULT: DIRECT

durable

Whether the exchange should survive broker restarts. Defaults to False.

TYPE: bool DEFAULT: False

auto_delete

Whether the exchange should be deleted when no longer in use. Defaults to False.

TYPE: bool DEFAULT: False

internal

Whether the exchange is used for internal purposes and should not be published to directly. Defaults to False.

TYPE: bool DEFAULT: False

passive

Whether to check if the exchange exists before creating it. Defaults to False.

TYPE: bool DEFAULT: False

arguments

Additional arguments for the exchange. Defaults to None.

TYPE: Optional[AnyDict] DEFAULT: None

timeout

Timeout for the operation. Defaults to None.

TYPE: TimeoutType DEFAULT: None

robust

Whether to use robust mode for the exchange. Defaults to True.

TYPE: bool DEFAULT: True

bind_to

Exchange to bind to. Defaults to None.

TYPE: Optional[RabbitExchange] DEFAULT: None

bind_arguments

Arguments for the binding. Defaults to None.

TYPE: Optional[AnyDict] DEFAULT: None

routing_key

Routing key for the exchange. Defaults to \"\".

TYPE: str DEFAULT: ''

RAISES DESCRIPTION NotImplementedError Source code in faststream/rabbit/shared/schemas.py
def __init__(\n    self,\n    name: str,\n    type: ExchangeType = ExchangeType.DIRECT,\n    durable: bool = False,\n    auto_delete: bool = False,\n    internal: bool = False,\n    passive: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_to: Optional[\"RabbitExchange\"] = None,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n) -> None:\n    \"\"\"Initialize a RabbitExchange object.\n\n    Args:\n        name (str): Name of the exchange.\n        type (ExchangeType, optional): Type of the exchange. Defaults to ExchangeType.DIRECT.\n        durable (bool, optional): Whether the exchange should survive broker restarts. Defaults to False.\n        auto_delete (bool, optional): Whether the exchange should be deleted when no longer in use. Defaults to False.\n        internal (bool, optional): Whether the exchange is used for internal purposes and should not be published to directly. Defaults to False.\n        passive (bool, optional): Whether to check if the exchange exists before creating it. Defaults to False.\n        arguments (Optional[AnyDict], optional): Additional arguments for the exchange. Defaults to None.\n        timeout (TimeoutType, optional): Timeout for the operation. Defaults to None.\n        robust (bool, optional): Whether to use robust mode for the exchange. Defaults to True.\n        bind_to (Optional[\"RabbitExchange\"], optional): Exchange to bind to. Defaults to None.\n        bind_arguments (Optional[AnyDict], optional): Arguments for the binding. Defaults to None.\n        routing_key (str, optional): Routing key for the exchange. Defaults to \"\".\n\n    Raises:\n        NotImplementedError:\n\n    \"\"\"\n    if routing_key and bind_to is None:  # pragma: no cover\n        warnings.warn(\n            (\n                \"\\nRabbitExchange `routing_key` is using to bind exchange to another one\"\n                \"\\nIt can be used only with the `bind_to` argument, please setup it too\"\n            ),\n            category=RuntimeWarning,\n            stacklevel=1,\n        )\n\n    super().__init__(\n        name=name,\n        type=type.value,\n        durable=durable,\n        auto_delete=auto_delete,\n        routing_key=routing_key,\n        bind_to=bind_to,\n        bind_arguments=bind_arguments,\n        robust=robust,\n        internal=internal,\n        passive=passive,\n        timeout=timeout,\n        arguments=arguments,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.arguments","title":"arguments class-attribute instance-attribute","text":"
arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.auto_delete","title":"auto_delete class-attribute instance-attribute","text":"
auto_delete: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.bind_arguments","title":"bind_arguments class-attribute instance-attribute","text":"
bind_arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.bind_to","title":"bind_to class-attribute instance-attribute","text":"
bind_to: Optional[RabbitExchange] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.durable","title":"durable class-attribute instance-attribute","text":"
durable: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.internal","title":"internal class-attribute instance-attribute","text":"
internal: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.passive","title":"passive class-attribute instance-attribute","text":"
passive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.robust","title":"robust class-attribute instance-attribute","text":"
robust: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.type","title":"type class-attribute instance-attribute","text":"
type: str = ExchangeType.DIRECT.value\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/","title":"RabbitQueue","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue","title":"faststream.rabbit.shared.schemas.RabbitQueue","text":"
RabbitQueue(\n    name: str,\n    durable: bool = False,\n    exclusive: bool = False,\n    passive: bool = False,\n    auto_delete: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n)\n

Bases: NameRequired

A class to represent a RabbitMQ queue.

METHOD DESCRIPTION __hash__

returns the hash value of the queue

routing

returns the routing key of the queue

__init__

initializes the RabbitQueue object with the given parameters

Initialize a class object.

PARAMETER DESCRIPTION name

The name of the object.

TYPE: str

durable

Whether the object is durable. Defaults to False.

TYPE: bool DEFAULT: False

exclusive

Whether the object is exclusive. Defaults to False.

TYPE: bool DEFAULT: False

passive

Whether the object is passive. Defaults to False.

TYPE: bool DEFAULT: False

auto_delete

Whether the object is auto delete. Defaults to False.

TYPE: bool DEFAULT: False

arguments

Additional arguments for the object. Defaults to None.

TYPE: dict DEFAULT: None

timeout

Timeout for the object. Defaults to None.

TYPE: TimeoutType DEFAULT: None

robust

Whether the object is robust. Defaults to True.

TYPE: bool DEFAULT: True

bind_arguments

Bind arguments for the object. Defaults to None.

TYPE: dict DEFAULT: None

routing_key

Routing key for the object. Defaults to \"\".

TYPE: str DEFAULT: ''

Source code in faststream/rabbit/shared/schemas.py
def __init__(\n    self,\n    name: str,\n    durable: bool = False,\n    exclusive: bool = False,\n    passive: bool = False,\n    auto_delete: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n) -> None:\n    \"\"\"Initialize a class object.\n\n    Args:\n        name (str): The name of the object.\n        durable (bool, optional): Whether the object is durable. Defaults to False.\n        exclusive (bool, optional): Whether the object is exclusive. Defaults to False.\n        passive (bool, optional): Whether the object is passive. Defaults to False.\n        auto_delete (bool, optional): Whether the object is auto delete. Defaults to False.\n        arguments (dict, optional): Additional arguments for the object. Defaults to None.\n        timeout (TimeoutType, optional): Timeout for the object. Defaults to None.\n        robust (bool, optional): Whether the object is robust. Defaults to True.\n        bind_arguments (dict, optional): Bind arguments for the object. Defaults to None.\n        routing_key (str, optional): Routing key for the object. Defaults to \"\".\n\n    \"\"\"\n    re, routing_key = compile_path(routing_key, replace_symbol=\"*\")\n    super().__init__(\n        name=name,\n        path_regex=re,\n        durable=durable,\n        exclusive=exclusive,\n        bind_arguments=bind_arguments,\n        routing_key=routing_key,\n        robust=robust,\n        passive=passive,\n        auto_delete=auto_delete,\n        arguments=arguments,\n        timeout=timeout,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.arguments","title":"arguments class-attribute instance-attribute","text":"
arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.auto_delete","title":"auto_delete class-attribute instance-attribute","text":"
auto_delete: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.bind_arguments","title":"bind_arguments class-attribute instance-attribute","text":"
bind_arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.durable","title":"durable class-attribute instance-attribute","text":"
durable: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.exclusive","title":"exclusive class-attribute instance-attribute","text":"
exclusive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'arbitrary_types_allowed': True}\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.name","title":"name class-attribute instance-attribute","text":"
name: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.passive","title":"passive class-attribute instance-attribute","text":"
passive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.path_regex","title":"path_regex class-attribute instance-attribute","text":"
path_regex: Optional[Pattern[str]] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.robust","title":"robust class-attribute instance-attribute","text":"
robust: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.routing","title":"routing property","text":"
routing: str\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.Config.arbitrary_types_allowed","title":"arbitrary_types_allowed class-attribute instance-attribute","text":"
arbitrary_types_allowed = True\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/ReplyConfig/","title":"ReplyConfig","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/ReplyConfig/#faststream.rabbit.shared.schemas.ReplyConfig","title":"faststream.rabbit.shared.schemas.ReplyConfig","text":"

Bases: BaseModel

","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/ReplyConfig/#faststream.rabbit.shared.schemas.ReplyConfig.immediate","title":"immediate class-attribute instance-attribute","text":"
immediate: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/ReplyConfig/#faststream.rabbit.shared.schemas.ReplyConfig.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/ReplyConfig/#faststream.rabbit.shared.schemas.ReplyConfig.persist","title":"persist class-attribute instance-attribute","text":"
persist: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/get_routing_hash/","title":"get_routing_hash","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/get_routing_hash/#faststream.rabbit.shared.schemas.get_routing_hash","title":"faststream.rabbit.shared.schemas.get_routing_hash","text":"
get_routing_hash(\n    queue: RabbitQueue,\n    exchange: Optional[RabbitExchange] = None,\n) -> int\n

Calculate the routing hash for a RabbitMQ queue and exchange.

PARAMETER DESCRIPTION queue

The RabbitMQ queue.

TYPE: RabbitQueue

exchange

The RabbitMQ exchange (optional).

TYPE: Optional[RabbitExchange] DEFAULT: None

RETURNS DESCRIPTION int

The routing hash as an integer.

Source code in faststream/rabbit/shared/schemas.py
def get_routing_hash(\n    queue: RabbitQueue,\n    exchange: Optional[RabbitExchange] = None,\n) -> int:\n    \"\"\"Calculate the routing hash for a RabbitMQ queue and exchange.\n\n    Args:\n        queue: The RabbitMQ queue.\n        exchange: The RabbitMQ exchange (optional).\n\n    Returns:\n        The routing hash as an integer.\n\n    \"\"\"\n    return hash(queue) + hash(exchange or \"\")\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/utils/build_url/","title":"build_url","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/utils/build_url/#faststream.rabbit.shared.utils.build_url","title":"faststream.rabbit.shared.utils.build_url","text":"
build_url(\n    url: Union[str, URL, None] = None,\n    *,\n    host: Optional[str] = None,\n    port: Optional[int] = None,\n    login: Optional[str] = None,\n    password: Optional[str] = None,\n    virtualhost: Optional[str] = None,\n    ssl: Optional[bool] = None,\n    ssl_options: Optional[SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    **kwargs: Any\n) -> URL\n
Source code in faststream/rabbit/shared/utils.py
def build_url(\n    url: Union[str, URL, None] = None,\n    *,\n    host: Optional[str] = None,\n    port: Optional[int] = None,\n    login: Optional[str] = None,\n    password: Optional[str] = None,\n    virtualhost: Optional[str] = None,\n    ssl: Optional[bool] = None,\n    ssl_options: Optional[SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    **kwargs: Any,\n) -> URL:\n    original_url = make_url(url)\n\n    return make_url(\n        host=host or original_url.host or \"localhost\",\n        port=port or original_url.port or 5672,\n        login=login or original_url.user or \"guest\",\n        password=password or original_url.password or \"guest\",\n        virtualhost=virtualhost or removeprefix(original_url.path, \"/\"),\n        ssl=ssl or original_url.scheme == \"amqps\",\n        ssl_options=ssl_options,\n        client_properties=client_properties,\n        **{\n            **kwargs,\n            **dict(original_url.query),\n        },\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/utils/removeprefix/","title":"removeprefix","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/utils/removeprefix/#faststream.rabbit.shared.utils.removeprefix","title":"faststream.rabbit.shared.utils.removeprefix","text":"
removeprefix(string: str, prefix: str) -> str\n
Source code in faststream/rabbit/shared/utils.py
def removeprefix(string: str, prefix: str) -> str:\n    if string.startswith(prefix):\n        return string[len(prefix) :]\n    return string\n
","boost":0.5},{"location":"api/faststream/rabbit/test/FakeProducer/","title":"FakeProducer","text":"","boost":0.5},{"location":"api/faststream/rabbit/test/FakeProducer/#faststream.rabbit.test.FakeProducer","title":"faststream.rabbit.test.FakeProducer","text":"
FakeProducer(broker: RabbitBroker)\n

Bases: AioPikaFastProducer

A fake RabbitMQ producer for testing purposes.

This class extends AioPikaFastProducer and is used to simulate RabbitMQ message publishing during tests.

Initialize a FakeProducer instance.

PARAMETER DESCRIPTION broker

The RabbitBroker instance to be used for message publishing.

TYPE: RabbitBroker

Source code in faststream/rabbit/test.py
def __init__(self, broker: RabbitBroker) -> None:\n    \"\"\"\n    Initialize a FakeProducer instance.\n\n    Args:\n        broker (RabbitBroker): The RabbitBroker instance to be used for message publishing.\n    \"\"\"\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/rabbit/test/FakeProducer/#faststream.rabbit.test.FakeProducer.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/rabbit/test/FakeProducer/#faststream.rabbit.test.FakeProducer.declarer","title":"declarer instance-attribute","text":"
declarer: RabbitDeclarer = declarer\n
","boost":0.5},{"location":"api/faststream/rabbit/test/FakeProducer/#faststream.rabbit.test.FakeProducer.publish","title":"publish async","text":"
publish(\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message to a RabbitMQ queue or exchange.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: AioPikaSendableMessage DEFAULT: ''

queue

The target queue for the message.

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The target exchange for the message.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key for the message.

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory.

TYPE: bool DEFAULT: True

immediate

Whether the message should be sent immediately.

TYPE: bool DEFAULT: False

timeout

The timeout for the message.

TYPE: TimeoutType DEFAULT: None

rpc

Whether the message is for RPC.

TYPE: bool DEFAULT: False

rpc_timeout

The RPC timeout.

TYPE: float DEFAULT: 30.0

raise_timeout

Whether to raise a timeout exception.

TYPE: bool DEFAULT: False

persist

Whether to persist the message.

TYPE: bool DEFAULT: False

reply_to

The reply-to address for RPC messages.

TYPE: str DEFAULT: None

**message_kwargs

Additional message properties and content.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

Optional[SendableMessage]: The published message if successful, or None if not.

Source code in faststream/rabbit/test.py
async def publish(\n    self,\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"\n    Publish a message to a RabbitMQ queue or exchange.\n\n    Args:\n        message (AioPikaSendableMessage, optional): The message to be published.\n        queue (Union[RabbitQueue, str], optional): The target queue for the message.\n        exchange (Union[RabbitExchange, str, None], optional): The target exchange for the message.\n        routing_key (str, optional): The routing key for the message.\n        mandatory (bool, optional): Whether the message is mandatory.\n        immediate (bool, optional): Whether the message should be sent immediately.\n        timeout (TimeoutType, optional): The timeout for the message.\n        rpc (bool, optional): Whether the message is for RPC.\n        rpc_timeout (float, optional): The RPC timeout.\n        raise_timeout (bool, optional): Whether to raise a timeout exception.\n        persist (bool, optional): Whether to persist the message.\n        reply_to (str, optional): The reply-to address for RPC messages.\n        **message_kwargs (Any): Additional message properties and content.\n\n    Returns:\n        Optional[SendableMessage]: The published message if successful, or None if not.\n    \"\"\"\n    exch = RabbitExchange.validate(exchange)\n\n    incoming = build_message(\n        message=message,\n        queue=queue,\n        exchange=exch,\n        routing_key=routing_key,\n        reply_to=reply_to,\n        **message_kwargs,\n    )\n\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        if handler.exchange == exch:\n            call: bool = False\n\n            if (\n                handler.exchange is None\n                or handler.exchange.type == ExchangeType.DIRECT\n            ):\n                call = handler.queue.name == incoming.routing_key\n\n            elif handler.exchange.type == ExchangeType.FANOUT:\n                call = True\n\n            elif handler.exchange.type == ExchangeType.TOPIC:\n                call = bool(\n                    re.match(\n                        handler.queue.routing_key.replace(\".\", r\"\\.\").replace(\n                            \"*\", \".*\"\n                        ),\n                        incoming.routing_key or \"\",\n                    )\n                )\n\n            elif handler.exchange.type == ExchangeType.HEADERS:  # pramga: no branch\n                queue_headers = (handler.queue.bind_arguments or {}).copy()\n                msg_headers = incoming.headers\n\n                if not queue_headers:\n                    call = True\n\n                else:\n                    matcher = queue_headers.pop(\"x-match\", \"all\")\n\n                    full = True\n                    none = True\n                    for k, v in queue_headers.items():\n                        if msg_headers.get(k) != v:\n                            full = False\n                        else:\n                            none = False\n\n                    if not none:\n                        call = (matcher == \"any\") or full\n\n            else:  # pragma: no cover\n                raise AssertionError(\"unreachable\")\n\n            if call:\n                r = await call_handler(\n                    handler=handler,\n                    message=incoming,\n                    rpc=rpc,\n                    rpc_timeout=rpc_timeout,\n                    raise_timeout=raise_timeout,\n                )\n\n                if rpc:  # pragma: no branch\n                    return r\n\n    return None\n
","boost":0.5},{"location":"api/faststream/rabbit/test/PatchedMessage/","title":"PatchedMessage","text":"","boost":0.5},{"location":"api/faststream/rabbit/test/PatchedMessage/#faststream.rabbit.test.PatchedMessage","title":"faststream.rabbit.test.PatchedMessage","text":"

Bases: IncomingMessage

Patched message class for testing purposes.

This class extends aio_pika's IncomingMessage class and is used to simulate RabbitMQ message handling during tests.

","boost":0.5},{"location":"api/faststream/rabbit/test/PatchedMessage/#faststream.rabbit.test.PatchedMessage.ack","title":"ack async","text":"
ack(multiple: bool = False) -> None\n

Asynchronously acknowledge a message.

PARAMETER DESCRIPTION multiple

Whether to acknowledge multiple messages at once. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/test.py
async def ack(self, multiple: bool = False) -> None:\n    \"\"\"Asynchronously acknowledge a message.\n\n    Args:\n        multiple (bool, optional): Whether to acknowledge multiple messages at once. Defaults to False.\n\n    Returns:\n        None\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/rabbit/test/PatchedMessage/#faststream.rabbit.test.PatchedMessage.nack","title":"nack async","text":"
nack(multiple: bool = False, requeue: bool = True) -> None\n

Nack the message.

PARAMETER DESCRIPTION multiple

Whether to nack multiple messages. Default is False.

TYPE: bool DEFAULT: False

requeue

Whether to requeue the message. Default is True.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/test.py
async def nack(self, multiple: bool = False, requeue: bool = True) -> None:\n    \"\"\"Nack the message.\n\n    Args:\n        multiple: Whether to nack multiple messages. Default is False.\n        requeue: Whether to requeue the message. Default is True.\n\n    Returns:\n        None\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/rabbit/test/PatchedMessage/#faststream.rabbit.test.PatchedMessage.reject","title":"reject async","text":"
reject(requeue: bool = False) -> None\n

Rejects a task.

PARAMETER DESCRIPTION requeue

Whether to requeue the task if it fails (default: False)

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/test.py
async def reject(self, requeue: bool = False) -> None:\n    \"\"\"Rejects a task.\n\n    Args:\n        requeue: Whether to requeue the task if it fails (default: False)\n\n    Returns:\n        None\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/","title":"TestRabbitBroker","text":"","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker","title":"faststream.rabbit.test.TestRabbitBroker","text":"
TestRabbitBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[RabbitBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: RabbitBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: RabbitBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(\n        queue=publisher.queue,\n        exchange=publisher.exchange,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: RabbitBroker, publisher: Any\n) -> None\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef patch_publisher(broker: RabbitBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: RabbitBroker, publisher: Publisher\n) -> None\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: RabbitBroker,\n    publisher: Publisher,\n) -> None:\n    broker.handlers.pop(\n        publisher._get_routing_hash(),\n        None,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/test/build_message/","title":"build_message","text":"","boost":0.5},{"location":"api/faststream/rabbit/test/build_message/#faststream.rabbit.test.build_message","title":"faststream.rabbit.test.build_message","text":"
build_message(\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any\n) -> PatchedMessage\n

Build a patched RabbitMQ message for testing.

PARAMETER DESCRIPTION message

The message content.

TYPE: AioPikaSendableMessage DEFAULT: ''

queue

The message queue.

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The message exchange.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The message routing key.

TYPE: str DEFAULT: ''

reply_to

The reply-to queue.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional message arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION PatchedMessage

A patched RabbitMQ message.

TYPE: PatchedMessage

Source code in faststream/rabbit/test.py
def build_message(\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any,\n) -> PatchedMessage:\n    \"\"\"\n    Build a patched RabbitMQ message for testing.\n\n    Args:\n        message (AioPikaSendableMessage): The message content.\n        queue (Union[RabbitQueue, str]): The message queue.\n        exchange (Union[RabbitExchange, str, None]): The message exchange.\n        routing_key (str): The message routing key.\n        reply_to (Optional[str]): The reply-to queue.\n        **message_kwargs (Any): Additional message arguments.\n\n    Returns:\n        PatchedMessage: A patched RabbitMQ message.\n    \"\"\"\n    que = RabbitQueue.validate(queue)\n    exch = RabbitExchange.validate(exchange)\n    msg = AioPikaParser.encode_message(\n        message=message,\n        persist=False,\n        reply_to=reply_to,\n        callback_queue=None,\n        **message_kwargs,\n    )\n\n    routing = routing_key or (getattr(que, \"name\", \"\"))\n\n    return PatchedMessage(\n        aiormq.abc.DeliveredMessage(\n            delivery=spec.Basic.Deliver(\n                exchange=getattr(exch, \"name\", \"\"),\n                routing_key=routing,\n            ),\n            header=ContentHeader(\n                properties=spec.Basic.Properties(\n                    content_type=msg.content_type,\n                    message_id=str(uuid4()),\n                    headers=msg.headers,\n                    reply_to=reply_to,\n                )\n            ),\n            body=msg.body,\n            channel=AsyncMock(),\n        )\n    )\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/","title":"ListSub","text":"","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub","title":"faststream.redis.ListSub","text":"
ListSub(\n    channel: str,\n    batch: bool = False,\n    max_records: PositiveInt = 10,\n    polling_interval: PositiveFloat = 0.1,\n)\n

Bases: NameRequired

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    channel: str,\n    batch: bool = False,\n    max_records: PositiveInt = 10,\n    polling_interval: PositiveFloat = 0.1,\n) -> None:\n    super().__init__(\n        name=channel,\n        batch=batch,\n        max_records=max_records,\n        polling_interval=polling_interval,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.max_records","title":"max_records class-attribute instance-attribute","text":"
max_records: PositiveInt = 10\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: PositiveFloat = 0.1\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.records","title":"records property","text":"
records: Optional[PositiveInt]\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/","title":"PubSub","text":"","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub","title":"faststream.redis.PubSub","text":"
PubSub(\n    channel: str,\n    pattern: bool = False,\n    polling_interval: PositiveFloat = 1.0,\n)\n

Bases: NameRequired

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    channel: str,\n    pattern: bool = False,\n    polling_interval: PositiveFloat = 1.0,\n) -> None:\n    reg, path = compile_path(channel, replace_symbol=\"*\")\n\n    if reg is not None:\n        pattern = True\n\n    super().__init__(\n        name=path,\n        path_regex=reg,\n        pattern=pattern,\n        polling_interval=polling_interval,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.last_id","title":"last_id class-attribute instance-attribute","text":"
last_id: str = '$'\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'arbitrary_types_allowed': True}\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.path_regex","title":"path_regex class-attribute instance-attribute","text":"
path_regex: Optional[Pattern[str]] = None\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.pattern","title":"pattern class-attribute instance-attribute","text":"
pattern: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: PositiveFloat = 1.0\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.Config.arbitrary_types_allowed","title":"arbitrary_types_allowed class-attribute instance-attribute","text":"
arbitrary_types_allowed = True\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/","title":"RedisBroker","text":"","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker","title":"faststream.redis.RedisBroker","text":"
RedisBroker(\n    url: str = \"redis://localhost:6379\",\n    polling_interval: Optional[float] = None,\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"custom\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: RedisLoggingMixin, BrokerAsyncUsecase[AnyRedisDict, 'Redis[bytes]']

Source code in faststream/redis/broker.py
def __init__(\n    self,\n    url: str = \"redis://localhost:6379\",\n    polling_interval: Optional[float] = None,\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"custom\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    self.global_polling_interval = polling_interval\n    self._producer = None\n\n    super().__init__(\n        url=url,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n    )\n\n    url_kwargs = urlparse(self.url)\n    self.protocol = protocol or url_kwargs.scheme\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.global_polling_interval","title":"global_polling_interval instance-attribute","text":"
global_polling_interval = polling_interval\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[int, Handler]\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol or url_kwargs.scheme\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.connect","title":"connect async","text":"
connect(*args: Any, **kwargs: Any) -> Redis[bytes]\n
Source code in faststream/redis/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> \"Redis[bytes]\":\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, **kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.publish_batch","title":"publish_batch async","text":"
publish_batch(*args: Any, **kwargs: Any) -> None\n
Source code in faststream/redis/broker.py
async def publish_batch(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish_batch(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.publisher","title":"publisher","text":"
publisher(\n    channel: Union[Channel, PubSub, None] = None,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/redis/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    channel: Union[Channel, PubSub, None] = None,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    channel = PubSub.validate(channel)\n    list = ListSub.validate(list)\n    stream = StreamSub.validate(stream)\n\n    any_of = channel or list or stream\n    if any_of is None:\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    key = Handler.get_routing_hash(any_of)\n    publisher = self._publishers.get(\n        key,\n        Publisher(\n            channel=channel,\n            list=list,\n            stream=stream,\n            headers=headers,\n            reply_to=reply_to,\n            # AsyncAPI\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(key, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.start","title":"start async","text":"
start() -> None\n
Source code in faststream/redis/broker.py
async def start(self) -> None:\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n    assert self._connection, NOT_CONNECTED_YET  # nosec B101\n\n    for handler in self.handlers.values():\n        if (stream := handler.stream_sub) is not None and stream.group:\n            try:\n                await self._connection.xgroup_create(\n                    name=stream.name,\n                    groupname=stream.group,\n                    mkstream=True,\n                )\n            except ResponseError as e:\n                if \"already exists\" not in str(e):\n                    raise e\n\n        c = self._get_log_context(None, handler.channel_name)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self._connection)\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Any, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[AnyRedisDict, RedisMessage]] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[Any, P_HandlerParams, T_HandlerReturn],\n]:\n    channel = PubSub.validate(channel)\n    list = ListSub.validate(list)\n    stream = StreamSub.validate(stream)\n\n    if (any_of := channel or list or stream) is None:\n        raise ValueError(\n            \"You should specify `channel`, `list`, `stream` subscriber type\"\n        )\n\n    if all((channel, list)):\n        raise ValueError(\"You can't use `PubSub` and `ListSub` both\")\n    elif all((channel, stream)):\n        raise ValueError(\"You can't use `PubSub` and `StreamSub` both\")\n    elif all((list, stream)):\n        raise ValueError(\"You can't use `ListSub` and `StreamSub` both\")\n\n    self._setup_log_context(channel=any_of.name)\n    super().subscriber()\n\n    key = Handler.get_routing_hash(any_of)\n    handler = self.handlers[key] = self.handlers.get(\n        key,\n        Handler(  # type: ignore[abstract]\n            log_context_builder=partial(\n                self._get_log_context,\n                channel=any_of.name,\n            ),\n            graceful_timeout=self.graceful_timeout,\n            # Redis\n            channel=channel,\n            list=list,\n            stream=stream,\n            # AsyncAPI\n            title=title,\n            description=description,\n            include_in_schema=include_in_schema,\n        ),\n    )\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[AnyRedisDict, P_HandlerParams, T_HandlerReturn,]:\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,  # type: ignore[arg-type]\n            decoder=decoder or self._global_decoder,  # type: ignore[arg-type]\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/redis/RedisRoute/","title":"RedisRoute","text":"","boost":0.5},{"location":"api/faststream/redis/RedisRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/redis/RedisRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/redis/RedisRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/redis/RedisRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/","title":"RedisRouter","text":"","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter","title":"faststream.redis.RedisRouter","text":"
RedisRouter(\n    prefix: str = \"\",\n    handlers: Sequence[RedisRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    include_in_schema: bool = True\n)\n

Bases: RedisRouter

Source code in faststream/redis/router.py
            publisher.list, update={\"name\": prefix + publisher.list.name}\n        )\n    elif publisher.stream is not None:\n        publisher.stream = model_copy(\n            publisher.stream, update={\"name\": prefix + publisher.stream.name}\n        )\n    else:\n        raise AssertionError(\"unreachable\")\n    return publisher\n\n@override\ndef publisher(  # type: ignore[override]\n    self,\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.publisher","title":"publisher","text":"
publisher(\n    channel: Union[str, PubSub, None] = None,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/redis/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    channel: Union[str, PubSub, None] = None,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    if not any((stream, list, channel)):\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            channel=PubSub.validate(channel),\n            list=ListSub.validate(list),\n            stream=StreamSub.validate(stream),\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[str, PubSub, None] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Any, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/router.py
) -> Publisher:\n    if not any((stream, list, channel)):\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            channel=PubSub.validate(channel),\n            list=ListSub.validate(list),\n            stream=StreamSub.validate(stream),\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/","title":"StreamSub","text":"","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub","title":"faststream.redis.StreamSub","text":"
StreamSub(\n    stream: str,\n    polling_interval: Optional[PositiveInt] = 100,\n    group: Optional[str] = None,\n    consumer: Optional[str] = None,\n    batch: bool = False,\n    no_ack: bool = False,\n    last_id: Optional[str] = None,\n)\n

Bases: NameRequired

Redis Stream subscriber parameters

PARAMETER DESCRIPTION stream

(str): Redis Stream name.

TYPE: str

polling_interval

(int:ms | None): wait message block.

TYPE: Optional[PositiveInt] DEFAULT: 100

group

(str | None): consumer group name.

TYPE: Optional[str] DEFAULT: None

consumer

(str | None): consumer name.

TYPE: Optional[str] DEFAULT: None

batch

(bool): consume messages in batches.

TYPE: bool DEFAULT: False

no_ack

(bool): do not add message to PEL.

TYPE: bool DEFAULT: False

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    stream: str,\n    polling_interval: Optional[PositiveInt] = 100,\n    group: Optional[str] = None,\n    consumer: Optional[str] = None,\n    batch: bool = False,\n    no_ack: bool = False,\n    last_id: Optional[str] = None,\n) -> None:\n    \"\"\"\n    Redis Stream subscriber parameters\n\n    Args:\n        stream: (str): Redis Stream name.\n        polling_interval: (int:ms | None): wait message block.\n        group: (str | None): consumer group name.\n        consumer: (str | None): consumer name.\n        batch: (bool): consume messages in batches.\n        no_ack: (bool): do not add message to PEL.\n    \"\"\"\n    if (group and not consumer) or (not group and consumer):\n        raise ValueError(\"You should specify `group` and `consumer` both\")\n\n    if group and consumer:\n        msg: Optional[str] = None\n\n        if last_id:\n            msg = \"`last_id` has no effect with consumer group\"\n\n        if no_ack:\n            msg = \"`no_ack` has no effect with consumer group\"\n\n        if msg:\n            warnings.warn(\n                message=msg,\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n    super().__init__(\n        name=stream,\n        group=group,\n        consumer=consumer,\n        polling_interval=polling_interval,\n        batch=batch,\n        no_ack=no_ack,\n        last_id=last_id or \"$\",\n    )\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.consumer","title":"consumer class-attribute instance-attribute","text":"
consumer: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.group","title":"group class-attribute instance-attribute","text":"
group: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.last_id","title":"last_id class-attribute instance-attribute","text":"
last_id: str = '$'\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.no_ack","title":"no_ack class-attribute instance-attribute","text":"
no_ack: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: Optional[PositiveInt] = Field(\n    default=100, description=\"ms\"\n)\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/redis/TestApp/#faststream.broker.test.TestApp","title":"faststream.broker.test.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/redis/TestApp/#faststream.broker.test.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/","title":"TestRedisBroker","text":"","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker","title":"faststream.redis.TestRedisBroker","text":"
TestRedisBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[RedisBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: RedisBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/redis/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: RedisBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(\n        channel=publisher.channel,\n        list=publisher.list,\n        stream=publisher.stream,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: RedisBroker, publisher: Any\n) -> None\n
Source code in faststream/redis/test.py
@staticmethod\ndef patch_publisher(\n    broker: RedisBroker,\n    publisher: Any,\n) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: RedisBroker, publisher: Publisher\n) -> None\n
Source code in faststream/redis/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: RedisBroker,\n    publisher: Publisher,\n) -> None:\n    any_of = publisher.channel or publisher.list or publisher.stream\n    assert any_of  # nosec B101\n    broker.handlers.pop(Handler.get_routing_hash(any_of), None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/","title":"Handler","text":"","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler","title":"faststream.redis.asyncapi.Handler","text":"
Handler(\n    *,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    channel: Optional[PubSub] = None,\n    list: Optional[ListSub] = None,\n    stream: Optional[StreamSub] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True\n)\n

Bases: LogicRedisHandler

Source code in faststream/redis/handler.py
def __init__(\n    self,\n    *,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # Redis info\n    channel: Optional[PubSub] = None,\n    list: Optional[ListSub] = None,\n    stream: Optional[StreamSub] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    self.channel = channel\n    self.list_sub = list\n    self.stream_sub = stream\n\n    self.subscription = None\n    self.task = None\n\n    self.last_id = stream.last_id if stream else \"$\"\n\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.channel","title":"channel instance-attribute","text":"
channel = channel\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.channel_name","title":"channel_name property","text":"
channel_name: str\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.last_id","title":"last_id instance-attribute","text":"
last_id = stream.last_id if stream else '$'\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.list_sub","title":"list_sub instance-attribute","text":"
list_sub = list\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.name","title":"name property","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.stream_sub","title":"stream_sub instance-attribute","text":"
stream_sub = stream\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.subscription","title":"subscription instance-attribute","text":"
subscription: Optional[RPubSub] = None\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.task","title":"task instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        AnyDict, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[AnyDict, RedisMessage]],\n    decoder: Optional[CustomDecoder[RedisMessage]],\n    filter: Filter[RedisMessage],\n    middlewares: Optional[\n        Sequence[Callable[[AnyDict], BaseMiddleware]]\n    ]\n) -> None\n
Source code in faststream/redis/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[AnyDict, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[AnyDict, RedisMessage]],\n    decoder: Optional[CustomDecoder[RedisMessage]],\n    filter: Filter[RedisMessage],\n    middlewares: Optional[Sequence[Callable[[AnyDict], BaseMiddleware]]],\n) -> None:\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, RedisParser.parse_message),\n        decoder=resolve_custom_func(decoder, RedisParser.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/redis/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.task is not None:\n        if not self.task.done():\n            self.task.cancel()\n        self.task = None\n\n    if self.subscription is not None:\n        await self.subscription.unsubscribe()\n        await self.subscription.aclose()  # type: ignore[attr-defined]\n        self.subscription = None\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(channel: Hashable) -> int\n
Source code in faststream/redis/handler.py
@staticmethod\ndef get_routing_hash(channel: Hashable) -> int:\n    return hash(channel)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/redis/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    method = None\n    if self.list_sub is not None:\n        method = \"lpop\"\n\n    elif (ch := self.channel) is not None:\n        if ch.pattern:\n            method = \"psubscribe\"\n        else:\n            method = \"subscribe\"\n\n    elif (stream := self.stream_sub) is not None:\n        if stream.group:\n            method = \"xreadgroup\"\n        else:\n            method = \"xread\"\n\n    else:\n        raise AssertionError(\"unreachable\")\n\n    return {\n        self.name: Channel(\n            description=self.description,\n            subscribe=Operation(\n                message=Message(\n                    title=f\"{self.name}:Message\",\n                    payload=resolve_payloads(payloads),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                redis=redis.ChannelBinding(\n                    channel=self.channel_name,\n                    group_name=getattr(self.stream_sub, \"group\", None),\n                    consumer_name=getattr(self.stream_sub, \"consumer\", None),\n                    method=method,\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.start","title":"start async","text":"
start(client: Redis[bytes]) -> None\n
Source code in faststream/redis/handler.py
@override\nasync def start(self, client: \"Redis[bytes]\") -> None:  # type: ignore[override]\n    self.started = anyio.Event()\n\n    consume: Union[\n        Callable[[], Awaitable[Optional[AnyRedisDict]]],\n        Callable[[], Awaitable[Optional[Sequence[AnyRedisDict]]]],\n    ]\n    sleep: float\n\n    if (list_sub := self.list_sub) is not None:\n        sleep = list_sub.polling_interval\n        consume = partial(\n            self._consume_list_msg,\n            client=client,\n        )\n        self.started.set()\n\n    elif (channel := self.channel) is not None:\n        self.subscription = psub = client.pubsub()\n\n        if channel.pattern:\n            await psub.psubscribe(channel.name)\n        else:\n            await psub.subscribe(channel.name)\n\n        consume = partial(\n            psub.get_message,\n            ignore_subscribe_messages=True,\n            timeout=channel.polling_interval,\n        )\n        sleep = 0.01\n        self.started.set()\n\n    elif self.stream_sub is not None:\n        consume = partial(  # type: ignore[assignment]\n            self._consume_stream_msg,\n            client=client,\n        )\n        sleep = 0.01\n\n    else:\n        raise AssertionError(\"unreachable\")\n\n    await super().start()\n    self.task = asyncio.create_task(self._consume(consume, sleep))\n    # wait until Stream starts to consume\n    await anyio.sleep(0.01)\n    await self.started.wait()\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/","title":"Publisher","text":"","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher","title":"faststream.redis.asyncapi.Publisher","text":"

Bases: LogicPublisher

","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.channel","title":"channel class-attribute instance-attribute","text":"
channel: Optional[PubSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.channel_name","title":"channel_name property","text":"
channel_name: str\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[AnyDict] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.list","title":"list class-attribute instance-attribute","text":"
list: Optional[ListSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.name","title":"name property","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.stream","title":"stream class-attribute instance-attribute","text":"
stream: Optional[StreamSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    channel: Union[str, PubSub, None] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage,\n    channel: Union[str, PubSub, None] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n\n    channel = PubSub.validate(channel or self.channel)\n    list = ListSub.validate(list or self.list)\n    stream = StreamSub.validate(stream or self.stream)\n\n    assert any(\n        (channel, list, stream)\n    ), \"You have to specify outgoing channel\"  # nosec B101\n\n    headers_to_send = (self.headers or {}).copy()\n    if headers is not None:\n        headers_to_send.update(headers)\n\n    if getattr(list, \"batch\", False):\n        await self._producer.publish_batch(\n            *message,\n            list=list.name,  # type: ignore[union-attr]\n        )\n        return None\n\n    else:\n        return await self._producer.publish(\n            message=message,\n            channel=getattr(channel, \"name\", None),\n            list=getattr(list, \"name\", None),\n            stream=getattr(stream, \"name\", None),\n            reply_to=reply_to or self.reply_to,\n            correlation_id=correlation_id,\n            headers=headers_to_send,\n            rpc=rpc,\n            rpc_timeout=rpc_timeout,\n            raise_timeout=raise_timeout,\n        )\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/redis/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    method = None\n    if self.list is not None:\n        method = \"rpush\"\n    elif self.channel is not None:\n        method = \"publish\"\n    elif self.stream is not None:\n        method = \"xadd\"\n    else:\n        raise AssertionError(\"unreachable\")\n\n    return {\n        self.name: Channel(\n            description=self.description,\n            publish=Operation(\n                message=Message(\n                    title=f\"{self.name}:Message\",\n                    payload=resolve_payloads(payloads, \"Publisher\"),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                redis=redis.ChannelBinding(\n                    channel=self.channel_name,\n                    method=method,\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/","title":"RedisBroker","text":"","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker","title":"faststream.redis.broker.RedisBroker","text":"
RedisBroker(\n    url: str = \"redis://localhost:6379\",\n    polling_interval: Optional[float] = None,\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"custom\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: RedisLoggingMixin, BrokerAsyncUsecase[AnyRedisDict, 'Redis[bytes]']

Source code in faststream/redis/broker.py
def __init__(\n    self,\n    url: str = \"redis://localhost:6379\",\n    polling_interval: Optional[float] = None,\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"custom\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    self.global_polling_interval = polling_interval\n    self._producer = None\n\n    super().__init__(\n        url=url,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n    )\n\n    url_kwargs = urlparse(self.url)\n    self.protocol = protocol or url_kwargs.scheme\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.global_polling_interval","title":"global_polling_interval instance-attribute","text":"
global_polling_interval = polling_interval\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[int, Handler]\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol or url_kwargs.scheme\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.connect","title":"connect async","text":"
connect(*args: Any, **kwargs: Any) -> Redis[bytes]\n
Source code in faststream/redis/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> \"Redis[bytes]\":\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, **kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.publish_batch","title":"publish_batch async","text":"
publish_batch(*args: Any, **kwargs: Any) -> None\n
Source code in faststream/redis/broker.py
async def publish_batch(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish_batch(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.publisher","title":"publisher","text":"
publisher(\n    channel: Union[Channel, PubSub, None] = None,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/redis/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    channel: Union[Channel, PubSub, None] = None,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    channel = PubSub.validate(channel)\n    list = ListSub.validate(list)\n    stream = StreamSub.validate(stream)\n\n    any_of = channel or list or stream\n    if any_of is None:\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    key = Handler.get_routing_hash(any_of)\n    publisher = self._publishers.get(\n        key,\n        Publisher(\n            channel=channel,\n            list=list,\n            stream=stream,\n            headers=headers,\n            reply_to=reply_to,\n            # AsyncAPI\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(key, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.start","title":"start async","text":"
start() -> None\n
Source code in faststream/redis/broker.py
async def start(self) -> None:\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n    assert self._connection, NOT_CONNECTED_YET  # nosec B101\n\n    for handler in self.handlers.values():\n        if (stream := handler.stream_sub) is not None and stream.group:\n            try:\n                await self._connection.xgroup_create(\n                    name=stream.name,\n                    groupname=stream.group,\n                    mkstream=True,\n                )\n            except ResponseError as e:\n                if \"already exists\" not in str(e):\n                    raise e\n\n        c = self._get_log_context(None, handler.channel_name)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self._connection)\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Any, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[AnyRedisDict, RedisMessage]] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[Any, P_HandlerParams, T_HandlerReturn],\n]:\n    channel = PubSub.validate(channel)\n    list = ListSub.validate(list)\n    stream = StreamSub.validate(stream)\n\n    if (any_of := channel or list or stream) is None:\n        raise ValueError(\n            \"You should specify `channel`, `list`, `stream` subscriber type\"\n        )\n\n    if all((channel, list)):\n        raise ValueError(\"You can't use `PubSub` and `ListSub` both\")\n    elif all((channel, stream)):\n        raise ValueError(\"You can't use `PubSub` and `StreamSub` both\")\n    elif all((list, stream)):\n        raise ValueError(\"You can't use `ListSub` and `StreamSub` both\")\n\n    self._setup_log_context(channel=any_of.name)\n    super().subscriber()\n\n    key = Handler.get_routing_hash(any_of)\n    handler = self.handlers[key] = self.handlers.get(\n        key,\n        Handler(  # type: ignore[abstract]\n            log_context_builder=partial(\n                self._get_log_context,\n                channel=any_of.name,\n            ),\n            graceful_timeout=self.graceful_timeout,\n            # Redis\n            channel=channel,\n            list=list,\n            stream=stream,\n            # AsyncAPI\n            title=title,\n            description=description,\n            include_in_schema=include_in_schema,\n        ),\n    )\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[AnyRedisDict, P_HandlerParams, T_HandlerReturn,]:\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,  # type: ignore[arg-type]\n            decoder=decoder or self._global_decoder,  # type: ignore[arg-type]\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/redis/fastapi/Context/#faststream.broker.fastapi.context.Context","title":"faststream.broker.fastapi.context.Context","text":"
Context(name: str) -> Any\n
Source code in faststream/broker/fastapi/context.py
def Context(name: str) -> Any:\n    return params.Depends(\n        lambda: context.resolve(name),\n        use_cache=True,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/","title":"RedisRouter","text":"","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter","title":"faststream.redis.fastapi.RedisRouter","text":"
RedisRouter(\n    url: str = \"redis://localhost:6379\",\n    polling_interval: Optional[float] = None,\n    *,\n    host: str = \"localhost\",\n    port: Union[str, int] = 6379,\n    db: Union[str, int] = 0,\n    client_name: Optional[str] = None,\n    health_check_interval: float = 0,\n    max_connections: Optional[int] = None,\n    socket_timeout: Optional[float] = None,\n    socket_connect_timeout: Optional[float] = None,\n    socket_read_size: int = 65536,\n    socket_keepalive: bool = False,\n    socket_keepalive_options: Optional[\n        Mapping[int, Union[int, bytes]]\n    ] = None,\n    socket_type: int = 0,\n    retry_on_timeout: bool = False,\n    encoding: str = \"utf-8\",\n    encoding_errors: str = \"strict\",\n    decode_responses: bool = False,\n    parser_class: Type[BaseParser] = DefaultParser,\n    connection_class: Type[Connection] = Connection,\n    encoder_class: Type[Encoder] = Encoder,\n    security: Optional[BaseSecurity] = None,\n    graceful_timeout: Optional[float] = None,\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    asyncapi_url: Optional[str] = None,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"custom\",\n    description: Optional[str] = None,\n    asyncapi_tags: Optional[Sequence[asyncapi.Tag]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    setup_state: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n)\n

Bases: StreamRouter[AnyRedisDict]

Source code in faststream/redis/fastapi.py
@staticmethod\ndef _setup_log_context(  # type: ignore[override]\n    main_broker: RB,\n    including_broker: RB,\n) -> None:\n    for h in including_broker.handlers.values():\n        main_broker._setup_log_context(h.channel_name)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.broker","title":"broker instance-attribute","text":"
broker: BrokerAsyncUsecase[\n    MsgType, Any\n] = self.broker_class(\n    *connection_args,\n    apply_types=False,\n    tags=asyncapi_tags,\n    **connection_kwars\n)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.broker_class","title":"broker_class class-attribute instance-attribute","text":"
broker_class = RB\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any\n) -> HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n]\n

Add an API message queue route.

PARAMETER DESCRIPTION path

The path of the route.

TYPE: Union[NameRequired, str]

*extra

Additional path segments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint function to be called for this route.

TYPE: Callable[P_HandlerParams, T_HandlerReturn]

dependencies

The dependencies required by the endpoint function.

TYPE: Sequence[Depends]

**broker_kwargs

Additional keyword arguments to be passed to the broker.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]

The handler call wrapper for the route.

Source code in faststream/broker/fastapi/router.py
def add_api_mq_route(\n    self,\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any,\n) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n    \"\"\"Add an API message queue route.\n\n    Args:\n        path: The path of the route.\n        *extra: Additional path segments.\n        endpoint: The endpoint function to be called for this route.\n        dependencies: The dependencies required by the endpoint function.\n        **broker_kwargs: Additional keyword arguments to be passed to the broker.\n\n    Returns:\n        The handler call wrapper for the route.\n\n    \"\"\"\n    route: StreamRoute[MsgType, P_HandlerParams, T_HandlerReturn] = StreamRoute(\n        path,\n        *extra,\n        endpoint=endpoint,\n        dependencies=dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        broker=self.broker,\n        **broker_kwargs,\n    )\n    self.routes.append(route)\n    return route.handler\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.publisher","title":"publisher","text":"
publisher(\n    channel: Union[Channel, PubSub, None] = None,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    dependencies: Sequence[Depends] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Any, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/fastapi.py
def subscriber(\n    self,\n    channel: Union[str, PubSub, None] = None,\n    *,\n    dependencies: Optional[Sequence[Depends]] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[AnyRedisDict, P_HandlerParams, T_HandlerReturn],\n]:\n    return super().subscriber(\n        path=channel,\n        dependencies=dependencies,\n        **broker_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/","title":"LogicRedisHandler","text":"","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler","title":"faststream.redis.handler.LogicRedisHandler","text":"
LogicRedisHandler(\n    *,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    channel: Optional[PubSub] = None,\n    list: Optional[ListSub] = None,\n    stream: Optional[StreamSub] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True\n)\n

Bases: AsyncHandler[AnyRedisDict]

Source code in faststream/redis/handler.py
def __init__(\n    self,\n    *,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # Redis info\n    channel: Optional[PubSub] = None,\n    list: Optional[ListSub] = None,\n    stream: Optional[StreamSub] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    self.channel = channel\n    self.list_sub = list\n    self.stream_sub = stream\n\n    self.subscription = None\n    self.task = None\n\n    self.last_id = stream.last_id if stream else \"$\"\n\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.channel","title":"channel instance-attribute","text":"
channel = channel\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.channel_name","title":"channel_name property","text":"
channel_name: str\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.last_id","title":"last_id instance-attribute","text":"
last_id = stream.last_id if stream else '$'\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.list_sub","title":"list_sub instance-attribute","text":"
list_sub = list\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.stream_sub","title":"stream_sub instance-attribute","text":"
stream_sub = stream\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.subscription","title":"subscription instance-attribute","text":"
subscription: Optional[RPubSub] = None\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.task","title":"task instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        AnyDict, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[AnyDict, RedisMessage]],\n    decoder: Optional[CustomDecoder[RedisMessage]],\n    filter: Filter[RedisMessage],\n    middlewares: Optional[\n        Sequence[Callable[[AnyDict], BaseMiddleware]]\n    ]\n) -> None\n
Source code in faststream/redis/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[AnyDict, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[AnyDict, RedisMessage]],\n    decoder: Optional[CustomDecoder[RedisMessage]],\n    filter: Filter[RedisMessage],\n    middlewares: Optional[Sequence[Callable[[AnyDict], BaseMiddleware]]],\n) -> None:\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, RedisParser.parse_message),\n        decoder=resolve_custom_func(decoder, RedisParser.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/redis/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.task is not None:\n        if not self.task.done():\n            self.task.cancel()\n        self.task = None\n\n    if self.subscription is not None:\n        await self.subscription.unsubscribe()\n        await self.subscription.aclose()  # type: ignore[attr-defined]\n        self.subscription = None\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(channel: Hashable) -> int\n
Source code in faststream/redis/handler.py
@staticmethod\ndef get_routing_hash(channel: Hashable) -> int:\n    return hash(channel)\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.start","title":"start async","text":"
start(client: Redis[bytes]) -> None\n
Source code in faststream/redis/handler.py
@override\nasync def start(self, client: \"Redis[bytes]\") -> None:  # type: ignore[override]\n    self.started = anyio.Event()\n\n    consume: Union[\n        Callable[[], Awaitable[Optional[AnyRedisDict]]],\n        Callable[[], Awaitable[Optional[Sequence[AnyRedisDict]]]],\n    ]\n    sleep: float\n\n    if (list_sub := self.list_sub) is not None:\n        sleep = list_sub.polling_interval\n        consume = partial(\n            self._consume_list_msg,\n            client=client,\n        )\n        self.started.set()\n\n    elif (channel := self.channel) is not None:\n        self.subscription = psub = client.pubsub()\n\n        if channel.pattern:\n            await psub.psubscribe(channel.name)\n        else:\n            await psub.subscribe(channel.name)\n\n        consume = partial(\n            psub.get_message,\n            ignore_subscribe_messages=True,\n            timeout=channel.polling_interval,\n        )\n        sleep = 0.01\n        self.started.set()\n\n    elif self.stream_sub is not None:\n        consume = partial(  # type: ignore[assignment]\n            self._consume_stream_msg,\n            client=client,\n        )\n        sleep = 0.01\n\n    else:\n        raise AssertionError(\"unreachable\")\n\n    await super().start()\n    self.task = asyncio.create_task(self._consume(consume, sleep))\n    # wait until Stream starts to consume\n    await anyio.sleep(0.01)\n    await self.started.wait()\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/","title":"AnyRedisDict","text":"","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict","title":"faststream.redis.message.AnyRedisDict","text":"

Bases: PubSubMessage

","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.channel","title":"channel instance-attribute","text":"
channel: bytes\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.data","title":"data instance-attribute","text":"
data: Union[bytes, List[bytes]]\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.message_id","title":"message_id instance-attribute","text":"
message_id: NotRequired[str]\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.message_ids","title":"message_ids instance-attribute","text":"
message_ids: NotRequired[List[str]]\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.pattern","title":"pattern instance-attribute","text":"
pattern: NotRequired[Optional[bytes]]\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.type","title":"type instance-attribute","text":"
type: Literal['stream', 'list', 'message', 'batch']\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/","title":"BatchMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage","title":"faststream.redis.message.BatchMessage","text":"

Bases: PubSubMessage

","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage.channel","title":"channel instance-attribute","text":"
channel: bytes\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage.data","title":"data instance-attribute","text":"
data: List[bytes]\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage.message_id","title":"message_id instance-attribute","text":"
message_id: NotRequired[str]\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage.message_ids","title":"message_ids instance-attribute","text":"
message_ids: NotRequired[List[str]]\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage.type","title":"type instance-attribute","text":"
type: Literal['batch']\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchRedisMessage/","title":"BatchRedisMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/BatchRedisMessage/#faststream.redis.message.BatchRedisMessage","title":"faststream.redis.message.BatchRedisMessage","text":"

Bases: RedisAckMixin[BatchMessage]

","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/","title":"OneMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage","title":"faststream.redis.message.OneMessage","text":"

Bases: PubSubMessage

","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.channel","title":"channel instance-attribute","text":"
channel: bytes\n
","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.data","title":"data instance-attribute","text":"
data: bytes\n
","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.message_id","title":"message_id instance-attribute","text":"
message_id: NotRequired[str]\n
","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.message_ids","title":"message_ids instance-attribute","text":"
message_ids: NotRequired[List[str]]\n
","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.pattern","title":"pattern instance-attribute","text":"
pattern: NotRequired[Optional[bytes]]\n
","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.type","title":"type instance-attribute","text":"
type: Literal['stream', 'list', 'message']\n
","boost":0.5},{"location":"api/faststream/redis/message/OneRedisMessage/","title":"OneRedisMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/OneRedisMessage/#faststream.redis.message.OneRedisMessage","title":"faststream.redis.message.OneRedisMessage","text":"

Bases: RedisAckMixin[OneMessage]

","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/","title":"PubSubMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage","title":"faststream.redis.message.PubSubMessage","text":"

Bases: TypedDict

","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage.channel","title":"channel instance-attribute","text":"
channel: bytes\n
","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage.data","title":"data instance-attribute","text":"
data: Union[bytes, List[bytes]]\n
","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage.message_id","title":"message_id instance-attribute","text":"
message_id: NotRequired[str]\n
","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage.message_ids","title":"message_ids instance-attribute","text":"
message_ids: NotRequired[List[str]]\n
","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage.type","title":"type instance-attribute","text":"
type: str\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/","title":"RedisAckMixin","text":"","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin","title":"faststream.redis.message.RedisAckMixin","text":"

Bases: StreamMessage[MsgType]

","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.ack","title":"ack async","text":"
ack(redis: Redis[bytes], **kwargs: Any) -> None\n
Source code in faststream/redis/message.py
@override\nasync def ack(  # type: ignore[override]\n    self,\n    redis: \"Redis[bytes]\",\n    **kwargs: Any,\n) -> None:\n    if (\n        not self.commited\n        and (ids := self.raw_message.get(\"message_ids\"))\n        and (handler := context.get_local(\"handler_\"))\n        and (stream := handler.stream_sub)\n        and (group := stream.group)\n    ):\n        await redis.xack(self.raw_message[\"channel\"], group, *ids)  # type: ignore[no-untyped-call]\n        await super().ack()\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.nack","title":"nack async","text":"
nack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def nack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.reject","title":"reject async","text":"
reject(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def reject(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisMessage/","title":"RedisMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/RedisMessage/#faststream.redis.message.RedisMessage","title":"faststream.redis.message.RedisMessage","text":"

Bases: RedisAckMixin[AnyRedisDict]

","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/","title":"RawMessage","text":"","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/#faststream.redis.parser.RawMessage","title":"faststream.redis.parser.RawMessage","text":"

Bases: BaseModel

","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/#faststream.redis.parser.RawMessage.data","title":"data instance-attribute","text":"
data: bytes\n
","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/#faststream.redis.parser.RawMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = Field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/#faststream.redis.parser.RawMessage.build","title":"build classmethod","text":"
build(\n    message: SendableMessage,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n) -> RawMessage\n
Source code in faststream/redis/parser.py
@classmethod\ndef build(\n    cls,\n    message: SendableMessage,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n) -> \"RawMessage\":\n    payload, content_type = encode_message(message)\n\n    headers_to_send = {\n        \"correlation_id\": correlation_id or str(uuid4()),\n    }\n\n    if content_type:\n        headers_to_send[\"content-type\"] = content_type\n\n    if reply_to:\n        headers_to_send[\"reply_to\"] = reply_to\n\n    if headers is not None:\n        headers_to_send.update(headers)\n\n    return cls(\n        data=payload,\n        headers=headers_to_send,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/#faststream.redis.parser.RawMessage.encode","title":"encode classmethod","text":"
encode(\n    message: SendableMessage,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n) -> str\n
Source code in faststream/redis/parser.py
@classmethod\ndef encode(\n    cls,\n    message: SendableMessage,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n) -> str:\n    return model_to_json(\n        cls.build(\n            message=message,\n            reply_to=reply_to,\n            headers=headers,\n            correlation_id=correlation_id,\n        )\n    )\n
","boost":0.5},{"location":"api/faststream/redis/parser/RedisParser/","title":"RedisParser","text":"","boost":0.5},{"location":"api/faststream/redis/parser/RedisParser/#faststream.redis.parser.RedisParser","title":"faststream.redis.parser.RedisParser","text":"","boost":0.5},{"location":"api/faststream/redis/parser/RedisParser/#faststream.redis.parser.RedisParser.decode_message","title":"decode_message async staticmethod","text":"
decode_message(msg: OneRedisMessage) -> DecodedMessage\n
Source code in faststream/redis/parser.py
@staticmethod\nasync def decode_message(\n    msg: OneRedisMessage,\n) -> DecodedMessage:\n    return decode_message(msg)\n
","boost":0.5},{"location":"api/faststream/redis/parser/RedisParser/#faststream.redis.parser.RedisParser.parse_message","title":"parse_message async classmethod","text":"
parse_message(\n    message: Union[OneMessage, BatchMessage]\n) -> Union[OneRedisMessage, BatchRedisMessage]\n
Source code in faststream/redis/parser.py
@classmethod\nasync def parse_message(\n    cls,\n    message: Union[OneMessage, BatchMessage],\n) -> Union[OneRedisMessage, BatchRedisMessage]:\n    id_ = str(uuid4())\n\n    if message[\"type\"] == \"batch\":\n        data = dump_json(\n            [cls.parse_one_msg(x)[0] for x in message[\"data\"]]\n        ).encode()\n\n        return BatchRedisMessage(\n            raw_message=message,\n            body=data,\n            content_type=\"application/json\",\n            message_id=id_,\n            correlation_id=id_,\n        )\n\n    else:\n        data, headers = cls.parse_one_msg(message[\"data\"])\n\n        channel = message.get(\"channel\", b\"\").decode()\n\n        handler = context.get_local(\"handler_\")\n        path_re: Optional[Pattern[str]]\n        path: AnyDict = {}\n        if (\n            handler\n            and handler.channel is not None\n            and (path_re := handler.channel.path_regex) is not None\n            and (match := path_re.match(channel)) is not None\n        ):\n            path = match.groupdict()\n\n        return OneRedisMessage(\n            raw_message=message,\n            body=data,\n            path=path,\n            headers=headers,\n            reply_to=headers.get(\"reply_to\", \"\"),\n            content_type=headers.get(\"content-type\", \"\"),\n            message_id=message.get(\"message_id\", id_),\n            correlation_id=headers.get(\"correlation_id\", id_),\n        )\n
","boost":0.5},{"location":"api/faststream/redis/parser/RedisParser/#faststream.redis.parser.RedisParser.parse_one_msg","title":"parse_one_msg staticmethod","text":"
parse_one_msg(raw_data: bytes) -> Tuple[bytes, AnyDict]\n
Source code in faststream/redis/parser.py
@staticmethod\ndef parse_one_msg(raw_data: bytes) -> Tuple[bytes, AnyDict]:\n    try:\n        obj = model_parse(RawMessage, raw_data)\n    except Exception:\n        # Raw Redis message format\n        data = raw_data\n        headers: AnyDict = {}\n    else:\n        # FastStream message format\n        data = obj.data\n        headers = obj.headers\n\n    return data, headers\n
","boost":0.5},{"location":"api/faststream/redis/producer/RedisFastProducer/","title":"RedisFastProducer","text":"","boost":0.5},{"location":"api/faststream/redis/producer/RedisFastProducer/#faststream.redis.producer.RedisFastProducer","title":"faststream.redis.producer.RedisFastProducer","text":"
RedisFastProducer(\n    connection: Redis[bytes],\n    parser: Union[\n        None,\n        AsyncCustomParser[OneMessage, OneRedisMessage],\n        AsyncCustomParser[BatchMessage, BatchRedisMessage],\n    ],\n    decoder: Union[\n        None,\n        AsyncCustomDecoder[OneRedisMessage],\n        AsyncCustomDecoder[BatchRedisMessage],\n    ],\n)\n
Source code in faststream/redis/producer.py
def __init__(\n    self,\n    connection: \"Redis[bytes]\",\n    parser: Union[\n        None,\n        AsyncCustomParser[OneMessage, OneRedisMessage],\n        AsyncCustomParser[BatchMessage, BatchRedisMessage],\n    ],\n    decoder: Union[\n        None,\n        AsyncCustomDecoder[OneRedisMessage],\n        AsyncCustomDecoder[BatchRedisMessage],\n    ],\n) -> None:\n    self._connection = connection\n    self._parser = resolve_custom_func(\n        parser,  # type: ignore[arg-type,assignment]\n        RedisParser.parse_message,\n    )\n    self._decoder = resolve_custom_func(decoder, RedisParser.decode_message)\n
","boost":0.5},{"location":"api/faststream/redis/producer/RedisFastProducer/#faststream.redis.producer.RedisFastProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    channel: Optional[str] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Optional[str] = None,\n    stream: Optional[str] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/producer.py
async def publish(\n    self,\n    message: SendableMessage,\n    channel: Optional[str] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Optional[str] = None,\n    stream: Optional[str] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    if not any((channel, list, stream)):\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    psub: Optional[PubSub] = None\n    if rpc is True:\n        if reply_to:\n            raise WRONG_PUBLISH_ARGS\n\n        reply_to = str(uuid4())\n        psub = self._connection.pubsub()\n        await psub.subscribe(reply_to)\n\n    msg = RawMessage.encode(\n        message=message,\n        reply_to=reply_to,\n        headers=headers,\n        correlation_id=correlation_id,\n    )\n\n    if channel is not None:\n        await self._connection.publish(channel, msg)\n    elif list is not None:\n        await self._connection.rpush(list, msg)\n    elif stream is not None:\n        await self._connection.xadd(stream, {DATA_KEY: msg})\n    else:\n        raise AssertionError(\"unreachable\")\n\n    if psub is None:\n        return None\n\n    else:\n        m = None\n        with timeout_scope(rpc_timeout, raise_timeout):\n            # skip subscribe message\n            await psub.get_message(\n                ignore_subscribe_messages=True,\n                timeout=rpc_timeout or 0.0,\n            )\n\n            # get real response\n            m = await psub.get_message(\n                ignore_subscribe_messages=True,\n                timeout=rpc_timeout or 0.0,\n            )\n\n        await psub.unsubscribe()\n        await psub.aclose()  # type: ignore[attr-defined]\n\n        if m is None:\n            if raise_timeout:\n                raise TimeoutError()\n            else:\n                return None\n        else:\n            return await self._decoder(await self._parser(m))\n
","boost":0.5},{"location":"api/faststream/redis/producer/RedisFastProducer/#faststream.redis.producer.RedisFastProducer.publish_batch","title":"publish_batch async","text":"
publish_batch(*msgs: SendableMessage, list: str) -> None\n
Source code in faststream/redis/producer.py
async def publish_batch(\n    self,\n    *msgs: SendableMessage,\n    list: str,\n) -> None:\n    batch = (encode_message(msg)[0] for msg in msgs)\n    await self._connection.rpush(list, *batch)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/","title":"LogicPublisher","text":"","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher","title":"faststream.redis.publisher.LogicPublisher dataclass","text":"

Bases: BasePublisher[AnyRedisDict]

","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.channel","title":"channel class-attribute instance-attribute","text":"
channel: Optional[PubSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.channel_name","title":"channel_name property","text":"
channel_name: str\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[AnyDict] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.list","title":"list class-attribute instance-attribute","text":"
list: Optional[ListSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.stream","title":"stream class-attribute instance-attribute","text":"
stream: Optional[StreamSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    channel: Union[str, PubSub, None] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage,\n    channel: Union[str, PubSub, None] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n\n    channel = PubSub.validate(channel or self.channel)\n    list = ListSub.validate(list or self.list)\n    stream = StreamSub.validate(stream or self.stream)\n\n    assert any(\n        (channel, list, stream)\n    ), \"You have to specify outgoing channel\"  # nosec B101\n\n    headers_to_send = (self.headers or {}).copy()\n    if headers is not None:\n        headers_to_send.update(headers)\n\n    if getattr(list, \"batch\", False):\n        await self._producer.publish_batch(\n            *message,\n            list=list.name,  # type: ignore[union-attr]\n        )\n        return None\n\n    else:\n        return await self._producer.publish(\n            message=message,\n            channel=getattr(channel, \"name\", None),\n            list=getattr(list, \"name\", None),\n            stream=getattr(stream, \"name\", None),\n            reply_to=reply_to or self.reply_to,\n            correlation_id=correlation_id,\n            headers=headers_to_send,\n            rpc=rpc,\n            rpc_timeout=rpc_timeout,\n            raise_timeout=raise_timeout,\n        )\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/","title":"RedisRouter","text":"","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter","title":"faststream.redis.router.RedisRouter","text":"
RedisRouter(\n    prefix: str = \"\",\n    handlers: Sequence[RedisRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    include_in_schema: bool = True\n)\n

Bases: RedisRouter

Source code in faststream/redis/router.py
            publisher.list, update={\"name\": prefix + publisher.list.name}\n        )\n    elif publisher.stream is not None:\n        publisher.stream = model_copy(\n            publisher.stream, update={\"name\": prefix + publisher.stream.name}\n        )\n    else:\n        raise AssertionError(\"unreachable\")\n    return publisher\n\n@override\ndef publisher(  # type: ignore[override]\n    self,\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.publisher","title":"publisher","text":"
publisher(\n    channel: Union[str, PubSub, None] = None,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/redis/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    channel: Union[str, PubSub, None] = None,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    if not any((stream, list, channel)):\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            channel=PubSub.validate(channel),\n            list=ListSub.validate(list),\n            stream=StreamSub.validate(stream),\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[str, PubSub, None] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Any, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/router.py
) -> Publisher:\n    if not any((stream, list, channel)):\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            channel=PubSub.validate(channel),\n            list=ListSub.validate(list),\n            stream=StreamSub.validate(stream),\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/","title":"ListSub","text":"","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub","title":"faststream.redis.schemas.ListSub","text":"
ListSub(\n    channel: str,\n    batch: bool = False,\n    max_records: PositiveInt = 10,\n    polling_interval: PositiveFloat = 0.1,\n)\n

Bases: NameRequired

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    channel: str,\n    batch: bool = False,\n    max_records: PositiveInt = 10,\n    polling_interval: PositiveFloat = 0.1,\n) -> None:\n    super().__init__(\n        name=channel,\n        batch=batch,\n        max_records=max_records,\n        polling_interval=polling_interval,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.max_records","title":"max_records class-attribute instance-attribute","text":"
max_records: PositiveInt = 10\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: PositiveFloat = 0.1\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.records","title":"records property","text":"
records: Optional[PositiveInt]\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/","title":"PubSub","text":"","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub","title":"faststream.redis.schemas.PubSub","text":"
PubSub(\n    channel: str,\n    pattern: bool = False,\n    polling_interval: PositiveFloat = 1.0,\n)\n

Bases: NameRequired

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    channel: str,\n    pattern: bool = False,\n    polling_interval: PositiveFloat = 1.0,\n) -> None:\n    reg, path = compile_path(channel, replace_symbol=\"*\")\n\n    if reg is not None:\n        pattern = True\n\n    super().__init__(\n        name=path,\n        path_regex=reg,\n        pattern=pattern,\n        polling_interval=polling_interval,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.last_id","title":"last_id class-attribute instance-attribute","text":"
last_id: str = '$'\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'arbitrary_types_allowed': True}\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.path_regex","title":"path_regex class-attribute instance-attribute","text":"
path_regex: Optional[Pattern[str]] = None\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.pattern","title":"pattern class-attribute instance-attribute","text":"
pattern: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: PositiveFloat = 1.0\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.Config.arbitrary_types_allowed","title":"arbitrary_types_allowed class-attribute instance-attribute","text":"
arbitrary_types_allowed = True\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/","title":"StreamSub","text":"","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub","title":"faststream.redis.schemas.StreamSub","text":"
StreamSub(\n    stream: str,\n    polling_interval: Optional[PositiveInt] = 100,\n    group: Optional[str] = None,\n    consumer: Optional[str] = None,\n    batch: bool = False,\n    no_ack: bool = False,\n    last_id: Optional[str] = None,\n)\n

Bases: NameRequired

Redis Stream subscriber parameters

PARAMETER DESCRIPTION stream

(str): Redis Stream name.

TYPE: str

polling_interval

(int:ms | None): wait message block.

TYPE: Optional[PositiveInt] DEFAULT: 100

group

(str | None): consumer group name.

TYPE: Optional[str] DEFAULT: None

consumer

(str | None): consumer name.

TYPE: Optional[str] DEFAULT: None

batch

(bool): consume messages in batches.

TYPE: bool DEFAULT: False

no_ack

(bool): do not add message to PEL.

TYPE: bool DEFAULT: False

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    stream: str,\n    polling_interval: Optional[PositiveInt] = 100,\n    group: Optional[str] = None,\n    consumer: Optional[str] = None,\n    batch: bool = False,\n    no_ack: bool = False,\n    last_id: Optional[str] = None,\n) -> None:\n    \"\"\"\n    Redis Stream subscriber parameters\n\n    Args:\n        stream: (str): Redis Stream name.\n        polling_interval: (int:ms | None): wait message block.\n        group: (str | None): consumer group name.\n        consumer: (str | None): consumer name.\n        batch: (bool): consume messages in batches.\n        no_ack: (bool): do not add message to PEL.\n    \"\"\"\n    if (group and not consumer) or (not group and consumer):\n        raise ValueError(\"You should specify `group` and `consumer` both\")\n\n    if group and consumer:\n        msg: Optional[str] = None\n\n        if last_id:\n            msg = \"`last_id` has no effect with consumer group\"\n\n        if no_ack:\n            msg = \"`no_ack` has no effect with consumer group\"\n\n        if msg:\n            warnings.warn(\n                message=msg,\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n    super().__init__(\n        name=stream,\n        group=group,\n        consumer=consumer,\n        polling_interval=polling_interval,\n        batch=batch,\n        no_ack=no_ack,\n        last_id=last_id or \"$\",\n    )\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.consumer","title":"consumer class-attribute instance-attribute","text":"
consumer: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.group","title":"group class-attribute instance-attribute","text":"
group: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.last_id","title":"last_id class-attribute instance-attribute","text":"
last_id: str = '$'\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.no_ack","title":"no_ack class-attribute instance-attribute","text":"
no_ack: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: Optional[PositiveInt] = Field(\n    default=100, description=\"ms\"\n)\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/security/parse_security/","title":"parse_security","text":"","boost":0.5},{"location":"api/faststream/redis/security/parse_security/#faststream.redis.security.parse_security","title":"faststream.redis.security.parse_security","text":"
parse_security(security: Optional[BaseSecurity]) -> AnyDict\n
Source code in faststream/redis/security.py
def parse_security(security: Optional[BaseSecurity]) -> AnyDict:\n    if security is None:\n        return {}\n    elif isinstance(security, SASLPlaintext):\n        return _parse_sasl_plaintext(security)\n    elif isinstance(security, BaseSecurity):\n        return _parse_base_security(security)\n    else:\n        raise NotImplementedError(f\"RedisBroker does not support {type(security)}\")\n
","boost":0.5},{"location":"api/faststream/redis/shared/logging/RedisLoggingMixin/","title":"RedisLoggingMixin","text":"","boost":0.5},{"location":"api/faststream/redis/shared/logging/RedisLoggingMixin/#faststream.redis.shared.logging.RedisLoggingMixin","title":"faststream.redis.shared.logging.RedisLoggingMixin","text":"
RedisLoggingMixin(\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any\n)\n

Bases: LoggingMixin

Source code in faststream/redis/shared/logging.py
def __init__(\n    self,\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any,\n) -> None:\n    super().__init__(\n        *args,\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n        **kwargs,\n    )\n    self._message_id_ln = 15\n    self._max_channel_name = 4\n
","boost":0.5},{"location":"api/faststream/redis/shared/logging/RedisLoggingMixin/#faststream.redis.shared.logging.RedisLoggingMixin.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/redis/shared/logging/RedisLoggingMixin/#faststream.redis.shared.logging.RedisLoggingMixin.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/redis/shared/logging/RedisLoggingMixin/#faststream.redis.shared.logging.RedisLoggingMixin.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRoute/","title":"RedisRoute","text":"","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/","title":"RedisRouter","text":"","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter","title":"faststream.redis.shared.router.RedisRouter","text":"
RedisRouter(\n    prefix: str = \"\",\n    handlers: Sequence[\n        RedisRoute[AnyRedisDict, SendableMessage]\n    ] = (),\n    **kwargs: Any\n)\n

Bases: BrokerRouter[int, AnyRedisDict]

Source code in faststream/redis/shared/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[RedisRoute[AnyRedisDict, SendableMessage]] = (),\n    **kwargs: Any,\n) -> None:\n    for h in handlers:\n        if not (channel := h.kwargs.pop(\"channel\", None)):\n            if list := h.kwargs.pop(\"list\", None):\n                h.kwargs[\"list\"] = prefix + list\n                continue\n\n            elif stream := h.kwargs.pop(\"stream\", None):\n                h.kwargs[\"stream\"] = prefix + stream\n                continue\n\n            channel, h.args = h.args[0], h.args[1:]\n\n        h.args = (prefix + channel, *h.args)\n\n    super().__init__(prefix, handlers, **kwargs)\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        AnyRedisDict, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/shared/router.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[AnyRedisDict, P_HandlerParams, T_HandlerReturn],\n]:\n    channel = PubSub.validate(channel)\n    list = ListSub.validate(list)\n    stream = StreamSub.validate(stream)\n\n    return self._wrap_subscriber(\n        channel=model_copy(channel, update={\"name\": self.prefix + channel.name})\n        if channel\n        else None,\n        list=model_copy(list, update={\"name\": self.prefix + list.name})\n        if list\n        else None,\n        stream=model_copy(stream, update={\"name\": self.prefix + stream.name})\n        if stream\n        else None,\n        **broker_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/test/FakeProducer/","title":"FakeProducer","text":"","boost":0.5},{"location":"api/faststream/redis/test/FakeProducer/#faststream.redis.test.FakeProducer","title":"faststream.redis.test.FakeProducer","text":"
FakeProducer(broker: RedisBroker)\n

Bases: RedisFastProducer

Source code in faststream/redis/test.py
def __init__(self, broker: RedisBroker) -> None:\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/redis/test/FakeProducer/#faststream.redis.test.FakeProducer.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/redis/test/FakeProducer/#faststream.redis.test.FakeProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    channel: Optional[str] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Optional[str] = None,\n    stream: Optional[str] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/test.py
@override\nasync def publish(\n    self,\n    message: SendableMessage,\n    channel: Optional[str] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Optional[str] = None,\n    stream: Optional[str] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    any_of = channel or list or stream\n    if any_of is None:\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        call = False\n        batch = False\n\n        if channel and (ch := handler.channel) is not None:\n            call = bool(\n                (not ch.pattern and ch.name == channel)\n                or (\n                    ch.pattern\n                    and re.match(\n                        ch.name.replace(\".\", \"\\\\.\").replace(\"*\", \".*\"),\n                        channel,\n                    )\n                )\n            )\n\n        if list and (ls := handler.list_sub) is not None:\n            batch = ls.batch\n            call = list == ls.name\n\n        if stream and (st := handler.stream_sub) is not None:\n            batch = st.batch\n            call = stream == st.name\n\n        if call:\n            r = await call_handler(\n                handler=handler,\n                message=build_message(\n                    message=[message] if batch else message,\n                    channel=any_of,\n                    headers=headers,\n                    correlation_id=correlation_id,\n                    reply_to=reply_to,\n                ),\n                rpc=rpc,\n                rpc_timeout=rpc_timeout,\n                raise_timeout=raise_timeout,\n            )\n\n            if rpc:  # pragma: no branch\n                return r\n\n    return None\n
","boost":0.5},{"location":"api/faststream/redis/test/FakeProducer/#faststream.redis.test.FakeProducer.publish_batch","title":"publish_batch async","text":"
publish_batch(*msgs: SendableMessage, list: str) -> None\n
Source code in faststream/redis/test.py
async def publish_batch(\n    self,\n    *msgs: SendableMessage,\n    list: str,\n) -> None:\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        if handler.list_sub and handler.list_sub.name == list:\n            await call_handler(\n                handler=handler,\n                message=build_message(\n                    message=msgs,\n                    channel=list,\n                ),\n            )\n\n    return None\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/","title":"TestRedisBroker","text":"","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker","title":"faststream.redis.test.TestRedisBroker","text":"
TestRedisBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[RedisBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: RedisBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/redis/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: RedisBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(\n        channel=publisher.channel,\n        list=publisher.list,\n        stream=publisher.stream,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: RedisBroker, publisher: Any\n) -> None\n
Source code in faststream/redis/test.py
@staticmethod\ndef patch_publisher(\n    broker: RedisBroker,\n    publisher: Any,\n) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: RedisBroker, publisher: Publisher\n) -> None\n
Source code in faststream/redis/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: RedisBroker,\n    publisher: Publisher,\n) -> None:\n    any_of = publisher.channel or publisher.list or publisher.stream\n    assert any_of  # nosec B101\n    broker.handlers.pop(Handler.get_routing_hash(any_of), None)\n
","boost":0.5},{"location":"api/faststream/redis/test/build_message/","title":"build_message","text":"","boost":0.5},{"location":"api/faststream/redis/test/build_message/#faststream.redis.test.build_message","title":"faststream.redis.test.build_message","text":"
build_message(\n    message: SendableMessage,\n    channel: str,\n    *,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[AnyDict] = None\n) -> AnyRedisDict\n
Source code in faststream/redis/test.py
def build_message(\n    message: SendableMessage,\n    channel: str,\n    *,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[AnyDict] = None,\n) -> AnyRedisDict:\n    data = RawMessage.encode(\n        message=message,\n        reply_to=reply_to,\n        headers=headers,\n        correlation_id=correlation_id,\n    )\n    return AnyRedisDict(\n        channel=channel.encode(),\n        data=data.encode(),\n        type=\"message\",\n    )\n
","boost":0.5},{"location":"api/faststream/security/BaseSecurity/","title":"BaseSecurity","text":"","boost":0.5},{"location":"api/faststream/security/BaseSecurity/#faststream.security.BaseSecurity","title":"faststream.security.BaseSecurity","text":"
BaseSecurity(\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Base class for defining security configurations.

This class provides a base for defining security configurations for communication with a broker. It allows setting SSL encryption and provides methods to retrieve security requirements and schemas.

PARAMETER DESCRIPTION ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements in the form of a list of dictionaries.

get_schema

Get the security schema as a dictionary.

Source code in faststream/security.py
def __init__(\n    self,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    if ssl_context is not None:\n        use_ssl = True\n\n    self.use_ssl = use_ssl\n    self.ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/security/BaseSecurity/#faststream.security.BaseSecurity.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/security/BaseSecurity/#faststream.security.BaseSecurity.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/security/BaseSecurity/#faststream.security.BaseSecurity.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return []\n
","boost":0.5},{"location":"api/faststream/security/BaseSecurity/#faststream.security.BaseSecurity.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {}\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/","title":"SASLPlaintext","text":"","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext","title":"faststream.security.SASLPlaintext","text":"
SASLPlaintext(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/PLAINTEXT authentication.

This class defines security configuration for SASL/PLAINTEXT authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/PLAINTEXT authentication.

get_schema

Get the security schema for SASL/PLAINTEXT authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/PLAINTEXT authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/PLAINTEXT authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"user-password\": []}]\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/PLAINTEXT authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/PLAINTEXT authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"user-password\": {\"type\": \"userPassword\"}}\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/","title":"SASLScram256","text":"","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256","title":"faststream.security.SASLScram256","text":"
SASLScram256(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/SCRAM-SHA-256 authentication.

This class defines security configuration for SASL/SCRAM-SHA-256 authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/SCRAM-SHA-256 authentication.

get_schema

Get the security schema for SASL/SCRAM-SHA-256 authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/SCRAM-SHA-256 authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/SCRAM-SHA-256 authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"scram256\": []}]\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/SCRAM-SHA-256 authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/SCRAM-SHA-256 authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"scram256\": {\"type\": \"scramSha256\"}}\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/","title":"SASLScram512","text":"","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512","title":"faststream.security.SASLScram512","text":"
SASLScram512(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/SCRAM-SHA-512 authentication.

This class defines security configuration for SASL/SCRAM-SHA-512 authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/SCRAM-SHA-512 authentication.

get_schema

Get the security schema for SASL/SCRAM-SHA-512 authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/SCRAM-SHA-512 authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/SCRAM-SHA-512 authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"scram512\": []}]\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/SCRAM-SHA-512 authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/SCRAM-SHA-512 authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"scram512\": {\"type\": \"scramSha512\"}}\n
","boost":0.5},{"location":"api/faststream/utils/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/utils/Context/#faststream.utils.Context","title":"faststream.utils.Context","text":"
Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n    )\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/","title":"ContextRepo","text":"","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo","title":"faststream.utils.ContextRepo","text":"
ContextRepo()\n

Bases: Singleton

A class to represent a context repository.

METHOD DESCRIPTION __init__

initializes the ContextRepo object

set_global

sets a global context variable

reset_global

resets a global context variable

set_local

sets a local context variable

reset_local

resets a local context variable

get_local

gets the value of a local context variable

clear

clears the global and scope context

get

gets the value of a context variable

__getattr__

gets the value of a context variable using attribute access

context

gets the current context as a dictionary

scope

creates a context scope for a specific key and value

Initialize the class.

Source code in faststream/utils/context/main.py
def __init__(self) -> None:\n    \"\"\"Initialize the class.\n\n    Attributes:\n        _global_context : a dictionary representing the global context\n        _scope_context : a dictionary representing the scope context\n    \"\"\"\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.context","title":"context property","text":"
context: AnyDict\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.clear","title":"clear","text":"
clear() -> None\n
Source code in faststream/utils/context/main.py
def clear(self) -> None:\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.get","title":"get","text":"
get(key: str, default: Any = None) -> Any\n

Get the value associated with a key.

PARAMETER DESCRIPTION key

The key to retrieve the value for.

TYPE: str

RETURNS DESCRIPTION Any

The value associated with the key.

Source code in faststream/utils/context/main.py
def get(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value associated with a key.\n\n    Args:\n        key: The key to retrieve the value for.\n\n    Returns:\n        The value associated with the key.\n    \"\"\"\n    return self._global_context.get(key, self.get_local(key, default))\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.get_local","title":"get_local","text":"
get_local(key: str, default: Any = None) -> Any\n

Get the value of a local variable.

PARAMETER DESCRIPTION key

The key of the local variable to retrieve.

TYPE: str

RETURNS DESCRIPTION Any

The value of the local variable.

Source code in faststream/utils/context/main.py
def get_local(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value of a local variable.\n\n    Args:\n        key: The key of the local variable to retrieve.\n\n    Returns:\n        The value of the local variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is not None:  # pragma: no branch\n        return context_var.get()\n    else:\n        return default\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.reset_global","title":"reset_global","text":"
reset_global(key: str) -> None\n

Resets a key in the global context.

PARAMETER DESCRIPTION key

The key to reset in the global context.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_global(self, key: str) -> None:\n    \"\"\"Resets a key in the global context.\n\n    Args:\n        key (str): The key to reset in the global context.\n\n    Returns:\n        None\n    \"\"\"\n    self._global_context.pop(key, None)\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.reset_local","title":"reset_local","text":"
reset_local(key: str, tag: Token[Any]) -> None\n

Resets the local context for a given key.

PARAMETER DESCRIPTION key

The key to reset the local context for.

TYPE: str

tag

The tag associated with the local context.

TYPE: Token[Any]

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_local(self, key: str, tag: \"Token[Any]\") -> None:\n    \"\"\"Resets the local context for a given key.\n\n    Args:\n        key (str): The key to reset the local context for.\n        tag (Token[Any]): The tag associated with the local context.\n\n    Returns:\n        None\n    \"\"\"\n    self._scope_context[key].reset(tag)\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.resolve","title":"resolve","text":"
resolve(argument: str) -> Any\n

Resolve the context of an argument.

PARAMETER DESCRIPTION argument

A string representing the argument.

TYPE: str

RETURNS DESCRIPTION Any

The resolved context of the argument.

RAISES DESCRIPTION AttributeError

If the attribute does not exist in the context.

Source code in faststream/utils/context/main.py
def resolve(self, argument: str) -> Any:\n    \"\"\"Resolve the context of an argument.\n\n    Args:\n        argument: A string representing the argument.\n\n    Returns:\n        The resolved context of the argument.\n\n    Raises:\n        AttributeError: If the attribute does not exist in the context.\n    \"\"\"\n    first, *keys = argument.split(\".\")\n\n    if (v := self.get(first, _empty)) is _empty:\n        raise KeyError(f\"`{self.context}` does not contains `{first}` key\")\n\n    for i in keys:\n        if isinstance(v, Mapping):\n            v = v[i]\n        else:\n            v = getattr(v, i)\n    return v\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.scope","title":"scope","text":"
scope(key: str, value: Any) -> Iterator[None]\n

Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.

PARAMETER DESCRIPTION key

The key of the local variable

TYPE: str

value

The value to set the local variable to

TYPE: Any

YIELDS DESCRIPTION Iterator[None]

None

RETURNS DESCRIPTION Iterator[None]

An iterator that yields None

Source code in faststream/utils/context/main.py
@contextmanager\ndef scope(self, key: str, value: Any) -> Iterator[None]:\n    \"\"\"Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.\n\n    Args:\n        key: The key of the local variable\n        value: The value to set the local variable to\n\n    Yields:\n        None\n\n    Returns:\n        An iterator that yields None\n    \"\"\"\n    token = self.set_local(key, value)\n    try:\n        yield\n    finally:\n        self.reset_local(key, token)\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.set_global","title":"set_global","text":"
set_global(key: str, v: Any) -> None\n

Sets a value in the global context.

PARAMETER DESCRIPTION key

The key to set in the global context.

TYPE: str

v

The value to set.

TYPE: Any

RETURNS DESCRIPTION None

None.

Source code in faststream/utils/context/main.py
def set_global(self, key: str, v: Any) -> None:\n    \"\"\"Sets a value in the global context.\n\n    Args:\n        key: The key to set in the global context.\n        v: The value to set.\n\n    Returns:\n        None.\n    \"\"\"\n    self._global_context[key] = v\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.set_local","title":"set_local","text":"
set_local(key: str, value: T) -> Token[T]\n

Set a local context variable.

PARAMETER DESCRIPTION key

The key for the context variable.

TYPE: str

value

The value to set for the context variable.

TYPE: T

RETURNS DESCRIPTION Token[T]

Token[T]: A token representing the context variable.

Source code in faststream/utils/context/main.py
def set_local(self, key: str, value: T) -> \"Token[T]\":\n    \"\"\"Set a local context variable.\n\n    Args:\n        key (str): The key for the context variable.\n        value (T): The value to set for the context variable.\n\n    Returns:\n        Token[T]: A token representing the context variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is None:\n        context_var = ContextVar(key, default=None)\n        self._scope_context[key] = context_var\n    return context_var.set(value)\n
","boost":0.5},{"location":"api/faststream/utils/Depends/","title":"Depends","text":"","boost":0.5},{"location":"api/faststream/utils/Depends/#fast_depends.use.Depends","title":"fast_depends.use.Depends","text":"
Depends(\n    dependency: Callable[P, T],\n    *,\n    use_cache: bool = True,\n    cast: bool = True\n) -> Any\n
Source code in fast_depends/use.py
def Depends(\n    dependency: Callable[P, T],\n    *,\n    use_cache: bool = True,\n    cast: bool = True,\n) -> Any:\n    return model.Depends(\n        dependency=dependency,\n        use_cache=use_cache,\n        cast=cast,\n    )\n
","boost":0.5},{"location":"api/faststream/utils/Header/","title":"Header","text":"","boost":0.5},{"location":"api/faststream/utils/Header/#faststream.utils.Header","title":"faststream.utils.Header","text":"
Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.headers.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/","title":"NoCast","text":"","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast","title":"faststream.utils.NoCast","text":"
NoCast()\n

Bases: CustomField

A class that represents a custom field without casting.

METHOD DESCRIPTION __init__

Initializes the NoCast object.

use

Returns the provided keyword arguments as a dictionary.

Source code in faststream/utils/no_cast.py
def __init__(self) -> None:\n    super().__init__(cast=False)\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast.cast","title":"cast instance-attribute","text":"
cast: bool = cast\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast.param_name","title":"param_name instance-attribute","text":"
param_name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast.required","title":"required instance-attribute","text":"
required: bool = required\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast.set_param_name","title":"set_param_name","text":"
set_param_name(name: str) -> Cls\n
Source code in fast_depends/library/model.py
def set_param_name(self: Cls, name: str) -> Cls:\n    self.param_name = name\n    return self\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast.use","title":"use","text":"
use(**kwargs: Any) -> AnyDict\n

Return a dictionary containing the keyword arguments passed to the function.

PARAMETER DESCRIPTION **kwargs

Keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION AnyDict

Dictionary containing the keyword arguments

Source code in faststream/utils/no_cast.py
def use(self, **kwargs: Any) -> AnyDict:\n    \"\"\"Return a dictionary containing the keyword arguments passed to the function.\n\n    Args:\n        **kwargs: Keyword arguments\n\n    Returns:\n        Dictionary containing the keyword arguments\n    \"\"\"\n    return kwargs\n
","boost":0.5},{"location":"api/faststream/utils/Path/","title":"Path","text":"","boost":0.5},{"location":"api/faststream/utils/Path/#faststream.utils.Path","title":"faststream.utils.Path","text":"
Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.path.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/apply_types/","title":"apply_types","text":"","boost":0.5},{"location":"api/faststream/utils/apply_types/#fast_depends.use.inject","title":"fast_depends.use.inject","text":"
inject(\n    func: Optional[Callable[P, T]] = None,\n    *,\n    cast: bool = True,\n    extra_dependencies: Sequence[model.Depends] = (),\n    pydantic_config: Optional[ConfigDict] = None,\n    dependency_overrides_provider: Optional[\n        Any\n    ] = dependency_provider,\n    wrap_model: Callable[\n        [CallModel[P, T]], CallModel[P, T]\n    ] = lambda: x\n) -> Union[Callable[P, T], _InjectWrapper[P, T]]\n
Source code in fast_depends/use.py
def inject(\n    func: Optional[Callable[P, T]] = None,\n    *,\n    cast: bool = True,\n    extra_dependencies: Sequence[model.Depends] = (),\n    pydantic_config: Optional[ConfigDict] = None,\n    dependency_overrides_provider: Optional[Any] = dependency_provider,\n    wrap_model: Callable[[CallModel[P, T]], CallModel[P, T]] = lambda x: x,\n) -> Union[Callable[P, T], _InjectWrapper[P, T],]:\n    decorator = _wrap_inject(\n        dependency_overrides_provider=dependency_overrides_provider,\n        wrap_model=wrap_model,\n        extra_dependencies=extra_dependencies,\n        cast=cast,\n        pydantic_config=pydantic_config,\n    )\n\n    if func is None:\n        return decorator\n\n    else:\n        return decorator(func)\n
","boost":0.5},{"location":"api/faststream/utils/ast/find_ast_node/","title":"find_ast_node","text":"","boost":0.5},{"location":"api/faststream/utils/ast/find_ast_node/#faststream.utils.ast.find_ast_node","title":"faststream.utils.ast.find_ast_node","text":"
find_ast_node(\n    module: ast.Module, lineno: Optional[int]\n) -> Optional[ast.AST]\n
Source code in faststream/utils/ast.py
def find_ast_node(module: ast.Module, lineno: Optional[int]) -> Optional[ast.AST]:\n    if lineno is not None:  # pragma: no branch\n        for i in getattr(module, \"body\", ()):\n            if i.lineno == lineno:\n                return cast(ast.AST, i)\n\n            r = find_ast_node(i, lineno)\n            if r is not None:\n                return r\n\n    return None\n
","boost":0.5},{"location":"api/faststream/utils/ast/find_withitems/","title":"find_withitems","text":"","boost":0.5},{"location":"api/faststream/utils/ast/find_withitems/#faststream.utils.ast.find_withitems","title":"faststream.utils.ast.find_withitems","text":"
find_withitems(\n    node: Union[ast.With, ast.AsyncWith]\n) -> Iterator[ast.withitem]\n
Source code in faststream/utils/ast.py
def find_withitems(node: Union[ast.With, ast.AsyncWith]) -> Iterator[ast.withitem]:\n    if isinstance(node, (ast.With, ast.AsyncWith)):\n        yield from node.items\n\n    for i in getattr(node, \"body\", ()):\n        yield from find_withitems(i)\n
","boost":0.5},{"location":"api/faststream/utils/ast/get_withitem_calls/","title":"get_withitem_calls","text":"","boost":0.5},{"location":"api/faststream/utils/ast/get_withitem_calls/#faststream.utils.ast.get_withitem_calls","title":"faststream.utils.ast.get_withitem_calls","text":"
get_withitem_calls(\n    node: Union[ast.With, ast.AsyncWith]\n) -> List[str]\n
Source code in faststream/utils/ast.py
def get_withitem_calls(node: Union[ast.With, ast.AsyncWith]) -> List[str]:\n    return [\n        id\n        for i in find_withitems(node)\n        if (id := getattr(i.context_expr.func, \"id\", None))  # type: ignore[attr-defined]\n    ]\n
","boost":0.5},{"location":"api/faststream/utils/ast/is_contains_context_name/","title":"is_contains_context_name","text":"","boost":0.5},{"location":"api/faststream/utils/ast/is_contains_context_name/#faststream.utils.ast.is_contains_context_name","title":"faststream.utils.ast.is_contains_context_name","text":"
is_contains_context_name(scip_name: str, name: str) -> bool\n
Source code in faststream/utils/ast.py
def is_contains_context_name(scip_name: str, name: str) -> bool:\n    stack = traceback.extract_stack()[-3]\n    tree = read_source_ast(stack.filename)\n    node = cast(Union[ast.With, ast.AsyncWith], find_ast_node(tree, stack.lineno))\n    context_calls = get_withitem_calls(node)\n\n    try:\n        pos = context_calls.index(scip_name)\n    except ValueError:\n        pos = 1\n\n    return name in context_calls[pos:]\n
","boost":0.5},{"location":"api/faststream/utils/classes/Singleton/","title":"Singleton","text":"","boost":0.5},{"location":"api/faststream/utils/classes/Singleton/#faststream.utils.classes.Singleton","title":"faststream.utils.classes.Singleton","text":"

A class to implement the Singleton design pattern.

METHOD DESCRIPTION __new__

creates a new instance of the class if it doesn't exist, otherwise returns the existing instance

_drop

sets the instance to None, allowing a new instance to be created

","boost":0.5},{"location":"api/faststream/utils/context/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/utils/context/Context/#faststream.utils.context.Context","title":"faststream.utils.context.Context","text":"
Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/","title":"ContextRepo","text":"","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo","title":"faststream.utils.context.ContextRepo","text":"
ContextRepo()\n

Bases: Singleton

A class to represent a context repository.

METHOD DESCRIPTION __init__

initializes the ContextRepo object

set_global

sets a global context variable

reset_global

resets a global context variable

set_local

sets a local context variable

reset_local

resets a local context variable

get_local

gets the value of a local context variable

clear

clears the global and scope context

get

gets the value of a context variable

__getattr__

gets the value of a context variable using attribute access

context

gets the current context as a dictionary

scope

creates a context scope for a specific key and value

Initialize the class.

Source code in faststream/utils/context/main.py
def __init__(self) -> None:\n    \"\"\"Initialize the class.\n\n    Attributes:\n        _global_context : a dictionary representing the global context\n        _scope_context : a dictionary representing the scope context\n    \"\"\"\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.context","title":"context property","text":"
context: AnyDict\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.clear","title":"clear","text":"
clear() -> None\n
Source code in faststream/utils/context/main.py
def clear(self) -> None:\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.get","title":"get","text":"
get(key: str, default: Any = None) -> Any\n

Get the value associated with a key.

PARAMETER DESCRIPTION key

The key to retrieve the value for.

TYPE: str

RETURNS DESCRIPTION Any

The value associated with the key.

Source code in faststream/utils/context/main.py
def get(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value associated with a key.\n\n    Args:\n        key: The key to retrieve the value for.\n\n    Returns:\n        The value associated with the key.\n    \"\"\"\n    return self._global_context.get(key, self.get_local(key, default))\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.get_local","title":"get_local","text":"
get_local(key: str, default: Any = None) -> Any\n

Get the value of a local variable.

PARAMETER DESCRIPTION key

The key of the local variable to retrieve.

TYPE: str

RETURNS DESCRIPTION Any

The value of the local variable.

Source code in faststream/utils/context/main.py
def get_local(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value of a local variable.\n\n    Args:\n        key: The key of the local variable to retrieve.\n\n    Returns:\n        The value of the local variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is not None:  # pragma: no branch\n        return context_var.get()\n    else:\n        return default\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.reset_global","title":"reset_global","text":"
reset_global(key: str) -> None\n

Resets a key in the global context.

PARAMETER DESCRIPTION key

The key to reset in the global context.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_global(self, key: str) -> None:\n    \"\"\"Resets a key in the global context.\n\n    Args:\n        key (str): The key to reset in the global context.\n\n    Returns:\n        None\n    \"\"\"\n    self._global_context.pop(key, None)\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.reset_local","title":"reset_local","text":"
reset_local(key: str, tag: Token[Any]) -> None\n

Resets the local context for a given key.

PARAMETER DESCRIPTION key

The key to reset the local context for.

TYPE: str

tag

The tag associated with the local context.

TYPE: Token[Any]

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_local(self, key: str, tag: \"Token[Any]\") -> None:\n    \"\"\"Resets the local context for a given key.\n\n    Args:\n        key (str): The key to reset the local context for.\n        tag (Token[Any]): The tag associated with the local context.\n\n    Returns:\n        None\n    \"\"\"\n    self._scope_context[key].reset(tag)\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.resolve","title":"resolve","text":"
resolve(argument: str) -> Any\n

Resolve the context of an argument.

PARAMETER DESCRIPTION argument

A string representing the argument.

TYPE: str

RETURNS DESCRIPTION Any

The resolved context of the argument.

RAISES DESCRIPTION AttributeError

If the attribute does not exist in the context.

Source code in faststream/utils/context/main.py
def resolve(self, argument: str) -> Any:\n    \"\"\"Resolve the context of an argument.\n\n    Args:\n        argument: A string representing the argument.\n\n    Returns:\n        The resolved context of the argument.\n\n    Raises:\n        AttributeError: If the attribute does not exist in the context.\n    \"\"\"\n    first, *keys = argument.split(\".\")\n\n    if (v := self.get(first, _empty)) is _empty:\n        raise KeyError(f\"`{self.context}` does not contains `{first}` key\")\n\n    for i in keys:\n        if isinstance(v, Mapping):\n            v = v[i]\n        else:\n            v = getattr(v, i)\n    return v\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.scope","title":"scope","text":"
scope(key: str, value: Any) -> Iterator[None]\n

Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.

PARAMETER DESCRIPTION key

The key of the local variable

TYPE: str

value

The value to set the local variable to

TYPE: Any

YIELDS DESCRIPTION Iterator[None]

None

RETURNS DESCRIPTION Iterator[None]

An iterator that yields None

Source code in faststream/utils/context/main.py
@contextmanager\ndef scope(self, key: str, value: Any) -> Iterator[None]:\n    \"\"\"Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.\n\n    Args:\n        key: The key of the local variable\n        value: The value to set the local variable to\n\n    Yields:\n        None\n\n    Returns:\n        An iterator that yields None\n    \"\"\"\n    token = self.set_local(key, value)\n    try:\n        yield\n    finally:\n        self.reset_local(key, token)\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.set_global","title":"set_global","text":"
set_global(key: str, v: Any) -> None\n

Sets a value in the global context.

PARAMETER DESCRIPTION key

The key to set in the global context.

TYPE: str

v

The value to set.

TYPE: Any

RETURNS DESCRIPTION None

None.

Source code in faststream/utils/context/main.py
def set_global(self, key: str, v: Any) -> None:\n    \"\"\"Sets a value in the global context.\n\n    Args:\n        key: The key to set in the global context.\n        v: The value to set.\n\n    Returns:\n        None.\n    \"\"\"\n    self._global_context[key] = v\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.set_local","title":"set_local","text":"
set_local(key: str, value: T) -> Token[T]\n

Set a local context variable.

PARAMETER DESCRIPTION key

The key for the context variable.

TYPE: str

value

The value to set for the context variable.

TYPE: T

RETURNS DESCRIPTION Token[T]

Token[T]: A token representing the context variable.

Source code in faststream/utils/context/main.py
def set_local(self, key: str, value: T) -> \"Token[T]\":\n    \"\"\"Set a local context variable.\n\n    Args:\n        key (str): The key for the context variable.\n        value (T): The value to set for the context variable.\n\n    Returns:\n        Token[T]: A token representing the context variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is None:\n        context_var = ContextVar(key, default=None)\n        self._scope_context[key] = context_var\n    return context_var.set(value)\n
","boost":0.5},{"location":"api/faststream/utils/context/Header/","title":"Header","text":"","boost":0.5},{"location":"api/faststream/utils/context/Header/#faststream.utils.context.Header","title":"faststream.utils.context.Header","text":"
Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.headers.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/Path/","title":"Path","text":"","boost":0.5},{"location":"api/faststream/utils/context/Path/#faststream.utils.context.Path","title":"faststream.utils.context.Path","text":"
Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.path.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/builders/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/utils/context/builders/Context/#faststream.utils.context.builders.Context","title":"faststream.utils.context.builders.Context","text":"
Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/builders/Header/","title":"Header","text":"","boost":0.5},{"location":"api/faststream/utils/context/builders/Header/#faststream.utils.context.builders.Header","title":"faststream.utils.context.builders.Header","text":"
Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.headers.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/builders/Path/","title":"Path","text":"","boost":0.5},{"location":"api/faststream/utils/context/builders/Path/#faststream.utils.context.builders.Path","title":"faststream.utils.context.builders.Path","text":"
Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.path.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/","title":"ContextRepo","text":"","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo","title":"faststream.utils.context.main.ContextRepo","text":"
ContextRepo()\n

Bases: Singleton

A class to represent a context repository.

METHOD DESCRIPTION __init__

initializes the ContextRepo object

set_global

sets a global context variable

reset_global

resets a global context variable

set_local

sets a local context variable

reset_local

resets a local context variable

get_local

gets the value of a local context variable

clear

clears the global and scope context

get

gets the value of a context variable

__getattr__

gets the value of a context variable using attribute access

context

gets the current context as a dictionary

scope

creates a context scope for a specific key and value

Initialize the class.

Source code in faststream/utils/context/main.py
def __init__(self) -> None:\n    \"\"\"Initialize the class.\n\n    Attributes:\n        _global_context : a dictionary representing the global context\n        _scope_context : a dictionary representing the scope context\n    \"\"\"\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.context","title":"context property","text":"
context: AnyDict\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.clear","title":"clear","text":"
clear() -> None\n
Source code in faststream/utils/context/main.py
def clear(self) -> None:\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.get","title":"get","text":"
get(key: str, default: Any = None) -> Any\n

Get the value associated with a key.

PARAMETER DESCRIPTION key

The key to retrieve the value for.

TYPE: str

RETURNS DESCRIPTION Any

The value associated with the key.

Source code in faststream/utils/context/main.py
def get(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value associated with a key.\n\n    Args:\n        key: The key to retrieve the value for.\n\n    Returns:\n        The value associated with the key.\n    \"\"\"\n    return self._global_context.get(key, self.get_local(key, default))\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.get_local","title":"get_local","text":"
get_local(key: str, default: Any = None) -> Any\n

Get the value of a local variable.

PARAMETER DESCRIPTION key

The key of the local variable to retrieve.

TYPE: str

RETURNS DESCRIPTION Any

The value of the local variable.

Source code in faststream/utils/context/main.py
def get_local(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value of a local variable.\n\n    Args:\n        key: The key of the local variable to retrieve.\n\n    Returns:\n        The value of the local variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is not None:  # pragma: no branch\n        return context_var.get()\n    else:\n        return default\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.reset_global","title":"reset_global","text":"
reset_global(key: str) -> None\n

Resets a key in the global context.

PARAMETER DESCRIPTION key

The key to reset in the global context.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_global(self, key: str) -> None:\n    \"\"\"Resets a key in the global context.\n\n    Args:\n        key (str): The key to reset in the global context.\n\n    Returns:\n        None\n    \"\"\"\n    self._global_context.pop(key, None)\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.reset_local","title":"reset_local","text":"
reset_local(key: str, tag: Token[Any]) -> None\n

Resets the local context for a given key.

PARAMETER DESCRIPTION key

The key to reset the local context for.

TYPE: str

tag

The tag associated with the local context.

TYPE: Token[Any]

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_local(self, key: str, tag: \"Token[Any]\") -> None:\n    \"\"\"Resets the local context for a given key.\n\n    Args:\n        key (str): The key to reset the local context for.\n        tag (Token[Any]): The tag associated with the local context.\n\n    Returns:\n        None\n    \"\"\"\n    self._scope_context[key].reset(tag)\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.resolve","title":"resolve","text":"
resolve(argument: str) -> Any\n

Resolve the context of an argument.

PARAMETER DESCRIPTION argument

A string representing the argument.

TYPE: str

RETURNS DESCRIPTION Any

The resolved context of the argument.

RAISES DESCRIPTION AttributeError

If the attribute does not exist in the context.

Source code in faststream/utils/context/main.py
def resolve(self, argument: str) -> Any:\n    \"\"\"Resolve the context of an argument.\n\n    Args:\n        argument: A string representing the argument.\n\n    Returns:\n        The resolved context of the argument.\n\n    Raises:\n        AttributeError: If the attribute does not exist in the context.\n    \"\"\"\n    first, *keys = argument.split(\".\")\n\n    if (v := self.get(first, _empty)) is _empty:\n        raise KeyError(f\"`{self.context}` does not contains `{first}` key\")\n\n    for i in keys:\n        if isinstance(v, Mapping):\n            v = v[i]\n        else:\n            v = getattr(v, i)\n    return v\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.scope","title":"scope","text":"
scope(key: str, value: Any) -> Iterator[None]\n

Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.

PARAMETER DESCRIPTION key

The key of the local variable

TYPE: str

value

The value to set the local variable to

TYPE: Any

YIELDS DESCRIPTION Iterator[None]

None

RETURNS DESCRIPTION Iterator[None]

An iterator that yields None

Source code in faststream/utils/context/main.py
@contextmanager\ndef scope(self, key: str, value: Any) -> Iterator[None]:\n    \"\"\"Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.\n\n    Args:\n        key: The key of the local variable\n        value: The value to set the local variable to\n\n    Yields:\n        None\n\n    Returns:\n        An iterator that yields None\n    \"\"\"\n    token = self.set_local(key, value)\n    try:\n        yield\n    finally:\n        self.reset_local(key, token)\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.set_global","title":"set_global","text":"
set_global(key: str, v: Any) -> None\n

Sets a value in the global context.

PARAMETER DESCRIPTION key

The key to set in the global context.

TYPE: str

v

The value to set.

TYPE: Any

RETURNS DESCRIPTION None

None.

Source code in faststream/utils/context/main.py
def set_global(self, key: str, v: Any) -> None:\n    \"\"\"Sets a value in the global context.\n\n    Args:\n        key: The key to set in the global context.\n        v: The value to set.\n\n    Returns:\n        None.\n    \"\"\"\n    self._global_context[key] = v\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.set_local","title":"set_local","text":"
set_local(key: str, value: T) -> Token[T]\n

Set a local context variable.

PARAMETER DESCRIPTION key

The key for the context variable.

TYPE: str

value

The value to set for the context variable.

TYPE: T

RETURNS DESCRIPTION Token[T]

Token[T]: A token representing the context variable.

Source code in faststream/utils/context/main.py
def set_local(self, key: str, value: T) -> \"Token[T]\":\n    \"\"\"Set a local context variable.\n\n    Args:\n        key (str): The key for the context variable.\n        value (T): The value to set for the context variable.\n\n    Returns:\n        Token[T]: A token representing the context variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is None:\n        context_var = ContextVar(key, default=None)\n        self._scope_context[key] = context_var\n    return context_var.set(value)\n
","boost":0.5},{"location":"api/faststream/utils/context/path/compile_path/","title":"compile_path","text":"","boost":0.5},{"location":"api/faststream/utils/context/path/compile_path/#faststream.utils.context.path.compile_path","title":"faststream.utils.context.path.compile_path","text":"
compile_path(\n    path: str, replace_symbol: str\n) -> Tuple[Optional[Pattern[str]], str]\n
Source code in faststream/utils/context/path.py
def compile_path(\n    path: str,\n    replace_symbol: str,\n) -> Tuple[Optional[Pattern[str]], str]:\n    path_regex = \"^\"\n    path_format = \"\"\n\n    idx = 0\n    params = set()\n    duplicated_params = set()\n    for match in PARAM_REGEX.finditer(path):\n        param_name = match.groups(\"str\")[0]\n\n        path_regex += re.escape(path[idx : match.start()])\n        path_regex += f\"(?P<{param_name.replace('+', '')}>[^/]+)\"\n\n        path_format += path[idx : match.start()]\n        path_format += replace_symbol\n\n        if param_name in params:\n            duplicated_params.add(param_name)\n        else:\n            params.add(param_name)\n\n        idx = match.end()\n\n    if duplicated_params:\n        names = \", \".join(sorted(duplicated_params))\n        ending = \"s\" if len(duplicated_params) > 1 else \"\"\n        raise ValueError(f\"Duplicated param name{ending} {names} at path {path}\")\n\n    if idx == 0:\n        regex = None\n    else:\n        path_regex += re.escape(path[idx:]) + \"$\"\n        regex = re.compile(path_regex)\n\n    path_format += path[idx:]\n    return regex, path_format\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context","title":"faststream.utils.context.types.Context","text":"
Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n    prefix: str = \"\"\n)\n

Bases: CustomField

A class to represent a context.

METHOD DESCRIPTION __init__

constructor method

use

method to use the context

Initialize the object.

PARAMETER DESCRIPTION real_name

The real name of the object.

TYPE: str DEFAULT: ''

cast

Whether to cast the object.

TYPE: bool DEFAULT: False

default

The default value of the object.

TYPE: Any DEFAULT: _empty

RAISES DESCRIPTION TypeError

If the default value is not provided.

Source code in faststream/utils/context/types.py
def __init__(\n    self,\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n    prefix: str = \"\",\n) -> None:\n    \"\"\"Initialize the object.\n\n    Args:\n        real_name: The real name of the object.\n        cast: Whether to cast the object.\n        default: The default value of the object.\n\n    Raises:\n        TypeError: If the default value is not provided.\n    \"\"\"\n    self.name = real_name\n    self.default = default\n    self.prefix = prefix\n    super().__init__(\n        cast=cast,\n        required=(default is _empty),\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.cast","title":"cast instance-attribute","text":"
cast: bool = cast\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.default","title":"default instance-attribute","text":"
default = default\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.name","title":"name instance-attribute","text":"
name = real_name\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.param_name","title":"param_name instance-attribute","text":"
param_name: str\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.required","title":"required instance-attribute","text":"
required: bool = required\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.set_param_name","title":"set_param_name","text":"
set_param_name(name: str) -> Cls\n
Source code in fast_depends/library/model.py
def set_param_name(self: Cls, name: str) -> Cls:\n    self.param_name = name\n    return self\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.use","title":"use","text":"
use(**kwargs: Any) -> AnyDict\n

Use the given keyword arguments.

PARAMETER DESCRIPTION **kwargs

Keyword arguments to be used

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION AnyDict

A dictionary containing the updated keyword arguments

RAISES DESCRIPTION KeyError

If the parameter name is not found in the keyword arguments

AttributeError

If the parameter name is not a valid attribute

Source code in faststream/utils/context/types.py
def use(self, /, **kwargs: Any) -> AnyDict:\n    \"\"\"Use the given keyword arguments.\n\n    Args:\n        **kwargs: Keyword arguments to be used\n\n    Returns:\n        A dictionary containing the updated keyword arguments\n\n    Raises:\n        KeyError: If the parameter name is not found in the keyword arguments\n        AttributeError: If the parameter name is not a valid attribute\n    \"\"\"\n    name = f\"{self.prefix}{self.name or self.param_name}\"\n\n    try:\n        kwargs[self.param_name] = context.resolve(name)\n    except (KeyError, AttributeError):\n        if self.required is False:\n            kwargs[self.param_name] = self.default\n\n    return kwargs\n
","boost":0.5},{"location":"api/faststream/utils/data/filter_by_dict/","title":"filter_by_dict","text":"","boost":0.5},{"location":"api/faststream/utils/data/filter_by_dict/#faststream.utils.data.filter_by_dict","title":"faststream.utils.data.filter_by_dict","text":"
filter_by_dict(\n    typed_dict: Type[TypedDictCls], data: AnyDict\n) -> TypedDictCls\n

Filter a dictionary based on a typed dictionary.

PARAMETER DESCRIPTION typed_dict

The typed dictionary to filter by.

TYPE: Type[TypedDictCls]

data

The dictionary to filter.

TYPE: AnyDict

RETURNS DESCRIPTION TypedDictCls

A new instance of the typed dictionary with only the keys present in the data dictionary.

Source code in faststream/utils/data.py
def filter_by_dict(typed_dict: Type[TypedDictCls], data: AnyDict) -> TypedDictCls:\n    \"\"\"Filter a dictionary based on a typed dictionary.\n\n    Args:\n        typed_dict: The typed dictionary to filter by.\n        data: The dictionary to filter.\n\n    Returns:\n        A new instance of the typed dictionary with only the keys present in the data dictionary.\n    \"\"\"\n    annotations = typed_dict.__annotations__\n    return typed_dict(  # type: ignore\n        {k: v for k, v in data.items() if k in annotations}\n    )\n
","boost":0.5},{"location":"api/faststream/utils/functions/call_or_await/","title":"call_or_await","text":"","boost":0.5},{"location":"api/faststream/utils/functions/call_or_await/#fast_depends.utils.run_async","title":"fast_depends.utils.run_async async","text":"
run_async(\n    func: Union[Callable[P, T], Callable[P, Awaitable[T]]],\n    *args: P.args,\n    **kwargs: P.kwargs\n) -> T\n
Source code in fast_depends/utils.py
async def run_async(\n    func: Union[\n        Callable[P, T],\n        Callable[P, Awaitable[T]],\n    ],\n    *args: P.args,\n    **kwargs: P.kwargs,\n) -> T:\n    if is_coroutine_callable(func):\n        return await cast(Callable[P, Awaitable[T]], func)(*args, **kwargs)\n    else:\n        return await run_in_threadpool(cast(Callable[P, T], func), *args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/utils/functions/drop_response_type/","title":"drop_response_type","text":"","boost":0.5},{"location":"api/faststream/utils/functions/drop_response_type/#faststream.utils.functions.drop_response_type","title":"faststream.utils.functions.drop_response_type","text":"
drop_response_type(\n    model: CallModel[F_Spec, F_Return]\n) -> CallModel[F_Spec, F_Return]\n
Source code in faststream/utils/functions.py
def drop_response_type(\n    model: CallModel[F_Spec, F_Return]\n) -> CallModel[F_Spec, F_Return]:\n    model.response_model = None\n    return model\n
","boost":0.5},{"location":"api/faststream/utils/functions/fake_context/","title":"fake_context","text":"","boost":0.5},{"location":"api/faststream/utils/functions/fake_context/#faststream.utils.functions.fake_context","title":"faststream.utils.functions.fake_context async","text":"
fake_context(\n    *args: Any, **kwargs: Any\n) -> AsyncIterator[None]\n
Source code in faststream/utils/functions.py
@asynccontextmanager\nasync def fake_context(*args: Any, **kwargs: Any) -> AsyncIterator[None]:\n    yield None\n
","boost":0.5},{"location":"api/faststream/utils/functions/get_function_positional_arguments/","title":"get_function_positional_arguments","text":"","boost":0.5},{"location":"api/faststream/utils/functions/get_function_positional_arguments/#faststream.utils.functions.get_function_positional_arguments","title":"faststream.utils.functions.get_function_positional_arguments","text":"
get_function_positional_arguments(\n    func: AnyCallable,\n) -> List[str]\n

Get the positional arguments of a function.

PARAMETER DESCRIPTION func

The function to get the positional arguments from.

TYPE: AnyCallable

RETURNS DESCRIPTION List[str]

A list of strings representing the names of the positional arguments.

Source code in faststream/utils/functions.py
def get_function_positional_arguments(func: AnyCallable) -> List[str]:\n    \"\"\"Get the positional arguments of a function.\n\n    Args:\n        func: The function to get the positional arguments from.\n\n    Returns:\n        A list of strings representing the names of the positional arguments.\n    \"\"\"\n    signature = inspect.signature(func)\n\n    arg_kinds = (\n        inspect.Parameter.POSITIONAL_ONLY,\n        inspect.Parameter.POSITIONAL_OR_KEYWORD,\n    )\n\n    return [\n        param.name for param in signature.parameters.values() if param.kind in arg_kinds\n    ]\n
","boost":0.5},{"location":"api/faststream/utils/functions/timeout_scope/","title":"timeout_scope","text":"","boost":0.5},{"location":"api/faststream/utils/functions/timeout_scope/#faststream.utils.functions.timeout_scope","title":"faststream.utils.functions.timeout_scope","text":"
timeout_scope(\n    timeout: Optional[float] = 30,\n    raise_timeout: bool = False,\n) -> ContextManager[anyio.CancelScope]\n
Source code in faststream/utils/functions.py
def timeout_scope(\n    timeout: Optional[float] = 30,\n    raise_timeout: bool = False,\n) -> ContextManager[anyio.CancelScope]:\n    scope: Callable[[Optional[float]], ContextManager[anyio.CancelScope]]\n    if raise_timeout:\n        scope = anyio.fail_after\n    else:\n        scope = anyio.move_on_after\n\n    return scope(timeout)\n
","boost":0.5},{"location":"api/faststream/utils/functions/to_async/","title":"to_async","text":"","boost":0.5},{"location":"api/faststream/utils/functions/to_async/#faststream.utils.functions.to_async","title":"faststream.utils.functions.to_async","text":"
to_async(\n    func: Union[\n        Callable[F_Spec, F_Return],\n        Callable[F_Spec, Awaitable[F_Return]],\n    ]\n) -> Callable[F_Spec, Awaitable[F_Return]]\n

Converts a synchronous function to an asynchronous function.

PARAMETER DESCRIPTION func

The synchronous function to be converted.

TYPE: Union[Callable[F_Spec, F_Return], Callable[F_Spec, Awaitable[F_Return]]]

RETURNS DESCRIPTION Callable[F_Spec, Awaitable[F_Return]]

The asynchronous version of the input function.

Source code in faststream/utils/functions.py
def to_async(\n    func: Union[\n        Callable[F_Spec, F_Return],\n        Callable[F_Spec, Awaitable[F_Return]],\n    ]\n) -> Callable[F_Spec, Awaitable[F_Return]]:\n    \"\"\"Converts a synchronous function to an asynchronous function.\n\n    Args:\n        func: The synchronous function to be converted.\n\n    Returns:\n        The asynchronous version of the input function.\n    \"\"\"\n\n    @wraps(func)\n    async def to_async_wrapper(*args: F_Spec.args, **kwargs: F_Spec.kwargs) -> F_Return:\n        \"\"\"Wraps a function to make it asynchronous.\n\n        Args:\n            func: The function to be wrapped\n            args: Positional arguments to be passed to the function\n            kwargs: Keyword arguments to be passed to the function\n\n        Returns:\n            The result of the wrapped function\n\n        Raises:\n            Any exceptions raised by the wrapped function\n        \"\"\"\n        return await call_or_await(func, *args, **kwargs)\n\n    return to_async_wrapper\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/","title":"NoCast","text":"","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast","title":"faststream.utils.no_cast.NoCast","text":"
NoCast()\n

Bases: CustomField

A class that represents a custom field without casting.

METHOD DESCRIPTION __init__

Initializes the NoCast object.

use

Returns the provided keyword arguments as a dictionary.

Source code in faststream/utils/no_cast.py
def __init__(self) -> None:\n    super().__init__(cast=False)\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast.cast","title":"cast instance-attribute","text":"
cast: bool = cast\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast.param_name","title":"param_name instance-attribute","text":"
param_name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast.required","title":"required instance-attribute","text":"
required: bool = required\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast.set_param_name","title":"set_param_name","text":"
set_param_name(name: str) -> Cls\n
Source code in fast_depends/library/model.py
def set_param_name(self: Cls, name: str) -> Cls:\n    self.param_name = name\n    return self\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast.use","title":"use","text":"
use(**kwargs: Any) -> AnyDict\n

Return a dictionary containing the keyword arguments passed to the function.

PARAMETER DESCRIPTION **kwargs

Keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION AnyDict

Dictionary containing the keyword arguments

Source code in faststream/utils/no_cast.py
def use(self, **kwargs: Any) -> AnyDict:\n    \"\"\"Return a dictionary containing the keyword arguments passed to the function.\n\n    Args:\n        **kwargs: Keyword arguments\n\n    Returns:\n        Dictionary containing the keyword arguments\n    \"\"\"\n    return kwargs\n
","boost":0.5},{"location":"getting-started/","title":"QUICK START","text":"

Install using pip:

KafkaRabbitMQNATSRedis
pip install \"faststream[kafka]\"\n

Tip

To start a new project, we need a test broker container

docker run -d --rm -p 9092:9092 --name test-mq \\\n-e KAFKA_ENABLE_KRAFT=yes \\\n-e KAFKA_CFG_NODE_ID=1 \\\n-e KAFKA_CFG_PROCESS_ROLES=broker,controller \\\n-e KAFKA_CFG_CONTROLLER_LISTENER_NAMES=CONTROLLER \\\n-e KAFKA_CFG_LISTENERS=PLAINTEXT://:9092,CONTROLLER://:9093 \\\n-e KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP=CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT \\\n-e KAFKA_CFG_ADVERTISED_LISTENERS=PLAINTEXT://127.0.0.1:9092 \\\n-e KAFKA_BROKER_ID=1 \\\n-e KAFKA_CFG_CONTROLLER_QUORUM_VOTERS=1@kafka:9093 \\\n-e ALLOW_PLAINTEXT_LISTENER=yes \\\nbitnami/kafka:3.5.0\n

pip install \"faststream[rabbit]\"\n

Tip

To start a new project, we need a test broker container

docker run -d --rm -p 5672:5672 --name test-mq rabbitmq:alpine\n

pip install \"faststream[nats]\"\n

Tip

To start a new project, we need a test broker container

bash docker run -d --rm -p 4222:4222 --name test-mq nats -js\n

pip install \"faststream[redis]\"\n

Tip

To start a new project, we need a test broker container

bash docker run -d --rm -p 6379:6379 --name test-mq redis\n

","boost":10},{"location":"getting-started/#basic-usage","title":"Basic Usage","text":"

To create a basic application, add the following code to a new file (e.g. serve.py):

KafkaRabbitMQNATSRedis serve.py
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n
serve.py
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\n\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n
serve.py
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\n\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n
serve.py
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\n\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n

And just run this command:

faststream run serve:app\n

After running the command, you should see the following output:

Enjoy your new development experience!

Don't forget to stop the test broker container
docker container stop test-mq\n
","boost":10},{"location":"getting-started/logging/","title":"Application and Access Logging","text":"

FastStream uses two already configured loggers:

","boost":10},{"location":"getting-started/logging/#logging-requests","title":"Logging Requests","text":"

To log requests, it is strongly recommended to use the access_logger of your broker, as it is available from the Context of your application.

from faststream import Logger\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker()\n\n@broker.subscriber(\"test\")\nasync def func(logger: Logger):\n    logger.info(\"message received\")\n

This approach offers several advantages:

","boost":10},{"location":"getting-started/logging/#logging-levels","title":"Logging Levels","text":"

If you use the FastStream CLI, you can change the current logging level of the entire application directly from the command line.

The --log-level flag sets the current logging level for both the broker and the FastStream app. This allows you to configure the levels of not only the default loggers but also your custom loggers, if you use them inside FastStream.

faststream run serve:app --log-level debug\n

If you want to completely disable the default logging of FastStream, you can set logger=None

from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(logger=None)     # Disables broker logs\napp = FastStream(broker, logger=None)  # Disables application logs\n

Warning

Be careful: the logger that you get from the context will also have the value None if you turn off broker logging.

If you don't want to lose access to the `logger' inside your context but want to disable the default logs of FastStream, you can lower the level of logs that the broker publishes itself.

import logging\nfrom faststream.rabbit import RabbitBroker\n\n# Sets the broker logs to the DEBUG level\nbroker = RabbitBroker(log_level=logging.DEBUG)\n
","boost":10},{"location":"getting-started/logging/#formatting-logs","title":"Formatting Logs","text":"

If you are not satisfied with the current format of your application logs, you can change it directly in your broker's constructor.

from faststream.rabbit import RabbitBroker\nbroker = RabbitBroker(log_fmt=\"%(asctime)s %(levelname)s - %(message)s\")\n
","boost":10},{"location":"getting-started/logging/#logger-access","title":"Logger Access","text":"

If you want to override default logger's behavior, you can access them directly via logging.

import logging\nlogger = logging.getLogger(\"faststream\")\naccess_logger = logging.getLogger(\"faststream.access\")\n

Or you can import them from FastStream.

from faststream.log import access_logger, logger\n
","boost":10},{"location":"getting-started/logging/#using-your-own-loggers","title":"Using Your Own Loggers","text":"

Since FastStream works with the standard logging.Logger object, you can initiate an application and a broker using your own logger.

import logging\nfrom faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nlogger = logging.getLogger(\"my_logger\")\n\nbroker = RabbitBroker(logger=logger)\napp = FastStream(broker, logger=logger)\n

Note

Doing this, you doesn't change the CLI logs behavior (multiprocessing and hot reload logs). This was done to keep your log storage clear of unnecessary stuff.

This logger will be used only for FastStream and StreamBroker service messages and will be passed to your function through the Context.

By doing this, you will lose information about the context of the current request. However, you can retrieve it directly from the context anywhere in your code.

from faststream import context\nlog_context: dict[str, str] = context.get_local(\"log_context\")\n

This way, all broker handlers can get access to your broker logger right from the context:

from faststream import Logger\n\n@broker.subscriber(...)\nasync def handler(\n    msg,\n    logger: Logger,  # <-- YOUR logger here\n):\n    logger.info(msg)\n
","boost":10},{"location":"getting-started/logging/#structlog-example","title":"Structlog Example","text":"

Structlog is a production-ready logging solution for Python. It can be easely integrated with any log storage system, making it suitable for use in production projects.

Here is a quick tutorial on integrating Structlog with FastStream:

Start with the Structlog guide example:

import sys\nimport structlog\n\nshared_processors = [\n    structlog.processors.add_log_level,\n    structlog.processors.StackInfoRenderer(),\n    structlog.dev.set_exc_info,\n    structlog.processors.TimeStamper(fmt=\"iso\"),\n]\n\nif sys.stderr.isatty():\n    # terminal session\n    processors = shared_processors + [\n        structlog.dev.ConsoleRenderer()\n    ]\nelse:\n    # Docker container session\n    processors = shared_processors + [\n        structlog.processors.dict_tracebacks,\n        structlog.processors.JSONRenderer(),\n    ]\n\nstructlog.configure(\n    processors=processors,\n    logger_factory=structlog.PrintLoggerFactory(),\n    cache_logger_on_first_use=False,\n)\n\nlogger = structlog.get_logger()\n

We created a logger that prints messages to the console in a user-friendly format during development and uses JSON-formatted logs in production.

To integrate this logger with our FastStream application, we just need to access it through context information and pass it to our objects:

import logging\n\nimport structlog\n\nfrom faststream import FastStream, context\nfrom faststream.kafka import KafkaBroker\n\ndef merge_contextvars(\n    logger: structlog.types.WrappedLogger,\n    method_name: str,\n    event_dict: structlog.types.EventDict,\n) -> structlog.types.EventDict:\n    event_dict[\"extra\"] = event_dict.get(\n        \"extra\",\n        context.get(\"log_context\", {}),\n    )\n    return event_dict\n\nshared_processors = [\n    merge_contextvars,\n    ...\n]\n\n...\n\nbroker = KafkaBroker(logger=logger, log_level=logging.DEBUG)\napp = FastStream(broker, logger=logger)\n

And the job is done! Now you have a perfectly structured logs using Structlog.

","boost":10},{"location":"getting-started/asyncapi/custom/","title":"Customizing AsyncAPI Documentation for FastStream","text":"

In this guide, we will explore how to customize AsyncAPI documentation for your FastStream application. Whether you want to add custom app info, broker information, handlers, or fine-tune payload details, we'll walk you through each step.

","boost":10},{"location":"getting-started/asyncapi/custom/#prerequisites","title":"Prerequisites","text":"

Before we dive into customization, ensure you have a basic FastStream application up and running. If you haven't done that yet, let's setup a simple appication right now.

Copy the following code in your basic.py file:

from faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaMessage\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n@broker.publisher(\"output_data\")\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg):\n    # your processing logic\n    pass\n

Now, when you run

faststream docs serve basic:app\n
you should see the following documentation:

","boost":10},{"location":"getting-started/asyncapi/custom/#setup-custom-faststream-app-info","title":"Setup Custom FastStream App Info","text":"

Let's start by customizing the app information that appears in your AsyncAPI documentation. This is a great way to give your documentation a personal touch. Here's how:

  1. Locate the app configuration in your FastStream application.
  2. Update the title, version, and description fields to reflect your application's details.
  3. Save the changes.
  4. Serve your FastStream app documentation.

Copy the following code in your basic.py file, we have highligted the additional info passed to FastStream app:

from faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaMessage\nfrom faststream.asyncapi.schema import Contact, ExternalDocs, License, Tag\n\nbroker = KafkaBroker(\"localhost:9092\")\ndescription=\"\"\"# Title of the description\nThis description supports **Markdown** syntax\"\"\"\napp = FastStream(\n    broker,\n    title=\"My App\",\n    version=\"1.0.0\",\n    description=description,\n    license=License(name=\"MIT\", url=\"https://opensource.org/license/mit/\"),\n    terms_of_service=\"https://my-terms.com/\",\n    contact=Contact(name=\"support\", url=\"https://help.com/\"),\n)\n\n@broker.publisher(\"output_data\")\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg):\n    # your processing logic\n    pass\n

Now, when you run

faststream docs serve basic:app\n
you should see the following in your general app documentation:

Now, your documentation reflects your application's identity and purpose.

Note

The description field in the above example supports Markdown text.

","boost":10},{"location":"getting-started/asyncapi/custom/#setup-custom-broker-information","title":"Setup Custom Broker Information","text":"

The next step is to customize broker information. This helps users understand the messaging system your application uses. Follow these steps:

  1. Locate the broker configuration in your FastStream application.
  2. Update the description field.
  3. Update the asyncapi_url field with a non-sensitive URL if you want to conceal your broker's actual bootstrap server URL.
  4. Save the changes.
  5. Serve your FastStream app.

Copy the following code in your basic.py file, we have highligted the additional info passed to the FastStream app broker:

from faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaMessage\nfrom faststream.asyncapi.schema import Tag\n\nbroker = KafkaBroker(\n    \"localhost:9092\",\n    description=\"Kafka broker running locally\",\n    asyncapi_url=\"non-sensitive-url:9092\",\n)\napp = FastStream(broker)\n\n\n@broker.publisher(\"output_data\")\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg):\n    # your processing logic\n    pass\n

Now, when you run

faststream docs serve basic:app\n
you should see the description in your broker documentation:

Your AsyncAPI documentation now provides clear insights into the messaging infrastructure you're using.

","boost":10},{"location":"getting-started/asyncapi/custom/#setup-custom-handler-information","title":"Setup Custom Handler Information","text":"

Customizing handler information helps users comprehend the purpose and behavior of each message handler. Here's how to do it:

  1. Navigate to your handler definitions in your FastStream application.
  2. Add descriptions to each handler using description field.
  3. For subscriber, consumer function's docstring can be used as description.
  4. Add titles to each handler using title field adhering to URI format.
  5. Add publishing schema to publisher handler using schema field.
  6. Save the changes.
  7. Serve your FastStream app.

Copy the following code in your basic.py file, we have highligted the additional info passed to the FastStream app handlers:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaMessage\n\n\nclass DataBasic(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.publisher(\n    \"output_data\",\n    description=\"My publisher description\",\n    title=\"output_data:Produce\",\n    schema=DataBasic,\n)\n@broker.subscriber(\n    \"input_data\", title=\"input_data:Consume\"\n)\nasync def on_input_data(msg):\n    \"\"\"Consumer function\n\n    Args:\n        msg: input msg\n    \"\"\"\n    # your processing logic\n    pass\n

Now, when you run

faststream docs serve basic:app\n
you should see the descriptions in your handlers:

Now, your documentation is enriched with meaningful details about each message handler.

","boost":10},{"location":"getting-started/asyncapi/custom/#setup-payload-information-via-pydantic-model","title":"Setup Payload Information via Pydantic Model","text":"

To describe your message payload effectively, you can use Pydantic models. Here's how:

  1. Define Pydantic models for your message payloads.
  2. Annotate these models with descriptions and examples.
  3. Use these models as argument types or return types in your handlers.
  4. Save the changes.
  5. Serve your FastStream app.

Copy the following code in your basic.py file, we have highligted the creation of payload info and you can see it being passed to the return type and the msg argument type in the on_input_data function:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\n\nclass DataBasic(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.publisher(\"output_data\")\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: DataBasic) -> DataBasic:\n    # your processing logic\n    pass\n

Now, when you run

faststream docs serve basic:app\n
you should see the payload schema described in your documentation:

Your AsyncAPI documentation now showcases well-structured payload information.

","boost":10},{"location":"getting-started/asyncapi/custom/#generate-schemajson-customize-and-serve-it","title":"Generate Schema.json, customize and serve it","text":"

To take customization to the next level, you can manually modify the schema.json file. Follow these steps:

  1. Generate the initial schema.json by running
    faststream docs gen basic:app\n
  2. Manually edit the asyncapi.json file to add custom fields, descriptions, and details.
  3. Save your changes.
  4. Serve your FastStream app with the updated asyncapi.json by running
    faststream docs serve asyncapi.json\n

Now, you have fine-tuned control over your AsyncAPI documentation.

","boost":10},{"location":"getting-started/asyncapi/custom/#conclusion","title":"Conclusion","text":"

Customizing AsyncAPI documentation for your FastStream application not only enhances its appearance but also provides valuable insights to users. With these steps, you can create documentation that's not only informative but also uniquely yours.

Happy coding with your customized FastStream AsyncAPI documentation!

","boost":10},{"location":"getting-started/asyncapi/export/","title":"How to Generate and Serve AsyncAPI Documentation","text":"

In this guide, let's explore how to generate and serve AsyncAPI documentation for our FastStream application.

","boost":10},{"location":"getting-started/asyncapi/export/#writing-the-faststream-application","title":"Writing the FastStream Application","text":"

Here's an example Python application using FastStream that consumes data from a topic, increments the value, and outputs the data to another topic. Save it in a file called basic.py.

basic.py
from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n\n\nclass DataBasic(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.publisher(\"output_data\")\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: DataBasic, logger: Logger) -> DataBasic:\n    logger.info(msg)\n    return DataBasic(data=msg.data + 1.0)\n
","boost":10},{"location":"getting-started/asyncapi/export/#generating-the-asyncapi-specification","title":"Generating the AsyncAPI Specification","text":"

Now that we have a FastStream application, we can proceed with generating the AsyncAPI specification using a CLI command.

faststream docs gen basic:app\n

The above command will generate the AsyncAPI specification and save it in a file called asyncapi.json.

If you prefer yaml instead of json, please run the following command to generate asyncapi.yaml.

faststream docs gen --yaml basic:app\n

Tip

To generate the documentation in yaml format, please install the necessary dependency to work with YAML file format at first.

pip install PyYAML\n
","boost":10},{"location":"getting-started/asyncapi/hosting/","title":"Serving the AsyncAPI Documentation","text":"

FastStream provides a command to serve the AsyncAPI documentation.

Note

This feature requires an Internet connection to obtain the AsyncAPI HTML via CDN.

faststream docs serve basic:app\n

In the above command, we are providing the path in the format of python_module:FastStream. Alternatively, you can also specify asyncapi.json or asyncapi.yaml to serve the AsyncAPI documentation.

JSONYAML
faststream docs serve asyncapi.json\n
faststream docs serve asyncapi.yaml\n

After running the command, it should serve the AsyncAPI documentation on port 8000 and display the following logs in the terminal.

And you should be able to see the following page in your browser:

ShortExpand

Tip

The command also offers options to serve the documentation on a different host and port.

","boost":10},{"location":"getting-started/asyncapi/hosting/#customizing-asyncapi-documentation","title":"Customizing AsyncAPI Documentation","text":"

FastStream also provides query parameters to show and hide specific sections of AsyncAPI documentation.

You can use the following parameters control the visibility of relevant sections:

  1. sidebar: Whether to include the sidebar. Default is true.
  2. info: Whether to include the info section. Default is true.
  3. servers: Whether to include the servers section. Default is true.
  4. operations: Whether to include the operations section. Default is true.
  5. messages: Whether to include the messages section. Default is true.
  6. schemas: Whether to include the schemas section. Default is true.
  7. errors: Whether to include the errors section. Default is true.
  8. expandMessageExamples: Whether to expand message examples. Default is true.

For example, to hide the entire Servers section of the documentation, simply add servers=false as a query parameter, i.e., http://localhost:8000?servers=false. The resulting page would look like the image below:

Please use the above-listed query parameters to show and hide sections of the AsyncAPI documentation.

","boost":10},{"location":"getting-started/cli/","title":"CLI","text":"

FastStream has its own built-in CLI tool for your maximum comfort as a developer.

Thanks to typer and watchfiles. Their work is the basis of this tool.

faststream --help\n
","boost":10},{"location":"getting-started/cli/#running-the-project","title":"Running the Project","text":"","boost":10},{"location":"getting-started/cli/#multiprocessing-scaling","title":"Multiprocessing Scaling","text":"

FastStream allows you to scale application right from the command line by running you application in the Process pool.

Just set the --worker option to scale your application:

faststream run serve:app --workers 2\n
","boost":10},{"location":"getting-started/cli/#hot-reload","title":"Hot Reload","text":"

Thanks to watchfiles, written in Rust, you can work with your project easily. Edit the code as much as you like - the new version has already been launched and is waiting for your requests!

faststream run serve:app --reload\n

Tip

Please, install watchfiles if you want to use --reload feature

pip install watchfiles\n

By default FastStream watches for .py file changes, but you can specify an extra file extensions to watch by (your config files as an example)

faststream run serve:app --reload  --reload-ext .yml --realod-ext .yaml\n
","boost":10},{"location":"getting-started/cli/#environment-management","title":"Environment Management","text":"

You can pass any custom flags and launch options to the FastStream CLI even without first registering them. Just use them when launching the application - and they will be right in your environment.

Use this option to select environment files, configure logging, or at your discretion.

For example, we will pass the .env file to the context of our application:

faststream run serve:app --env=.env.dev\n
KafkaRabbitMQNATSRedis
from faststream import FastStream, ContextRepo\nfrom faststream.kafka import KafkaBroker\nfrom pydantic_settings import BaseSettings\n\nbroker = KafkaBroker()\n\napp = FastStream(broker)\n\nclass Settings(BaseSettings):\n    host: str = \"localhost:9092\"\n\n@app.on_startup\nasync def setup(env: str, context: ContextRepo):\n    settings = Settings(_env_file=env)\n    await broker.connect(settings.host)\n    context.set_global(\"settings\", settings)\n
from faststream import FastStream, ContextRepo\nfrom faststream.rabbit import RabbitBroker\nfrom pydantic_settings import BaseSettings\n\nbroker = RabbitBroker()\n\napp = FastStream(broker)\n\nclass Settings(BaseSettings):\n    host: str = \"amqp://guest:guest@localhost:5672/\" \n\n@app.on_startup\nasync def setup(env: str, context: ContextRepo):\n    settings = Settings(_env_file=env)\n    await broker.connect(settings.host)\n    context.set_global(\"settings\", settings)\n
from faststream import FastStream, ContextRepo\nfrom faststream.nats import NatsBroker\nfrom pydantic_settings import BaseSettings\n\nbroker = NatsBroker()\n\napp = FastStream(broker)\n\nclass Settings(BaseSettings):\n    host: str = \"nats://localhost:4222\"\n\n@app.on_startup\nasync def setup(env: str, context: ContextRepo):\n    settings = Settings(_env_file=env)\n    await broker.connect(settings.host)\n    context.set_global(\"settings\", settings)\n
from faststream import FastStream, ContextRepo\nfrom faststream.redis import RedisBroker\nfrom pydantic_settings import BaseSettings\n\nbroker = RedisBroker()\n\napp = FastStream(broker)\n\nclass Settings(BaseSettings):\n    host: str = \"redis://localhost:6379\"\n\n@app.on_startup\nasync def setup(env: str, context: ContextRepo):\n    settings = Settings(_env_file=env)\n    await broker.connect(settings.host)\n    context.set_global(\"settings\", settings)\n

Note

Note that the env parameter was passed to the setup function directly from the command line

All passed values can be of type bool, str or list[str].

In this case, the flags will be interpreted as follows:

You can use them both individually and together in unlimited quantities.

","boost":10},{"location":"getting-started/cli/#asyncapi-schema","title":"AsyncAPI Schema","text":"

Also, the FastStream CLI allows you to work with the AsyncAPI schema in a simple way.

You are able to generate .json or .yaml files by your application code or host HTML representation directly:

faststream docs --help\n

To learn more about the commands above, please visit AsyncAPI export and AsyncAPI hosting.

","boost":10},{"location":"getting-started/config/","title":"Settings and Environment Variables","text":"

In many cases, your application may require external settings or configurations, such as a broker connection or database credentials.

To manage these settings effectively, it's common to provide them through environment variables that can be read by the application.

","boost":10},{"location":"getting-started/config/#pydantic-settings","title":"Pydantic Settings","text":"

Fortunately, Pydantic provides a useful utility for handling settings coming from environment variables with Pydantic: Settings management.

","boost":10},{"location":"getting-started/config/#install-pydantic-settings","title":"Install pydantic-settings","text":"

First, install the pydantic-settings package:

pip install pydantic-settings\n

Info

In Pydantic v1, this functionality was included with the main package. Now it is distributed as an independent package so that you can choose not to install it if you don't need that functionality.

","boost":10},{"location":"getting-started/config/#create-the-settings-object","title":"Create the Settings Object","text":"

Import BaseSettings from Pydantic and create a subclass, similar to what you would do with a Pydantic model.

Just like with Pydantic models, you declare class attributes with type annotations and can use all the same validation features and tools, including different data types and additional validations with Field().

Pydantic v2Pydantic v1 config.py
from pydantic_settings import BaseSettings\n\n\nclass Settings(BaseSettings):\n    url: str = \"\"\n    queue: str = \"test-queue\"\n\n\nsettings = Settings()\n

Info

In Pydantic v1 you would import BaseSettings directly from pydantic instead of from pydantic_settings.

config.py
from pydantic import BaseSettings\n\n\nclass Settings(BaseSettings):\n    url: str = \"\"\n    queue: str = \"test-queue\"\n\n\nsettings = Settings()\n

When you create an instance of that Settings class (in this case, in the settings object), Pydantic will read the environment variables in a case-insensitive way. For example, an upper-case variable APP_NAME will still be read for the attribute app_name.

It will also convert and validate the data, so when you use that settings object, you will have data of the type you declared (e.g. items_per_user will be an int).

","boost":10},{"location":"getting-started/config/#using-the-settings","title":"Using the settings","text":"

Now you can use the new settings object in your application:

serve.py
import os\n\nfrom pydantic_settings import BaseSettings\n\nfrom faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\n\nclass Settings(BaseSettings):\n    url: str\n    queue: str = \"test-queue\"\n\n\nsettings = Settings(_env_file=os.getenv(\"ENV\", \".env\"))\n\nbroker = RabbitBroker(settings.url)\napp = FastStream(broker)\n\n\n@broker.subscriber(settings.queue)\nasync def handler(msg):\n    ...\n
","boost":10},{"location":"getting-started/config/#running-the-application","title":"Running the Application","text":"

You can run the application while passing the configuration parameters as environment variables. For example, you could set an URL:

URL=\"amqp://guest:guest@localhost:5672\" faststream run serve:app\n

Tip

To set multiple environment variables for a single command, separate them with spaces and put them all before the command.

","boost":10},{"location":"getting-started/config/#reading-a-env-file","title":"Reading a .env File","text":"

If you have many settings that may change frequently, especially in different environments, it might be useful to store them in a file and then read them as if they were environment variables.

This practice is common enough that it has a name; these environment variables are typically placed in a file named .env, commonly referred to as a \"dotenv\" file.

Tip

In Unix-like systems like Linux and macOS, a file starting with a dot (.) is considered a hidden file.

But a dotenv file doesn't really have to have that exact filename.

Pydantic supports reading from these types of files using an external library. You can learn more at Pydantic Settings: Dotenv (.env) support.

Tip

To use this feature, you need to install the python-dotenv library.

","boost":10},{"location":"getting-started/config/#the-env-file","title":"The .env File","text":"

You can create a .env file with contents like this:

URL=\"amqp://guest:guest@localhost:5672\"\nQUEUE=\"test-queue\"\n
","boost":10},{"location":"getting-started/config/#reading-settings-from-env","title":"Reading Settings from .env","text":"

Then update your config.py as follows:

import os\n\nfrom pydantic_settings import BaseSettings\n\n\nclass Settings(BaseSettings):\n    url: str\n    queue: str = \"test-queue\"\n\n\nsettings = Settings(_env_file=os.getenv(\"ENV\", \".env\"))\n

This way, you can specify different .env files directly from your terminal, which can be extremely helpful for various testing and production scenarios.

Note

By default, Pydantic will attempt to find a .env file. If it's not present, Pydantic will use the default field values.

","boost":10},{"location":"getting-started/config/#choosing-the-env-file-at-startup","title":"Choosing the .env File at Startup","text":"

Now you can run the apllication with different .env files like so:

ENV=.local.env faststream run serve:app\n

Or, for a production environment:

ENV=.production.env faststream run serve:app\n

Or even for a test environment:

ENV=.test.env pytest\n
","boost":10},{"location":"getting-started/context/","title":"Application Context","text":"

FastStreams has its own Dependency Injection container - Context, used to store application runtime objects and variables.

With this container, you can access both application scope and message processing scope objects. This functionality is similar to Depends usage.

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message=Context(),  # get access to raw message\n):\n    ...\n
from faststream import Context, FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message=Context(),  # get access to raw message\n):\n    ...\n
from faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message=Context(),  # get access to raw message\n):\n    ...\n
from faststream import Context, FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message=Context(),  # get access to raw message\n):\n    ...\n

But, with the Annotated Python feature usage, it is much closer to @pytest.fixture.

KafkaRabbitMQNATSRedis
from typing import Annotated\n\nfrom faststream import Context, FastStream\nfrom faststream.kafka import KafkaBroker\nfrom faststream.kafka.message import KafkaMessage\n\nMessage = Annotated[KafkaMessage, Context()]\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message: Message,  # get access to raw message\n):\n    ...\n
from typing import Annotated\n\nfrom faststream import Context, FastStream\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.rabbit.message import RabbitMessage\n\nMessage = Annotated[RabbitMessage, Context()]\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message: Message,  # get access to raw message\n):\n    ...\n
from typing import Annotated\n\nfrom faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.message import NatsMessage\n\nMessage = Annotated[NatsMessage, Context()]\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message: Message,  # get access to raw message\n):\n    ...\n
from typing import Annotated\n\nfrom faststream import Context, FastStream\nfrom faststream.redis import RedisBroker\nfrom faststream.redis.message import RedisMessage\n\nMessage = Annotated[RedisMessage, Context()]\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message: Message,  # get access to raw message\n):\n    ...\n
","boost":10},{"location":"getting-started/context/#usages","title":"Usages","text":"

By default, the context is available in the same place as Depends:

Tip

Fields obtained from the Context are editable, so editing them in a function means editing them everywhere.

","boost":10},{"location":"getting-started/context/#compatibility-with-regular-functions","title":"Compatibility with Regular Functions","text":"

To use context in other functions, use the @apply_types decorator. In this case, the context of the called function will correspond to the context of the event handler from which it was called.

from faststream import Context, apply_types\n\n@broker.subscriber(\"test\")\nasync def handler(body):\n    nested_func(body)\n\n@apply_types\ndef nested_func(body, logger=Context()):\n    logger.info(body)\n

In the example above, we did not pass the logger function at calling it; it was placed from context.

","boost":10},{"location":"getting-started/context/custom/","title":"Context Fields Declaration","text":"

You can also store your own objects in the Context.

","boost":10},{"location":"getting-started/context/custom/#global","title":"Global","text":"

To declare an application-level context field, you need to call the context.set_global method with with a key to indicate where the object will be placed in the context.

KafkaRabbitMQNATSRedis
from faststream import FastStream, ContextRepo, Context\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n@app.on_startup\nasync def set_global(context: ContextRepo):\n    context.set_global(\"secret_str\", \"my-perfect-secret\")\n
from faststream import FastStream, ContextRepo, Context\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n@app.on_startup\nasync def set_global(context: ContextRepo):\n    context.set_global(\"secret_str\", \"my-perfect-secret\")\n
from faststream import FastStream, ContextRepo, Context\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n@app.on_startup\nasync def set_global(context: ContextRepo):\n    context.set_global(\"secret_str\", \"my-perfect-secret\")\n
from faststream import FastStream, ContextRepo, Context\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n@app.on_startup\nasync def set_global(context: ContextRepo):\n    context.set_global(\"secret_str\", \"my-perfect-secret\")\n

Afterward, you can access your secret field in the usual way:

KafkaRabbitMQNATSRedis
@broker.subscriber(\"test-topic\")\nasync def handle(\n    msg: str,\n    secret_str: str=Context(),\n):\n    assert secret_str == \"my-perfect-secret\"\n
@broker.subscriber(\"test-queue\")\nasync def handle(\n    msg: str,\n    secret_str: str=Context(),\n):\n    assert secret_str == \"my-perfect-secret\"\n
@broker.subscriber(\"test-subject\")\nasync def handle(\n    msg: str,\n    secret_str: str=Context(),\n):\n    assert secret_str == \"my-perfect-secret\"\n
@broker.subscriber(\"test-channel\")\nasync def handle(\n    msg: str,\n    secret_str: str=Context(),\n):\n    assert secret_str == \"my-perfect-secret\"\n

In this case, the field becomes a global context field: it does not depend on the current message handler (unlike message)

To remove a field from the context use the reset_global method:

context.reset_global(\"my_key\")\n
","boost":10},{"location":"getting-started/context/custom/#local","title":"Local","text":"

To set a local context (available only within the message processing scope), use the context manager scope

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream, apply_types\nfrom faststream.kafka import KafkaBroker\nfrom faststream.kafka.annotations import ContextRepo, KafkaMessage\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    msg: str,\n    message: KafkaMessage,\n    context: ContextRepo,\n):\n    with context.scope(\"correlation_id\", message.correlation_id):\n        call()\n\n\n@apply_types\ndef call(\n    message: KafkaMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n
from faststream import Context, FastStream, apply_types\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.rabbit.annotations import ContextRepo, RabbitMessage\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    msg: str,\n    message: RabbitMessage,\n    context: ContextRepo,\n):\n    with context.scope(\"correlation_id\", message.correlation_id):\n        call()\n\n\n@apply_types\ndef call(\n    message: RabbitMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n
from faststream import Context, FastStream, apply_types\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import ContextRepo, NatsMessage\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    msg: str,\n    message: NatsMessage,\n    context: ContextRepo,\n):\n    with context.scope(\"correlation_id\", message.correlation_id):\n        call()\n\n\n@apply_types\ndef call(\n    message: NatsMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n
from faststream import Context, FastStream, apply_types\nfrom faststream.redis import RedisBroker\nfrom faststream.redis.annotations import ContextRepo, RedisMessage\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    msg: str,\n    message: RedisMessage,\n    context: ContextRepo,\n):\n    with context.scope(\"correlation_id\", message.correlation_id):\n        call()\n\n\n@apply_types\ndef call(\n    message: RedisMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n

You can also set the context by yourself, and it will remain within the current call stack until you clear it.

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream, apply_types, context\nfrom faststream.kafka import KafkaBroker\nfrom faststream.kafka.annotations import KafkaMessage\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    msg: str,\n    message: KafkaMessage,\n):\n    tag = context.set_local(\"correlation_id\", message.correlation_id)\n    call(tag)\n\n\n@apply_types\ndef call(\n    tag,\n    message: KafkaMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n    context.reset_local(\"correlation_id\", tag)\n
from faststream import Context, FastStream, apply_types, context\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.rabbit.annotations import RabbitMessage\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    msg: str,\n    message: RabbitMessage,\n):\n    tag = context.set_local(\"correlation_id\", message.correlation_id)\n    call(tag)\n\n\n@apply_types\ndef call(\n    tag,\n    message: RabbitMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n    context.reset_local(\"correlation_id\", tag)\n
from faststream import Context, FastStream, apply_types, context\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import NatsMessage\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    msg: str,\n    message: NatsMessage,\n):\n    tag = context.set_local(\"correlation_id\", message.correlation_id)\n    call(tag)\n\n\n@apply_types\ndef call(\n    tag,\n    message: NatsMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n    context.reset_local(\"correlation_id\", tag)\n
from faststream import Context, FastStream, apply_types, context\nfrom faststream.redis import RedisBroker\nfrom faststream.redis.annotations import RedisMessage\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    msg: str,\n    message: RedisMessage,\n):\n    tag = context.set_local(\"correlation_id\", message.correlation_id)\n    call(tag)\n\n\n@apply_types\ndef call(\n    tag,\n    message: RedisMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n    context.reset_local(\"correlation_id\", tag)\n
","boost":10},{"location":"getting-started/context/existed/","title":"Existing Fields","text":"

Context already contains some global objects that you can always access:

At the same time, thanks to contextlib.ContextVar, message is local for you current consumer scope.

","boost":10},{"location":"getting-started/context/existed/#access-to-context-fields","title":"Access to Context Fields","text":"

By default, the context searches for an object based on the argument name.

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker_object = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"test-topic\")\nasync def handle(\n    msg: str,\n    logger=Context(),\n    message=Context(),\n    broker=Context(),\n    context=Context(),\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream import Context, FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker_object = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"test-queue\")\nasync def handle(\n    msg: str,\n    logger=Context(),\n    message=Context(),\n    broker=Context(),\n    context=Context(),\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\n\nbroker_object = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"test-subject\")\nasync def handle(\n    msg: str,\n    logger=Context(),\n    message=Context(),\n    broker=Context(),\n    context=Context(),\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream import Context, FastStream\nfrom faststream.redis import RedisBroker\n\nbroker_object = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"test-channel\")\nasync def handle(\n    msg: str,\n    logger=Context(),\n    message=Context(),\n    broker=Context(),\n    context=Context(),\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
","boost":10},{"location":"getting-started/context/existed/#annotated-aliases","title":"Annotated Aliases","text":"

Also, FastStream has already created Annotated aliases to provide you with comfortable access to existing objects. You can import them directly from faststream or your broker-specific modules:

from faststream import Logger, ContextRepo\n
KafkaRabbitMQNATSRedis
from faststream.kafka.annotations import (\n    Logger, ContextRepo, KafkaMessage,\n    KafkaBroker, KafkaProducer, NoCast,\n)\n

faststream.kafka.KafkaMessage is an alias to faststream.kafka.annotations.KafkaMessage

from faststream.kafka import KafkaMessage\n

To use them, simply import and use them as subscriber argument annotations.

from faststream import Context, FastStream\nfrom faststream.kafka import KafkaBroker\nfrom faststream.kafka.annotations import (\n    ContextRepo,\n    KafkaMessage,\n    Logger,\n    KafkaBroker as BrokerAnnotation,\n)\n\nbroker_object = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"response-topic\")\nasync def handle_response(\n    msg: str,\n    logger: Logger,\n    message: KafkaMessage,\n    context: ContextRepo,\n    broker: BrokerAnnotation,\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream.rabbit.annotations import (\n    Logger, ContextRepo, RabbitMessage,\n    RabbitBroker, RabbitProducer, NoCast,\n)\n

faststream.rabbit.RabbitMessage is an alias to faststream.rabbit.annotations.RabbitMessage

from faststream.rabbit import RabbitMessage\n

To use them, simply import and use them as subscriber argument annotations.

from faststream import Context, FastStream\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.rabbit.annotations import (\n    ContextRepo,\n    RabbitMessage,\n    Logger,\n    RabbitBroker as BrokerAnnotation,\n)\n\nbroker_object = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"response-queue\")\nasync def handle_response(\n    msg: str,\n    logger: Logger,\n    message: RabbitMessage,\n    context: ContextRepo,\n    broker: BrokerAnnotation,\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream.nats.annotations import (\n    Logger, ContextRepo, NatsMessage,\n    NatsBroker, NatsProducer, NatsJsProducer,\n    Client, JsClient, NoCast,\n)\n

faststream.nats.NatsMessage is an alias to faststream.nats.annotations.NatsMessage

from faststream.nats import NatsMessage\n

To use them, simply import and use them as subscriber argument annotations.

from faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import (\n    ContextRepo,\n    NatsMessage,\n    Logger,\n    NatsBroker as BrokerAnnotation,\n)\n\nbroker_object = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"response-subject\")\nasync def handle_response(\n    msg: str,\n    logger: Logger,\n    message: NatsMessage,\n    context: ContextRepo,\n    broker: BrokerAnnotation,\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream.redis.annotations import (\n    Logger, ContextRepo, RedisMessage,\n    RedisBroker, Redis, NoCast,\n)\n

faststream.redis.RedisMessage is an alias to faststream.redis.annotations.RedisMessage

from faststream.redis import RedisMessage\n

To use them, simply import and use them as subscriber argument annotations.

from faststream import Context, FastStream\nfrom faststream.redis import RedisBroker\nfrom faststream.redis.annotations import (\n    ContextRepo,\n    RedisMessage,\n    Logger,\n    RedisBroker as BrokerAnnotation,\n)\n\nbroker_object = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"response-channel\")\nasync def handle_response(\n    msg: str,\n    logger: Logger,\n    message: RedisMessage,\n    context: ContextRepo,\n    broker: BrokerAnnotation,\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
","boost":10},{"location":"getting-started/context/extra/","title":"Context Extra Options","text":"

Additionally, Context provides you with some extra capabilities for working with containing objects.

","boost":10},{"location":"getting-started/context/extra/#default-values","title":"Default Values","text":"

For instance, if you attempt to access a field that doesn't exist in the global context, you will receive a pydantic.ValidationError exception.

However, you can set default values if needed.

KafkaRabbitMQNATSRedis
@broker.subscriber(\"test-topic\")\nasync def handle(\n    not_existed: None = Context(\"not_existed\", default=None),\n):\n    assert not_existed is None\n
@broker.subscriber(\"test-queue\")\nasync def handle(\n    not_existed: None = Context(\"not_existed\", default=None),\n):\n    assert not_existed is None\n
@broker.subscriber(\"test-subject\")\nasync def handle(\n    not_existed: None = Context(\"not_existed\", default=None),\n):\n    assert not_existed is None\n
@broker.subscriber(\"test-channel\")\nasync def handle(\n    not_existed: None = Context(\"not_existed\", default=None),\n):\n    assert not_existed is None\n
","boost":10},{"location":"getting-started/context/extra/#cast-context-types","title":"Cast Context Types","text":"

By default, context fields are NOT CAST to the type specified in their annotation.

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream, context\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\ncontext.set_global(\"secret\", \"1\")\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    secret: int = Context(),\n):\n    assert secret == \"1\"\n
from faststream import Context, FastStream, context\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\ncontext.set_global(\"secret\", \"1\")\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    secret: int = Context(),\n):\n    assert secret == \"1\"\n
from faststream import Context, FastStream, context\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\ncontext.set_global(\"secret\", \"1\")\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    secret: int = Context(),\n):\n    assert secret == \"1\"\n
from faststream import Context, FastStream, context\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\ncontext.set_global(\"secret\", \"1\")\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    secret: int = Context(),\n):\n    assert secret == \"1\"\n

If you require this functionality, you can enable the appropriate flag.

KafkaRabbitMQNATSRedis
@broker.subscriber(\"test-topic2\")\nasync def handle_int(\n    secret: int = Context(cast=True),\n):\n    assert secret == 1\n
@broker.subscriber(\"test-queue2\")\nasync def handle_int(\n    secret: int = Context(cast=True),\n):\n    assert secret == 1\n
@broker.subscriber(\"test-subject2\")\nasync def handle_int(\n    secret: int = Context(cast=True),\n):\n    assert secret == 1\n
@broker.subscriber(\"test-channel2\")\nasync def handle_int(\n    secret: int = Context(cast=True),\n):\n    assert secret == 1\n
","boost":10},{"location":"getting-started/context/fields/","title":"Access by Name","text":"

Sometimes, you may need to use a different name for the argument (not the one under which it is stored in the context) or get access to specific parts of the object. To do this, simply specify the name of what you want to access, and the context will provide you with the object.

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream\nfrom faststream.kafka import KafkaBroker\nfrom faststream.kafka.message import KafkaMessage\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    msg: KafkaMessage = Context(\"message\"),\n    correlation_id: str = Context(\"message.correlation_id\"),\n    user_header: str = Context(\"message.headers.user\"),\n):\n    assert msg.correlation_id == correlation_id\n    assert msg.headers[\"user\"] == user_header\n

This way you can get access to context object by its name

msg: KafkaMessage = Context(\"message\"),\n
from faststream import Context, FastStream\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.rabbit.message import RabbitMessage\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    msg: RabbitMessage = Context(\"message\"),\n    correlation_id: str = Context(\"message.correlation_id\"),\n    user_header: str = Context(\"message.headers.user\"),\n):\n    assert msg.correlation_id == correlation_id\n    assert msg.headers[\"user\"] == user_header\n

This way you can get access to context object by its name

msg: RabbitMessage = Context(\"message\"),\n
from faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.message import NatsMessage\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    msg: NatsMessage = Context(\"message\"),\n    correlation_id: str = Context(\"message.correlation_id\"),\n    user_header: str = Context(\"message.headers.user\"),\n):\n    assert msg.correlation_id == correlation_id\n    assert msg.headers[\"user\"] == user_header\n

This way you can get access to context object by its name

msg: NatsMessage = Context(\"message\"),\n
from faststream import Context, FastStream\nfrom faststream.redis import RedisBroker\nfrom faststream.redis.message import RedisMessage\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    msg: RedisMessage = Context(\"message\"),\n    correlation_id: str = Context(\"message.correlation_id\"),\n    user_header: str = Context(\"message.headers.user\"),\n):\n    assert msg.correlation_id == correlation_id\n    assert msg.headers[\"user\"] == user_header\n

This way you can get access to context object by its name

msg: RedisMessage = Context(\"message\"),\n

This way you can get access to context object specific field

correlation_id: str = Context(\"message.correlation_id\"),\n

Or even to a dict key

user_header: str = Context(\"message.headers.user\"),\n
","boost":10},{"location":"getting-started/contributing/CONTRIBUTING/","title":"Development","text":"

After cloning the project, you'll need to set up the development environment. Here are the guidelines on how to do this.

","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#virtual-environment-with-venv","title":"Virtual Environment with venv","text":"

Create a virtual environment in a directory using Python's venv module:

python -m venv venv\n

That will create a ./venv/ directory with Python binaries, allowing you to install packages in an isolated environment.

","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#activate-the-environment","title":"Activate the Environment","text":"

Activate the new environment with:

source ./venv/bin/activate\n

Ensure you have the latest pip version in your virtual environment:

python -m pip install --upgrade pip\n
","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#installing-dependencies","title":"Installing Dependencies","text":"

After activating the virtual environment as described above, run:

pip install -e \".[dev]\"\n

This will install all the dependencies and your local FastStream in your virtual environment.

","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#using-your-local-faststream","title":"Using Your local FastStream","text":"

If you create a Python file that imports and uses FastStream, and run it with the Python from your local environment, it will use your local FastStream source code.

Whenever you update your local FastStream source code, it will automatically use the latest version when you run your Python file again. This is because it is installed with -e.

This way, you don't have to \"install\" your local version to be able to test every change.

To use your local FastStream CLI, type:

python -m faststream ...\n
","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#running-tests","title":"Running Tests","text":"","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#pytest","title":"Pytest","text":"

To run tests with your current FastStream application and Python environment, use:

pytest tests\n# or\n./scripts/test.sh\n# with coverage output\n./scripts/test-cov.sh\n

In your project, you'll find some pytest marks:

By default, running pytest will execute \"not slow\" tests.

To run all tests use:

pytest -m 'all'\n

If you don't have a local broker instance running, you can run tests without those dependencies:

pytest -m 'not rabbit and not kafka and not nats and not redis'\n

To run tests based on RabbitMQ, Kafka, or other dependencies, the following dependencies are needed to be started as docker containers:

version: \"3\"\nservices:\n  # nosemgrep: yaml.docker-compose.security.writable-filesystem-service.writable-filesystem-service\n  rabbitmq:\n    image: rabbitmq:alpine\n    ports:\n      - \"5672:5672\"\n    # https://semgrep.dev/r?q=yaml.docker-compose.security.no-new-privileges.no-new-privileges\n    security_opt:\n      - no-new-privileges:true\n  # nosemgrep: yaml.docker-compose.security.writable-filesystem-service.writable-filesystem-service\n  kafka:\n    image: bitnami/kafka:3.5.0\n    ports:\n      - \"9092:9092\"\n    environment:\n      KAFKA_ENABLE_KRAFT: \"true\"\n      KAFKA_CFG_NODE_ID: \"1\"\n      KAFKA_CFG_PROCESS_ROLES: \"broker,controller\"\n      KAFKA_CFG_CONTROLLER_LISTENER_NAMES: \"CONTROLLER\"\n      KAFKA_CFG_LISTENERS: \"PLAINTEXT://:9092,CONTROLLER://:9093\"\n      KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP: \"CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT\"\n      KAFKA_CFG_ADVERTISED_LISTENERS: \"PLAINTEXT://127.0.0.1:9092\"\n      KAFKA_BROKER_ID: \"1\"\n      KAFKA_CFG_CONTROLLER_QUORUM_VOTERS: \"1@kafka:9093\"\n      ALLOW_PLAINTEXT_LISTENER: \"true\"\n    # https://semgrep.dev/r?q=yaml.docker-compose.security.no-new-privileges.no-new-privileges\n    security_opt:\n      - no-new-privileges:true\n  # nosemgrep: yaml.docker-compose.security.writable-filesystem-service.writable-filesystem-service\n  nats:\n    image: nats\n    command: -js\n    ports:\n      - 4222:4222\n      - 8222:8222  # management\n    # https://semgrep.dev/r?q=yaml.docker-compose.security.no-new-privileges.no-new-privileges\n    security_opt:\n      - no-new-privileges:true\n  # nosemgrep: yaml.docker-compose.security.writable-filesystem-service.writable-filesystem-service\n  redis:\n    image: redis:alpine\n    ports:\n      - 6379:6379\n    # https://semgrep.dev/r?q=yaml.docker-compose.security.no-new-privileges.no-new-privileges\n    security_opt:\n      - no-new-privileges:true\n

You can start the dependencies easily using provided script by running:

./scripts/start_test_env.sh\n

Once you are done with development and running tests, you can stop the dependencies' docker containers by running:

./scripts/stop_test_env.sh\n
","boost":3},{"location":"getting-started/contributing/docs/","title":"Documentation","text":"","boost":3},{"location":"getting-started/contributing/docs/#how-to-help","title":"How to help","text":"

You will be of invaluable help if you contribute to the documentation.

Such a contribution can be:

You can report all this in discussions on GitHub, start issue, or write about it in our discord group.

Note

Special thanks to those who are ready to offer help with the case and help in developing documentation, as well as translating it into other languages.

","boost":3},{"location":"getting-started/contributing/docs/#how-to-get-started","title":"How to get started","text":"

To develop the documentation, you don't even need to install the entire FastStream project as a whole.

Enough:

  1. Clone the project repository
  2. Create a virtual environment
    python -m venv venv\n
  3. Activate it
    source venv/bin/activate\n
  4. Install documentation dependencies
    pip install \".[devdocs]\"\n
  5. Go to the docs/ directory
  6. Start the local documentation server
    mkdocs serve\n

Now all changes in the documentation files will be reflected on your local version of the site. After making all the changes, you can issue a PR with them - and we will gladly accept it!

","boost":3},{"location":"getting-started/dependencies/","title":"Dependencies","text":"

FastStream uses the secondary library FastDepends for dependency management. This dependency system is literally borrowed from FastAPI, so if you know how to work with that framework, you'll be comfortable with dependencies in FastStream.

You can visit the FastDepends documentation for more details, but the key points and additions are covered here.

","boost":10},{"location":"getting-started/dependencies/#type-casting","title":"Type Casting","text":"

The key function in the dependency management and type conversion system in FastStream is the decorator @apply_types (also known as @inject in FastDepends).

By default, it applies to all event handlers, unless you disabled the same option when creating the broker.

KafkaRabbitMQNATSRedis
from faststream.kafka import KafkaBroker\nbroker = KafkaBroker(..., apply_types=False)\n
from faststream.rabbit import RabbitBroker\nbroker = RabbitBroker(..., apply_types=False)\n
from faststream.nats import NatsBroker\nbroker = NatsBroker(..., apply_types=False)\n
from faststream.redis import RedisBroker\nbroker = RedisBroker(..., apply_types=False)\n

Warning

Setting the apply_types=False flag not only disables type casting but also Depends and Context. If you want to disable only type casting, use validate=False instead.

This flag can be useful if you are using FastStream within another framework and you need to use its native dependency system.

","boost":10},{"location":"getting-started/dependencies/#dependency-injection","title":"Dependency Injection","text":"

To implement dependencies in FastStream, a special class called Depends is used

KafkaRabbitMQNATSRedis
from faststream import FastStream, Depends\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\ndef simple_dependency():\n    return 1\n\n@broker.subscriber(\"test\")\nasync def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
from faststream import FastStream, Depends\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\ndef simple_dependency():\n    return 1\n\n@broker.subscriber(\"test\")\nasync def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
from faststream import FastStream, Depends\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\ndef simple_dependency():\n    return 1\n\n@broker.subscriber(\"test\")\nasync def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
from faststream import FastStream, Depends\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\ndef simple_dependency():\n    return 1\n\n@broker.subscriber(\"test\")\nasync def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n

The first step: You need to declare a dependency, which can be any Callable object.

Callable

A \"Callable\" is an object that can be \"called\". It can be a function, a class, or a class method.

In other words, if you can write code like my_object() - my_object is Callable

KafkaRabbitMQNATSRedis
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n

Second step: Declare which dependencies you need using Depends

KafkaRabbitMQNATSRedis
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n

The last step: Just use the result of executing your dependency!

It's easy, isn't it?

Auto @apply_types

In the code above, we didn't use this decorator for our dependencies. However, it still applies to all functions used as dependencies. Please keep this in your mind.

","boost":10},{"location":"getting-started/dependencies/#top-level-dependencies","title":"Top-level Dependencies","text":"

If you don't need a dependency result, you can use the following code:

@broker.subscriber(\"test\")\ndef method(_ = Depends(...)): ...\n

But, using a special subscriber parameter is much more suitable:

@broker.subscriber(\"test\", dependencies=[Depends(...)])\ndef method(): ...\n

You can also declare broker-level dependencies, which will be applied to all broker's handlers:

broker = RabbitBroker(dependencies=[Depends(...)])\n
","boost":10},{"location":"getting-started/dependencies/#nested-dependencies","title":"Nested Dependencies","text":"

Dependencies can also contain other dependencies. This works in a very predictable way: just declare Depends in the dependent function.

KafkaRabbitMQNATSRedis
from faststream import FastStream, Depends\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\ndef another_dependency():\n    return 1\n\ndef simple_dependency(b: int = Depends(another_dependency)): # (1)\n    return b * 2\n\n@broker.subscriber(\"test\")\nasync def handler(\n    body: dict,\n    a: int = Depends(another_dependency),\n    b: int = Depends(simple_dependency)):\n    assert (a + b) == 3\n
  1. A nested dependency is called here
from faststream import FastStream, Depends\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\ndef another_dependency():\n    return 1\n\ndef simple_dependency(b: int = Depends(another_dependency)): # (1)\n    return b * 2\n\n@broker.subscriber(\"test\")\nasync def handler(\n    body: dict,\n    a: int = Depends(another_dependency),\n    b: int = Depends(simple_dependency)):\n    assert (a + b) == 3\n
  1. A nested dependency is called here
from faststream import FastStream, Depends\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\ndef another_dependency():\n    return 1\n\ndef simple_dependency(b: int = Depends(another_dependency)): # (1)\n    return b * 2\n\n@broker.subscriber(\"test\")\nasync def handler(\n    body: dict,\n    a: int = Depends(another_dependency),\n    b: int = Depends(simple_dependency)):\n    assert (a + b) == 3\n
  1. A nested dependency is called here
from faststream import FastStream, Depends\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\ndef another_dependency():\n    return 1\n\ndef simple_dependency(b: int = Depends(another_dependency)): # (1)\n    return b * 2\n\n@broker.subscriber(\"test\")\nasync def handler(\n    body: dict,\n    a: int = Depends(another_dependency),\n    b: int = Depends(simple_dependency)):\n    assert (a + b) == 3\n
  1. A nested dependency is called here

Caching

In the example above, the another_dependency function will be called at ONCE! FastDepends caches all dependency execution results within ONE @apply_types call stack. This means that all nested dependencies will receive the cached result of dependency execution. But, between different calls of the main function, these results will be different.

To prevent this behavior, just use Depends(..., cache=False). In this case, the dependency will be used for each function in the call stack where it is used.

","boost":10},{"location":"getting-started/dependencies/#use-with-regular-functions","title":"Use with Regular Functions","text":"

You can use the decorator @apply_types not only with @broker.subscriber(...), but also with regular functions, both synchronous and asynchronous.

SyncAsync
from faststream import Depends, apply_types\n\ndef simple_dependency(a: int, b: int = 3):\n    return a + b\n\n@apply_types\ndef method(a: int, d: int = Depends(simple_dependency)):\n    return a + d\n\ndef test_sync_dependency():\n    assert method(\"1\") == 5\n
import asyncio\nimport pytest\nfrom faststream import Depends, apply_types\n\nasync def simple_dependency(a: int, b: int = 3):\n    return a + b\n\ndef another_dependency(a: int):\n    return a\n\n@apply_types\nasync def method(\n    a: int,\n    b: int = Depends(simple_dependency),\n    c: int = Depends(another_dependency),\n):\n    return a + b + c\n\n@pytest.mark.asyncio\nasync def test_async_dependency():\n    assert 6 == await method(\"1\")\n

Be careful

In asynchronous code, you can use both synchronous and asynchronous dependencies. But in synchronous code, only synchronous dependencies are available to you.

","boost":10},{"location":"getting-started/dependencies/#casting-dependency-types","title":"Casting Dependency Types","text":"

FastDepends, used by FastStream, also gives the type return. This means that the value returned by the dependency will be be cast to the type twice: as return for dependencies and as the input argument of the main function. This does not incur additional costs if these types have the same annotation. Just keep it in mind. Or not... Anyway, I've warned you.

from faststream import Depends, apply_types\n\ndef simple_dependency(a: int, b: int = 3) -> str:\n    return a + b  # 'return' is cast to `str` for the first time\n\n@apply_types\ndef method(a: int, d: int = Depends(simple_dependency)):\n    # 'd' is cast to `int` for the second time\n    return a + d\n\nassert method(\"1\") == 5\n

Also, the result of executing the dependency is cached. If you use this dependency in N functions, this cached result will be converted to type N times (at the input to the function being used).

To avoid problems with this, use mypy or just be careful with the annotation of types in your project.

","boost":10},{"location":"getting-started/dependencies/global/","title":"Global","text":""},{"location":"getting-started/dependencies/testing/","title":"Testing","text":"

https://lancetnik.github.io/FastDepends/tutorial/overrides/

"},{"location":"getting-started/integrations/django/","title":"Using FastStream with Django","text":"

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel. It\u2019s free and open source.

In this tutorial, let's see how to use the FastStream app alongside a Django app.

","boost":10},{"location":"getting-started/integrations/django/#asgi","title":"ASGI","text":"

ASGI protocol supports lifespan events, and Django can be served as an ASGI application. So, the best way to integrate FastStream with the Django is by using ASGI lifespan. You can write it by yourself (it is really easy) or use something like this, but the prefered way for us is using Starlette Router.

Starlette Router allows you to serve any ASGI application you want, and it also supports lifespans. So, you can use it in your project to serve your regular Django ASGI and start up your FastStream broker too. Additionally, Starlette has much better static files support, providing an extra zero-cost feature.

","boost":10},{"location":"getting-started/integrations/django/#default-django-application","title":"Default Django Application","text":"

Well, lets take a look at a default Django asgi.py

asgi.py
import os\n\nfrom django.core.asgi import get_asgi_application\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\")\n\napplication = get_asgi_application()\n

You can already serve it using any ASGI server

For example, using uvicorn:

uvicorn asgi:app --workers 4\n

Or you can use Gunicorn with uvicorn workers

gunicorn asgi:app --workers 4 --worker-class uvicorn.workers.UvicornWorker\n

Your Django views, models and other stuff has no any changes if you serving it through ASGI, so you need no worry about it.

","boost":10},{"location":"getting-started/integrations/django/#faststream-integration","title":"FastStream Integration","text":"","boost":10},{"location":"getting-started/integrations/django/#serving-django-via-starlette","title":"Serving Django via Starlette","text":"

Now, we need to modify our asgi.py to serve it using Starlette

asgi.py
# regular Djano stuff\nimport os\n\nfrom django.core.asgi import get_asgi_application\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\")\n\ndjango_asgi = get_asgi_application()\n\n# Starlette serving\nfrom starlette.applications import Starlette\nfrom starlette.routing import Mount\n\napp = Starlette(\n    routes=(\n        Mount(\"/\", django_asgi()),  # redirect all requests to Django\n    ),\n)\n
","boost":10},{"location":"getting-started/integrations/django/#serving-static-files-with-starlette","title":"Serving static files with Starlette","text":"

Also, Starlette has a better static files provider than original Django one, so we can reuse it too.

Just add this line to your settings.py

settings.py
STATIC_ROOT = \"static/\"\n

And collect all static files by default Django command

python manage.py collectstatic\n

It creates a static/ directory in the root of your project, so you can serve it using Starlette

asgi.py
# Code above omitted \ud83d\udc46\n\nfrom starlette.staticfiles import StaticFiles\n\napp = Starlette(\n    routes=(\n        # /static is your STATIC_URL setting\n        Mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\"),\n        Mount(\"/\", get_asgi_application()),  # regular Django ASGI\n    ),\n)\n
","boost":10},{"location":"getting-started/integrations/django/#faststream-lifespan","title":"FastStream lifespan","text":"

Finally, we can add our FastStream integration like a regular lifespan

asgi.py
# Code above omitted \ud83d\udc46\n\nfrom contextlib import asynccontextmanager\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker()\n\n@asynccontextmanager\nasync def broker_lifespan(app):\n    await broker.start()\n    try:\n        yield\n    finally:\n        await broker.close()\n\napp = Starlette(\n    ...,\n    lifespan=broker_lifespan,\n)\n

Note

The code imports KafkaBroker as our application is going to connect with Kafka. Depending on your requirements, import the necessary service's broker from the options provided by FastStream, such as RabbitBroker, NatsBroker or KafkaBroker.

Full Example asgi.py
import os\nfrom contextlib import asynccontextmanager\n\nfrom django.core.asgi import get_asgi_application\nfrom starlette.applications import Starlette\nfrom starlette.routing import Mount\nfrom starlette.staticfiles import StaticFiles\nfrom faststream.kafka import KafkaBroker\n\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\")\n\nbroker = KafkaBroker()\n\n@asynccontextmanager\nasync def broker_lifespan(app):\n    await broker.start()\n    try:\n        yield\n    finally:\n        await broker.close()\n\napp = Starlette(\n    routes=(\n        Mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\"),\n        Mount(\"/\", get_asgi_application()),\n    ),\n    lifespan=broker_lifespan,\n)\n

This way we can easely integrate our FastStream apllication with the Django!

","boost":10},{"location":"getting-started/integrations/fastapi/","title":"FastAPI Plugin","text":"","boost":10},{"location":"getting-started/integrations/fastapi/#handling-messages","title":"Handling messages","text":"

FastStream can be used as a part of FastAPI.

Just import a StreamRouter you need and declare the message handler in the same way as with a regular FastStream application.

Tip

When used in this way, FastStream does not use its own dependency system but integrates into FastAPI. That is, you can use Depends, BackgroundTasks and other original FastAPI features as if it were a regular HTTP endpoint, but you can't use faststream.Context and faststream.Depends.

Note that the code below uses fastapi.Depends, not faststream.Depends.

Also, instead original faststream.Context you should use faststream.[broker].fastapi.Context (the same with already created annotations)

KafkaRabbitMQNATSRedis
from fastapi import Depends, FastAPI\nfrom pydantic import BaseModel\n\nfrom faststream.kafka.fastapi import KafkaRouter, Logger\n\nrouter = KafkaRouter(\"localhost:9092\")\n\nclass Incoming(BaseModel):\n    m: dict\n\ndef call():\n    return True\n\n@router.subscriber(\"test\")\n@router.publisher(\"response\")\nasync def hello(m: Incoming, logger: Logger, d=Depends(call)):\n    logger.info(m)\n    return {\"response\": \"Hello, Kafka!\"}\n\n@router.get(\"/\")\nasync def hello_http():\n    return \"Hello, HTTP!\"\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom pydantic import BaseModel\n\nfrom faststream.rabbit.fastapi import RabbitRouter, Logger\n\nrouter = RabbitRouter(\"amqp://guest:guest@localhost:5672/\")\n\nclass Incoming(BaseModel):\n    m: dict\n\ndef call():\n    return True\n\n@router.subscriber(\"test\")\n@router.publisher(\"response\")\nasync def hello(m: Incoming, logger: Logger, d=Depends(call)):\n    logger.info(m)\n    return {\"response\": \"Hello, Rabbit!\"}\n\n@router.get(\"/\")\nasync def hello_http():\n    return \"Hello, HTTP!\"\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom pydantic import BaseModel\n\nfrom faststream.nats.fastapi import NatsRouter, Logger\n\nrouter = NatsRouter(\"nats://localhost:4222\")\n\nclass Incoming(BaseModel):\n    m: dict\n\ndef call():\n    return True\n\n@router.subscriber(\"test\")\n@router.publisher(\"response\")\nasync def hello(m: Incoming, logger: Logger, d=Depends(call)):\n    logger.info(m)\n    return {\"response\": \"Hello, NATS!\"}\n\n@router.get(\"/\")\nasync def hello_http():\n    return \"Hello, HTTP!\"\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom pydantic import BaseModel\n\nfrom faststream.redis.fastapi import RedisRouter, Logger\n\nrouter = RedisRouter(\"redis://localhost:6379\")\n\nclass Incoming(BaseModel):\n    m: dict\n\ndef call():\n    return True\n\n@router.subscriber(\"test\")\n@router.publisher(\"response\")\nasync def hello(m: Incoming, logger: Logger, d=Depends(call)):\n    logger.info(m)\n    return {\"response\": \"Hello, Redis!\"}\n\n@router.get(\"/\")\nasync def hello_http():\n    return \"Hello, HTTP!\"\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n

When processing a message from a broker, the entire message body is placed simultaneously in both the body and path request parameters. You can access them in any way convenient for you. The message header is placed in headers.

Also, this router can be fully used as an HttpRouter (of which it is the inheritor). So, you can use it to declare any get, post, put and other HTTP methods. For example, this is done at line 20.

Warning

If your ASGI server does not support installing state inside lifespan, you can disable this behavior as follows:

router = StreamRouter(..., setup_state=False)\n

However, after that, you will not be able to access the broker from your application's state (but it is still available as the router.broker).

","boost":10},{"location":"getting-started/integrations/fastapi/#accessing-the-broker-object","title":"Accessing the Broker Object","text":"

Inside each router, there is a broker. You can easily access it if you need to send a message to MQ:

KafkaRabbitMQNATSRedis
from fastapi import FastAPI\n\nfrom faststream.kafka.fastapi import KafkaRouter\n\nrouter = KafkaRouter(\"localhost:9092\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\n@router.get(\"/\")\nasync def hello_http():\n    await router.broker.publish(\"Hello, Kafka!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.rabbit.fastapi import RabbitRouter\n\nrouter = RabbitRouter(\"amqp://guest:guest@localhost:5672/\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\n@router.get(\"/\")\nasync def hello_http():\n    await router.broker.publish(\"Hello, Rabbit!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.nats.fastapi import NatsRouter\n\nrouter = NatsRouter(\"nats://localhost:4222\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\n@router.get(\"/\")\nasync def hello_http():\n    await router.broker.publish(\"Hello, NATS!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.redis.fastapi import RedisRouter\n\nrouter = RedisRouter(\"redis://localhost:6379\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\n@router.get(\"/\")\nasync def hello_http():\n    await router.broker.publish(\"Hello, Redis!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n

Also, you can use the following Depends to access the broker if you want to use it at different parts of your program:

KafkaRabbitMQNATSRedis
from fastapi import Depends, FastAPI\nfrom typing_extensions import Annotated\n\nfrom faststream.kafka import KafkaBroker, fastapi\n\nrouter = fastapi.KafkaRouter(\"localhost:9092\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\ndef broker():\n    return router.broker\n\n\n@router.get(\"/\")\nasync def hello_http(broker: Annotated[KafkaBroker, Depends(broker)]):\n    await broker.publish(\"Hello, Kafka!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom typing_extensions import Annotated\n\nfrom faststream.rabbit import RabbitBroker, fastapi\n\nrouter = fastapi.RabbitRouter(\"amqp://guest:guest@localhost:5672/\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\ndef broker():\n    return router.broker\n\n\n@router.get(\"/\")\nasync def hello_http(broker: Annotated[RabbitBroker, Depends(broker)]):\n    await broker.publish(\"Hello, Rabbit!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom typing_extensions import Annotated\n\nfrom faststream.nats import NatsBroker, fastapi\n\nrouter = fastapi.NatsRouter(\"nats://localhost:4222\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\ndef broker():\n    return router.broker\n\n\n@router.get(\"/\")\nasync def hello_http(broker: Annotated[NatsBroker, Depends(broker)]):\n    await broker.publish(\"Hello, NATS!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom typing_extensions import Annotated\n\nfrom faststream.redis import RedisBroker, fastapi\n\nrouter = fastapi.RedisRouter(\"redis://localhost:6379\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\ndef broker():\n    return router.broker\n\n\n@router.get(\"/\")\nasync def hello_http(broker: Annotated[RedisBroker, Depends(broker)]):\n    await broker.publish(\"Hello, Redis!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n

Or you can access the broker from a FastAPI application state (if you don't disable it with setup_state=False):

from fastapi import Request\n\n@app.get(\"/\")\ndef main(request: Request):\n    broker = request.state.broker\n
","boost":10},{"location":"getting-started/integrations/fastapi/#after_startup","title":"@after_startup","text":"

The FastStream application has the @after_startup hook, which allows you to perform operations with your message broker after the connection is established. This can be extremely convenient for managing your brokers' objects and/or sending messages. This hook is also available for your FastAPI StreamRouter

KafkaRabbitMQNATSRedis
from fastapi import FastAPI\n\nfrom faststream.kafka.fastapi import KafkaRouter\n\nrouter = KafkaRouter(\"localhost:9092\")\n\n\n@router.subscriber(\"test\")\nasync def hello(msg: str):\n    return {\"response\": \"Hello, Kafka!\"}\n\n\n@router.after_startup\nasync def test(app: FastAPI):\n    await router.broker.publish(\"Hello!\", \"test\")\n\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.rabbit.fastapi import RabbitRouter\n\nrouter = RabbitRouter(\"amqp://guest:guest@localhost:5672/\")\n\n\n@router.subscriber(\"test\")\nasync def hello(msg: str):\n    return {\"response\": \"Hello, Rabbit!\"}\n\n\n@router.after_startup\nasync def test(app: FastAPI):\n    await router.broker.publish(\"Hello!\", \"test\")\n\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.nats.fastapi import NatsRouter\n\nrouter = NatsRouter(\"nats://localhost:4222\")\n\n\n@router.subscriber(\"test\")\nasync def hello(msg: str):\n    return {\"response\": \"Hello, NATS!\"}\n\n\n@router.after_startup\nasync def test(app: FastAPI):\n    await router.broker.publish(\"Hello!\", \"test\")\n\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.redis.fastapi import RedisRouter\n\nrouter = RedisRouter(\"redis://localhost:6379\")\n\n\n@router.subscriber(\"test\")\nasync def hello(msg: str):\n    return {\"response\": \"Hello, Redis!\"}\n\n\n@router.after_startup\nasync def test(app: FastAPI):\n    await router.broker.publish(\"Hello!\", \"test\")\n\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
","boost":10},{"location":"getting-started/integrations/fastapi/#documentation","title":"Documentation","text":"

When using FastStream as a router for FastAPI, the framework automatically registers endpoints for hosting AsyncAPI documentation into your application with the following default values:

KafkaRabbitMQNATSRedis
from faststream.kafka.fastapi import KafkaRouter\n\nrouter = KafkaRouter(\n    ...,\n    schema_url=\"/asyncapi\",\n    include_in_schema=True,\n)\n
from faststream.rabbit.fastapi import RabbitRouter\n\nrouter = RabbitRouter(\n    ...,\n    schema_url=\"/asyncapi\",\n    include_in_schema=True,\n)\n
from faststream.nats.fastapi import NatsRouter\n\nrouter = NatsRouter(\n    ...,\n    schema_url=\"/asyncapi\",\n    include_in_schema=True,\n)\n
from faststream.redis.fastapi import RedisRouter\n\nrouter = RedisRouter(\n    ...,\n    schema_url=\"/asyncapi\",\n    include_in_schema=True,\n)\n

This way, you will have three routes to interact with your application's AsyncAPI schema:

","boost":10},{"location":"getting-started/integrations/fastapi/#testing","title":"Testing","text":"

To test your FastAPI StreamRouter, you can still use it with the TestClient:

KafkaRabbitMQNATSRedis
import pytest\n\nfrom faststream.kafka import TestKafkaBroker, fastapi\n\nrouter = fastapi.KafkaRouter()\n\n\n@router.subscriber(\"test\")\nasync def handler(msg: str):\n    ...\n\n\n@pytest.mark.asyncio\nasync def test_router():\n    async with TestKafkaBroker(router.broker) as br:\n        await br.publish(\"Hi!\", \"test\")\n\n        handler.mock.assert_called_once_with(\"Hi!\")\n
import pytest\n\nfrom faststream.rabbit import TestRabbitBroker, fastapi\n\nrouter = fastapi.RabbitRouter()\n\n\n@router.subscriber(\"test\")\nasync def handler(msg: str):\n    ...\n\n\n@pytest.mark.asyncio\nasync def test_router():\n    async with TestRabbitBroker(router.broker) as br:\n        await br.publish(\"Hi!\", \"test\")\n\n        handler.mock.assert_called_once_with(\"Hi!\")\n
import pytest\n\nfrom faststream.nats import TestNatsBroker, fastapi\n\nrouter = fastapi.NatsRouter()\n\n\n@router.subscriber(\"test\")\nasync def handler(msg: str):\n    ...\n\n\n@pytest.mark.asyncio\nasync def test_router():\n    async with TestNatsBroker(router.broker) as br:\n        await br.publish(\"Hi!\", \"test\")\n\n        handler.mock.assert_called_once_with(\"Hi!\")\n
import pytest\n\nfrom faststream.redis import TestRedisBroker, fastapi\n\nrouter = fastapi.RedisRouter()\n\n\n@router.subscriber(\"test\")\nasync def handler(msg: str):\n    ...\n\n\n@pytest.mark.asyncio\nasync def test_router():\n    async with TestRedisBroker(router.broker) as br:\n        await br.publish(\"Hi!\", \"test\")\n\n        handler.mock.assert_called_once_with(\"Hi!\")\n
","boost":10},{"location":"getting-started/integrations/fastapi/#miltiple-routers","title":"Miltiple Routers","text":"

Using FastStream as a FastAPI plugin you are still able to separate messages processing logic between different routers (like with a regular HTTPRouter). But it can be confusing - how you should include multiple routers, if we have to setup router.lifespan_context as a FastAPI object lifespan.

You can make it in a two ways, depends on you reminds.

","boost":10},{"location":"getting-started/integrations/fastapi/#routers-nesting","title":"Routers nesting","text":"

If you want to use the SAME CONNECTION for all of you routers you should nest them each other and finally use only the core router to include it into FastAPI object.

KafkaRabbitMQNATSRedis
from fastapi import FastAPI\nfrom faststream.kafka.fastapi import KafkaRouter\n\ncore_router = KafkaRouter()\nnested_router = KafkaRouter()\n\n@core_router.subscriber(\"core-topic\")\nasync def handler():\n    ...\n\n@nested_router.subscriber(\"nested-topic\")\nasync def nested_handler():\n    ...\n\ncore_router.include_router(nested_router)\n\napp = FastAPI(lifespan=core_router.lifespan_context)\napp.include_router(core_router)\n
from fastapi import FastAPI\nfrom faststream.rabbit.fastapi import RabbitRouter\n\ncore_router = RabbitRouter()\nnested_router = RabbitRouter()\n\n@core_router.subscriber(\"core-queue\")\nasync def handler():\n    ...\n\n@nested_router.subscriber(\"nested-queue\")\nasync def nested_handler():\n    ...\n\ncore_router.include_router(nested_router)\n\napp = FastAPI(lifespan=core_router.lifespan_context)\napp.include_router(core_router)\n
from fastapi import FastAPI\nfrom faststream.nats.fastapi import NatsRouter\n\ncore_router = NatsRouter()\nnested_router = NatsRouter()\n\n@core_router.subscriber(\"core-subject\")\nasync def handler():\n    ...\n\n@nested_router.subscriber(\"nested-subject\")\nasync def nested_handler():\n    ...\n\ncore_router.include_router(nested_router)\n\napp = FastAPI(lifespan=core_router.lifespan_context)\napp.include_router(core_router)\n
from fastapi import FastAPI\nfrom faststream.redis.fastapi import RedisRouter\n\ncore_router = RedisRouter()\nnested_router = RedisRouter()\n\n@core_router.subscriber(\"core-channel\")\nasync def handler():\n    ...\n\n@nested_router.subscriber(\"nested-channel\")\nasync def nested_handler():\n    ...\n\ncore_router.include_router(nested_router)\n\napp = FastAPI(lifespan=core_router.lifespan_context)\napp.include_router(core_router)\n

This way the core router collects all nested routers publishers and subscribers and stores it like its own.

","boost":10},{"location":"getting-started/integrations/fastapi/#custom-lifespan","title":"Custom lifespan","text":"

Overwise, if you want to has multiple connections to different broker instances, you should start routers independently in your custom lifespan

KafkaRabbitMQNATSRedis
from contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom faststream.kafka.fastapi import KafkaRouter\n\ncore_router = KafkaRouter()\nnested_router = KafkaRouter()\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    async with (\n        core_router.lifespan_context(app),\n        nested_router.lifespan_context(app),\n    ):\n        yield\n\napp = FastAPI(lifespan=lifespan)\napp.include_router(core_router)\napp.include_router(nested_router)\n
from contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom faststream.rabbit.fastapi import RabbitRouter\n\ncore_router = RabbitRouter()\nnested_router = RabbitRouter()\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    async with (\n        core_router.lifespan_context(app),\n        nested_router.lifespan_context(app),\n    ):\n        yield\n\napp = FastAPI(lifespan=lifespan)\napp.include_router(core_router)\napp.include_router(nested_router)\n
from contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom faststream.nats.fastapi import NatsRouter\n\ncore_router = NatsRouter()\nnested_router = NatsRouter()\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    async with (\n        core_router.lifespan_context(app),\n        nested_router.lifespan_context(app),\n    ):\n        yield\n\napp = FastAPI(lifespan=lifespan)\napp.include_router(core_router)\napp.include_router(nested_router)\n
from contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom faststream.redis.fastapi import RedisRouter\n\ncore_router = RedisRouter()\nnested_router = RedisRouter()\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    async with (\n        core_router.lifespan_context(app),\n        nested_router.lifespan_context(app),\n    ):\n        yield\n\napp = FastAPI(lifespan=lifespan)\napp.include_router(core_router)\napp.include_router(nested_router)\n

Warning

This way you lose AsyncAPI schema, but we are working on it.

","boost":10},{"location":"getting-started/integrations/frameworks/","title":"INTEGRATIONS","text":"

FastStream brokers are very easy to integrate with any of your applications: it is enough to initialize the broker at startup and close it correctly at the end of your application.

Most HTTP frameworks have built-in lifecycle hooks for this.

FastAPILitestarAiohttpBlacksheepFalconQuartSanic

Tip

If you want to use FastStream in conjunction with FastAPI, perhaps you should use a special plugin

from contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    await broker.start()\n    yield\n    await broker.close()\n\napp = FastAPI(lifespan=lifespan)\n\n@app.get(\"/\")\ndef read_root():\n    return {\"Hello\": \"World\"}\n
from litestar import Litestar, get\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\n\n@broker.subscriber(\"queue\")\nasync def handle(msg):\n    print(msg)\n\n@get(\"/\")\nasync def index() -> str:\n    return \"Hello, world!\"\n\napp = Litestar(\n    [index],\n    on_startup=(broker.start,),\n    on_shutdown=(broker.close,),\n)\n
from aiohttp import web\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\nasync def start_broker(app):\n    await broker.start()\n\n\nasync def stop_broker(app):\n    await broker.close()\n\n\nasync def hello(request):\n    return web.Response(text=\"Hello, world\")\n\n\napp = web.Application()\napp.add_routes([web.get(\"/\", hello)])\napp.on_startup.append(start_broker)\napp.on_cleanup.append(stop_broker)\n\n\nif __name__ == \"__main__\":\n    web.run_app(app)\n
from blacksheep import Application\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\napp = Application()\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\n@app.on_start\nasync def start_broker(application: Application) -> None:\n    await broker.start()\n\n\n@app.on_stop\nasync def stop_broker(application: Application) -> None:\n    await broker.close()\n\n\n@app.route(\"/\")\nasync def home():\n    return \"Hello, World!\"\n
import falcon\nimport falcon.asgi\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\nclass ThingsResource:\n    async def on_get(self, req, resp):\n        resp.status = falcon.HTTP_200\n        resp.content_type = falcon.MEDIA_TEXT\n        resp.text = (\n            \"\\nTwo things awe me most, the starry sky \"\n            \"above me and the moral law within me.\\n\"\n            \"\\n\"\n            \"    ~ Immanuel Kant\\n\\n\"\n        )\n\n\nclass StreamMiddleware:\n    async def process_startup(self, scope, event):\n        await broker.start()\n\n    async def process_shutdown(self, scope, event):\n        await broker.close()\n\n\napp = falcon.asgi.App()\napp.add_middleware(StreamMiddleware())\napp.add_route(\"/things\", ThingsResource())\n
from quart import Quart\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\napp = Quart(__name__)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\n@app.before_serving\nasync def start_broker():\n    await broker.start()\n\n\n@app.after_serving\nasync def stop_broker():\n    await broker.close()\n\n\n@app.route(\"/\")\nasync def json():\n    return {\"hello\": \"world\"}\n
from sanic import Sanic\nfrom sanic.response import text\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\napp = Sanic(\"MyHelloWorldApp\")\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\n@app.after_server_start\nasync def start_broker(app, loop):\n    await broker.start()\n\n\n@app.after_server_stop\nasync def stop_broker(app, loop):\n    await broker.close()\n\n\n@app.get(\"/\")\nasync def hello_world(request):\n    return text(\"Hello, world.\")\n

However, even if such a hook is not provided, you can do it yourself.

Tornado
import asyncio\n\nimport tornado.web\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\nclass MainHandler(tornado.web.RequestHandler):\n    def get(self):\n        self.write(\"Hello, world\")\n\n\ndef make_app():\n    return tornado.web.Application(\n        [\n            (r\"/\", MainHandler),\n        ]\n    )\n\n\nasync def main():\n    app = make_app()\n    app.listen(8888)\n\n    await broker.start()\n    try:\n        await asyncio.Event().wait()\n    finally:\n        await broker.close()\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n
","boost":10},{"location":"getting-started/lifespan/","title":"Lifespan Events","text":"

Sometimes you need to define the logic that should be executed before launching the application. This means that the code will be executed once - even before your application starts receiving messages.

Also, you may need to terminate some processes after stopping the application. In this case, your code will also be executed exactly once: but after the completion of the main application.

Since this code is executed before the application starts and after it stops, it covers the entire lifecycle (lifespan) of the application.

This can be very useful for initializing your application settings at startup, raising a pool of connections to a database, or running machine learning models.

","boost":10},{"location":"getting-started/lifespan/context/","title":"Lifespan Context Manager","text":"

Also, you can define startup and shutdown logic using the lifespan parameter of the FastSTream app, and a \"context manager\" (I'll show you what that is in a second).

Let's start with an example from hooks page and refactor it using \"context manager\".

We create an async function lifespan() with yield like this:

KafkaRabbitMQNATSRedis
from contextlib import asynccontextmanager\n\nfrom faststream import Context, ContextRepo, FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n\ndef fake_ml_model_answer(x: float):\n    return x * 42\n\n\n@asynccontextmanager\nasync def lifespan(context: ContextRepo):\n    # load fake ML model\n    ml_models = { \"answer_to_everything\": fake_ml_model_answer }\n    context.set_global(\"model\", ml_models)\n\n    yield\n\n    # Clean up the ML models and release the resources\n    ml_models.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n\n\napp = FastStream(broker, lifespan=lifespan)\n
from contextlib import asynccontextmanager\n\nfrom faststream import Context, ContextRepo, FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\n\n\ndef fake_ml_model_answer(x: float):\n    return x * 42\n\n\n@asynccontextmanager\nasync def lifespan(context: ContextRepo):\n    # load fake ML model\n    ml_models = { \"answer_to_everything\": fake_ml_model_answer }\n    context.set_global(\"model\", ml_models)\n\n    yield\n\n    # Clean up the ML models and release the resources\n    ml_models.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n\n\napp = FastStream(broker, lifespan=lifespan)\n
from contextlib import asynccontextmanager\n\nfrom faststream import Context, ContextRepo, FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\n\n\ndef fake_ml_model_answer(x: float):\n    return x * 42\n\n\n@asynccontextmanager\nasync def lifespan(context: ContextRepo):\n    # load fake ML model\n    ml_models = { \"answer_to_everything\": fake_ml_model_answer }\n    context.set_global(\"model\", ml_models)\n\n    yield\n\n    # Clean up the ML models and release the resources\n    ml_models.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n\n\napp = FastStream(broker, lifespan=lifespan)\n
from contextlib import asynccontextmanager\n\nfrom faststream import Context, ContextRepo, FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\n\n\ndef fake_ml_model_answer(x: float):\n    return x * 42\n\n\n@asynccontextmanager\nasync def lifespan(context: ContextRepo):\n    # load fake ML model\n    ml_models = { \"answer_to_everything\": fake_ml_model_answer }\n    context.set_global(\"model\", ml_models)\n\n    yield\n\n    # Clean up the ML models and release the resources\n    ml_models.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n\n\napp = FastStream(broker, lifespan=lifespan)\n

As you can see, lifespan parameter is much suitable for case (than @app.on_startup and @app.after_shutdown separated calls) if you have object needs to process at application startup and shutdown both.

Tip

lifespan starts BEFORE your broken started (@app.on_startup hook) and AFTER broker was shutdown (@app.after_shutdown), so you can't publish any messages here.

If you want to make some actions will already/still running broker, please use @app.after_startup and @app.on_shutdown hooks.

Also, lifespan supports all FastStream hooks features:

","boost":10},{"location":"getting-started/lifespan/hooks/","title":"Lifespan Hooks","text":"","boost":10},{"location":"getting-started/lifespan/hooks/#usage-example","title":"Usage example","text":"

Let's imagine that your application uses pydantic as your settings manager.

I highly recommend using pydantic for these purposes, because this dependency is already used at FastStream and you don't have to install an additional package

Also, let's imagine that you have several .env, .env.development, .env.test, .env.production files with your application settings, and you want to switch them at startup without any code changes.

By passing optional arguments with the command line to your code FastStream allows you to do this easily.

","boost":10},{"location":"getting-started/lifespan/hooks/#lifespan","title":"Lifespan","text":"

Let's write some code for our example

KafkaRabbitMQNATSRedis
from pydantic_settings import BaseSettings\n\nfrom faststream import ContextRepo, FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker()\napp = FastStream(broker)\n\n\nclass Settings(BaseSettings):\n    host: str = \"localhost:9092\"\n\n\n@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
from pydantic_settings import BaseSettings\n\nfrom faststream import ContextRepo, FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\n\nclass Settings(BaseSettings):\n    host: str = \"amqp://guest:guest@localhost:5672/\" \n\n\n@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
from pydantic_settings import BaseSettings\n\nfrom faststream import ContextRepo, FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n\nclass Settings(BaseSettings):\n    host: str = \"nats://localhost:4222\"\n\n\n@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
from pydantic_settings import BaseSettings\n\nfrom faststream import ContextRepo, FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\nclass Settings(BaseSettings):\n    host: str = \"redis://localhost:6379\"\n\n\n@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n

Now this application can be run using the following command to manage the environment:

faststream run serve:app --env .env.test\n
","boost":10},{"location":"getting-started/lifespan/hooks/#details","title":"Details","text":"

Now let's look into a little more detail

To begin with, we used a decorator

@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n

to declare a function that should run when our application starts

The next step is to declare the arguments that our function will receive

@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n

In this case, the env field will be passed to the setup function from the arguments with the command line

Tip

The default lifecycle functions are used with the decorator @apply_types, therefore, all context fields and dependencies are available in them

Then, we initialized the settings of our application using the file passed to us from the command line

@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n

And put these settings in a global context

KafkaRabbitMQNATSRedis
@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
Note

Now we can access our settings anywhere in the application right from the context

from faststream import Context, apply_types\n@apply_types\nasync def func(settings = Context()): ...\n

The last step we initialized our broker: now, when the application starts, it will be ready to receive messages

@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
","boost":10},{"location":"getting-started/lifespan/hooks/#another-example","title":"Another example","text":"

Now let's imagine that we have a machine learning model that needs to process messages from some broker.

Initialization of such models usually takes a long time. It would be wise to do this at the start of the application, and not when processing each message.

You can initialize your model somewhere at the top of your module/file. However, in this case, this code will be run even just in case of importing this module, for example, during testing. It is unlikely that you want to run your model on every test run...

Therefore, it is worth initializing the model in the @app.on_startup hook.

Also, we don't want the model to finish its work incorrectly when the application is stopped. To avoid this, we need the hook @app.on_shutdown

KafkaRabbitMQNATSRedis
from faststream import Context, ContextRepo, FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\nml_models = {}  # fake ML model\n\n\ndef fake_answer_to_everything_ml_model(x: float):\n    return x * 42\n\n\n@app.on_startup\nasync def setup_model(context: ContextRepo):\n    # Load the ML model\n    ml_models[\"answer_to_everything\"] = fake_answer_to_everything_ml_model\n    context.set_global(\"model\", ml_models)\n\n\n@app.on_shutdown\nasync def shutdown_model(model: dict = Context()):\n    # Clean up the ML models and release the resources\n    model.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n
from faststream import Context, ContextRepo, FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\nml_models = {}  # fake ML model\n\n\ndef fake_answer_to_everything_ml_model(x: float):\n    return x * 42\n\n\n@app.on_startup\nasync def setup_model(context: ContextRepo):\n    # Load the ML model\n    ml_models[\"answer_to_everything\"] = fake_answer_to_everything_ml_model\n    context.set_global(\"model\", ml_models)\n\n\n@app.on_shutdown\nasync def shutdown_model(model: dict = Context()):\n    # Clean up the ML models and release the resources\n    model.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n
from faststream import Context, ContextRepo, FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\nml_models = {}  # fake ML model\n\n\ndef fake_answer_to_everything_ml_model(x: float):\n    return x * 42\n\n\n@app.on_startup\nasync def setup_model(context: ContextRepo):\n    # Load the ML model\n    ml_models[\"answer_to_everything\"] = fake_answer_to_everything_ml_model\n    context.set_global(\"model\", ml_models)\n\n\n@app.on_shutdown\nasync def shutdown_model(model: dict = Context()):\n    # Clean up the ML models and release the resources\n    model.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n
from faststream import Context, ContextRepo, FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\nml_models = {}  # fake ML model\n\n\ndef fake_answer_to_everything_ml_model(x: float):\n    return x * 42\n\n\n@app.on_startup\nasync def setup_model(context: ContextRepo):\n    # Load the ML model\n    ml_models[\"answer_to_everything\"] = fake_answer_to_everything_ml_model\n    context.set_global(\"model\", ml_models)\n\n\n@app.on_shutdown\nasync def shutdown_model(model: dict = Context()):\n    # Clean up the ML models and release the resources\n    model.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n
","boost":10},{"location":"getting-started/lifespan/hooks/#multiple-hooks","title":"Multiple hooks","text":"

If you want to declare multiple lifecycle hooks, they will be used in the order they are registered:

from faststream import Context, ContextRepo, FastStream\n\napp = FastStream()\n\n\n@app.on_startup\nasync def setup(context: ContextRepo):\n    context.set_global(\"field\", 1)\n\n\n@app.on_startup\nasync def setup_later(field: int = Context()):\n    assert field == 1\n
","boost":10},{"location":"getting-started/lifespan/hooks/#some-more-details","title":"Some more details","text":"","boost":10},{"location":"getting-started/lifespan/hooks/#async-or-not-async","title":"Async or not async","text":"

In the asynchronous version of the application, both asynchronous and synchronous methods can be used as hooks. In the synchronous version, only synchronous methods are available.

","boost":10},{"location":"getting-started/lifespan/hooks/#command-line-arguments","title":"Command line arguments","text":"

Command line arguments are available in all @app.on_startup hooks. To use them in other parts of the application, put them in the ContextRepo.

","boost":10},{"location":"getting-started/lifespan/hooks/#broker-initialization","title":"Broker initialization","text":"

The @app.on_startup hooks are called BEFORE the broker is launched by the application. The @app.after_shutdown hooks are triggered AFTER stopping the broker.

If you want to perform some actions AFTER initializing the broker: send messages, initialize objects, etc., you should use the @app.after_startup hook.

","boost":10},{"location":"getting-started/lifespan/test/","title":"Events Testing","text":"

In the most cases you are testing your subsriber/publisher functions, but sometimes you need to trigger some lifespan hooks in your tests too.

For this reason, FastStream has a special TestApp patcher working as a regular async context manager.

KafkaRabbitMQNATSRedis
import pytest\n\nfrom faststream import FastStream, TestApp\nfrom faststream.kafka import KafkaBroker, TestKafkaBroker\n\napp = FastStream(KafkaBroker())\n\n\n@app.after_startup\nasync def handle():\n    print(\"Calls in tests too!\")\n\n\n@pytest.mark.asyncio\nasync def test_lifespan():\n    async with (\n        TestKafkaBroker(app.broker, connect_only=True),\n        TestApp(app),\n    ):\n        # test something\n        pass\n
import pytest\n\nfrom faststream import FastStream, TestApp\nfrom faststream.rabbit import RabbitBroker, TestRabbitBroker\n\napp = FastStream(RabbitBroker())\n\n\n@app.after_startup\nasync def handle():\n    print(\"Calls in tests too!\")\n\n\n@pytest.mark.asyncio\nasync def test_lifespan():\n    async with (\n        TestRabbitBroker(app.broker, connect_only=True),\n        TestApp(app),\n    ):\n        # test something\n        pass\n
import pytest\n\nfrom faststream import FastStream, TestApp\nfrom faststream.nats import NatsBroker, TestNatsBroker\n\napp = FastStream(NatsBroker())\n\n\n@app.after_startup\nasync def handle():\n    print(\"Calls in tests too!\")\n\n\n@pytest.mark.asyncio\nasync def test_lifespan():\n    async with (\n        TestNatsBroker(app.broker, connect_only=True),\n        TestApp(app),\n    ):\n        # test something\n        pass\n
import pytest\n\nfrom faststream import FastStream, TestApp\nfrom faststream.redis import RedisBroker, TestRedisBroker\n\napp = FastStream(RedisBroker())\n\n\n@app.after_startup\nasync def handle():\n    print(\"Calls in tests too!\")\n\n\n@pytest.mark.asyncio\nasync def test_lifespan():\n    async with (\n        TestRedisBroker(app.broker, connect_only=True),\n        TestApp(app),\n    ):\n        # test something\n        pass\n
","boost":10},{"location":"getting-started/lifespan/test/#using-with-testbroker","title":"Using with TestBroker","text":"

If you want to use In-Memory patched broker in your tests, it's advisable to patch the broker first (before applying the application patch).

Also, TestApp and TestBroker are calling broker.start() both. According to the original logic, broker should be started in the FastStream application, but TestBroker applied first breaks this behavior. This reason TestApp prevents TestBroker broker.start() call if it placed incide TestBroker context.

This behavior is ruled by connect_only TestBroker argument. By default it has None value, but TestApp can set it to True/False by inner logic. To prevent this \"magic\", just setup connect_only argument manually.

Warning

With connect_only=False, all FastStream hooks will be called after broker was started, what can breaks some @app.on_startup logic.

","boost":10},{"location":"getting-started/middlewares/","title":"Middlewares","text":"

Middlewares are a powerful mechanism that allows you to add additional logic to any stage of the message processing pipeline.

This way, you can greatly extend your FastStream application with features such as:

Middlewares have several methods to override. You can implement some or all of them and use middlewares at the broker, router, or subscriber level. Thus, middlewares are the most flexible FastStream feature.

","boost":10},{"location":"getting-started/middlewares/#message-receive-wrapper","title":"Message Receive Wrapper","text":"

Unfortunately, this powerful feature has a somewhat complex signature too.

Using middlewares, you can wrap the entire message processing pipeline. In this case, you need to specify on_receive and after_processed methods:

from faststream import BaseMiddleware\n\nclass MyMiddleware(BaseMiddleware):\n    async def on_receive(self):\n        print(f\"Received: {self.message}\")\n        return await super().on_receive()\n\n    async def after_processed(self, exc_type, exc_val, exec_tb):\n        return await super().after_processed(exc_type, exc_val, exec_tb)\n

These methods should be overwritten only in a broker-level middlewares.

Broker(middlewares=[MyMiddleware])\n

In other cases, on_receive will be called at every subscriber filter function call.

Tip

Please always call super() methods at the end of your function; this is important for correct error processing.

","boost":10},{"location":"getting-started/middlewares/#message-consuming-wrapper","title":"Message Consuming Wrapper","text":"

Also, using middlewares, you are able to wrap consumer function calls directly.

In this case, you need to specify on_receive and after_processed methods:

from typing import Optional\n\nfrom faststream import BaseMiddleware:\nfrom faststream.types import DecodedMessage\n\nclass MyMiddleware(BaseMiddleware):\n    async def on_consume(self, msg: DecodedMessage) -> DecodedMessage:\n        return await super().on_consume(msg)\n\n    async def after_consume(self, err: Optional[Exception]) -> None:\n        return await super().after_consume(err)\n

This way, you can patch the incoming message body right before passing it to your consumer subscriber.

Also, if you have multiple filters for one subscriber, these methods will be called at once when the filtering is completed successfully.

","boost":10},{"location":"getting-started/middlewares/#message-publishing-wrapper","title":"Message Publishing Wrapper","text":"

Finally, using middlewares, you are able to patch outgoing messages too. For example, you can compress/encode outgoing messages at the application level.

In this, case you need to specify on_publish and after_publish methods:

from typing import Optional\n\nfrom faststream import BaseMiddleware:\nfrom faststream.types import SendableMessage\n\nclass MyMiddleware(BaseMiddleware):\n    async def on_publish(self, msg: SendableMessage) -> SendableMessage:\n        return await super().on_publish(msg)\n\n    async def after_publish(self, err: Optional[Exception]) -> None:\n        return await super().after_publish(err)\n
","boost":10},{"location":"getting-started/publishing/","title":"Publishing Basics","text":"

FastStream is broker-agnostic and easy to use, even as a client in non-FastStream applications.

It offers several use cases for publishing messages:

All of these variants have their own advantages and limitations, so you can choose what you want based on your requirements. Please visit the following pages for details.

","boost":10},{"location":"getting-started/publishing/#serialization","title":"Serialization","text":"

FastStream allows you to publish any JSON-serializable messages (Python types, Pydantic models, etc.) or raw bytes.

It automatically sets up all required headers, especially the correlation_id, which is used to trace message processing pipelines across all services.

The content-type is a meaningfull header for FastStream services. It helps the framework serialize messages faster, selecting the right serializer based on the header. This header is automatically set by FastStream too, but you should set it up manually using other libraries to interact with FastStream applications.

Content-Type can be:

By the way, you can use application/json for all of your messages if they are not raw bytes. You can even omit using any header at all, but it makes serialization slightly slower.

","boost":10},{"location":"getting-started/publishing/#publishing","title":"Publishing","text":"

FastStream can also be used as a Broker client to send messages in other applications. It is quite straightforward and similar to aiohttp or requests.

You just need to connect your broker, and you are ready to send a message. Additionally, you can use Broker as an async context manager to establish a connection and disconnect when leaving the scope.

To publish a message, simply set up the message content and a routing key:

KafkaRabbitMQNATSRedis
async with KafkaBroker() as br:\n    await br.publish(\"message\", \"topic\")\n
async with RabbitBroker() as br:\n    await br.publish(\"message\", \"queue\")\n
async with NatsBroker() as br:\n    await br.publish(\"message\", \"subject\")\n
async with RedisBroker() as br:\n    await br.publish(\"message\", \"channel\")\n
","boost":10},{"location":"getting-started/publishing/broker/","title":"Broker Publishing","text":"

The easiest way to publish a message is to use a Broker, which allows you to use it as a publisher client in any applications.

In the FastStream project, this call is not represented in the AsyncAPI scheme. You can use it to send rarely-publishing messages, such as startup or shutdown events.

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle():\n    await broker.publish(\"Hi!\", topic=\"another-topic\")\n\n\n@broker.subscriber(\"another-topic\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", topic=\"test-topic\")\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle():\n    await broker.publish(\"Hi!\", queue=\"another-queue\")\n\n\n@broker.subscriber(\"another-queue\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", queue=\"test-queue\")\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle():\n    await broker.publish(\"Hi!\", subject=\"another-subject\")\n\n\n@broker.subscriber(\"another-subject\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", subject=\"test-subject\")\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle():\n    await broker.publish(\"Hi!\", channel=\"another-channel\")\n\n\n@broker.subscriber(\"another-channel\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", channel=\"test-channel\")\n
","boost":10},{"location":"getting-started/publishing/decorator/","title":"Publisher Decorator","text":"

The second easiest way to publish messages is by using the Publisher Decorator. This method has an AsyncAPI representation and is suitable for quickly creating applications. However, it doesn't provide all testing features.

It creates a structured DataPipeline unit with an input and output. The order of Subscriber and Publisher decorators doesn't matter, but @broker.publisher(...) can be used only with functions already decorated by a @broker.subscriber(...).

Note

It uses the handler function's return type annotation to cast the function's return value before sending, so be accurate with it.

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\n@broker.publisher(\"another-topic\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-topic\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", topic=\"test-topic\")\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\n@broker.publisher(\"another-queue\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-queue\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", queue=\"test-queue\")\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\n@broker.publisher(\"another-subject\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-subject\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", subject=\"test-subject\")\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\n@broker.publisher(\"another-channel\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-channel\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", channel=\"test-channel\")\n
","boost":10},{"location":"getting-started/publishing/decorator/#message-broadcasting","title":"Message Broadcasting","text":"

The decorator can be used multiple times with one function to broadcast the function's return:

@broker.subscriber(\"in\")\n@broker.publisher(\"first-out\")\n@broker.publisher(\"second-out\")\nasync def handle(msg) -> str:\n    return \"Response\"\n

This way you will send a copy of your return to the all output topics.

Note

Also, if this subscriber consumes a message with RPC mode, it sends a reply not only to the RPC channel but also to all publishers as well.

","boost":10},{"location":"getting-started/publishing/decorator/#details","title":"Details","text":"

Additionally, @broker.publisher(...) automatically sends a message with the same correlation_id as the incoming message. This way, you get the same correlation_id for the entire message pipeline process across all services, allowing you to collect a trace.

","boost":10},{"location":"getting-started/publishing/direct/","title":"Publisher Direct Usage","text":"

The Publisher Object provides a full-featured way to publish messages. It has an AsyncAPI representation and includes testability features.

This method creates a reusable Publisher object that can be used directly to publish a message:

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-topic\")\n\n@broker.subscriber(\"test-topic\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n\n\n@broker.subscriber(\"another-topic\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-queue\")\n\n@broker.subscriber(\"test-queue\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n\n\n@broker.subscriber(\"another-queue\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-subject\")\n\n@broker.subscriber(\"test-subject\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n\n\n@broker.subscriber(\"another-subject\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-channel\")\n\n@broker.subscriber(\"test-channel\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n\n\n@broker.subscriber(\"another-channel\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n

It is something in the middle between broker publish and object decorator. It has an AsyncAPI representation and testability features (like the object decorator), but allows you to send different messages to different outputs (like the broker publish).

@broker.subscriber(\"in\")\nasync def handle(msg) -> str:\n    await publisher1.publish(\"Response-1\")\n    await publisher2.publish(\"Response-2\")\n

Note

When using this method, FastStream doesn't reuse the incoming correlation_id to mark outgoing messages with it. You should set it manually if it is required.

","boost":10},{"location":"getting-started/publishing/object/","title":"Publisher Object","text":"

The Publisher Object provides a full-featured way to publish messages. It has an AsyncAPI representation and includes testability features. This method creates a reusable Publisher object.

Additionally, this object can be used as a decorator. The order of Subscriber and Publisher decorators doesn't matter, but @publisher can be used only with functions already decorated by a @broker.subscriber(...).

Note

It uses the handler function's return type annotation to cast the function's return value before sending, so be accurate with it.

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-topic\")\n\n@publisher\n@broker.subscriber(\"test-topic\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-topic\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-queue\")\n\n@publisher\n@broker.subscriber(\"test-queue\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-queue\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-subject\")\n\n@publisher\n@broker.subscriber(\"test-subject\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-subject\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-channel\")\n\n@publisher\n@broker.subscriber(\"test-channel\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-channel\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
","boost":10},{"location":"getting-started/publishing/object/#message-broadcasting","title":"Message Broadcasting","text":"

The decorator can be used multiple times with one function to broadcast the function's return:

@publisher1\n@publisher2\n@broker.subscriber(\"in\")\nasync def handle(msg) -> str:\n    return \"Response\"\n

This way, you will send a copy of your return to all output topics.

Note

Also, if this subscriber consumes a message with RPC mode, it sends a reply not only to the RPC channel but also to all publishers as well.

","boost":10},{"location":"getting-started/publishing/object/#details","title":"Details","text":"

Additionally, @publisher automatically sends a message with the same correlation_id as the incoming message. This way, you get the same correlation_id for the entire message pipeline process across all services, allowing you to collect a trace.

","boost":10},{"location":"getting-started/publishing/test/","title":"Publisher Testing","text":"

If you are working with a Publisher object (either as a decorator or directly), you have several testing features available:

","boost":10},{"location":"getting-started/publishing/test/#base-application","title":"Base Application","text":"

Let's take a look at a simple application example with a publisher as a decorator or as a direct call:

DecoratorDirect KafkaRabbitMQNATSRedis
publisher = broker.publisher(\"another-topic\")\n\n@publisher\n@broker.subscriber(\"test-topic\")\nasync def handle() -> str:\n    return \"Hi!\"\n
publisher = broker.publisher(\"another-queue\")\n\n@publisher\n@broker.subscriber(\"test-queue\")\nasync def handle() -> str:\n    return \"Hi!\"\n
publisher = broker.publisher(\"another-subject\")\n\n@publisher\n@broker.subscriber(\"test-subject\")\nasync def handle() -> str:\n    return \"Hi!\"\n
publisher = broker.publisher(\"another-channel\")\n\n@publisher\n@broker.subscriber(\"test-channel\")\nasync def handle() -> str:\n    return \"Hi!\"\n
KafkaRabbitMQNATSRedis
publisher = broker.publisher(\"another-topic\")\n\n@broker.subscriber(\"test-topic\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n
publisher = broker.publisher(\"another-queue\")\n\n@broker.subscriber(\"test-queue\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n
publisher = broker.publisher(\"another-subject\")\n\n@broker.subscriber(\"test-subject\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n
publisher = broker.publisher(\"another-channel\")\n\n@broker.subscriber(\"test-channel\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n
","boost":10},{"location":"getting-started/publishing/test/#testing","title":"Testing","text":"

To test it, you just need to patch your broker with a special TestBroker.

KafkaRabbitMQNATSRedis
import pytest\n\nfrom faststream.kafka import TestKafkaBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestKafkaBroker(broker) as br:\n        await br.publish(\"\", topic=\"test-topic\")\n
import pytest\n\nfrom faststream.rabbit import TestRabbitBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRabbitBroker(broker) as br:\n        await br.publish(\"\", queue=\"test-queue\")\n
import pytest\n\nfrom faststream.nats import TestNatsBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestNatsBroker(broker) as br:\n        await br.publish(\"\", subject=\"test-subject\")\n
import pytest\n\nfrom faststream.redis import TestRedisBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRedisBroker(broker) as br:\n        await br.publish(\"\", channel=\"test-channel\")\n

By default, it patches you broker to run In-Memory, so you can use it without any external broker. It should be extremely usefull in your CI or local development environment.

Also, it allows you to check the outgoing message body in the same way as with a subscriber.

publisher.mock.assert_called_once_with(\"Hi!\")\n

Note

The Publisher mock contains not just a publish method input value. It sets up a virtual consumer for an outgoing topic, consumes a message, and stores this consumed one.

Additionally, TestBroker can be used with a real external broker to make your tests end-to-end suitable. For more information, please visit the subscriber testing page.

","boost":10},{"location":"getting-started/routers/","title":"Broker Router","text":"

Sometimes you want to:

For these reasons, FastStream has a special Broker Router.

","boost":10},{"location":"getting-started/routers/#router-usage","title":"Router Usage","text":"

First, you need to import the Broker Router from the same module from where you imported the broker.

When creating a Broker Router, you can specify a prefix that will be automatically applied to all subscribers and publishers of this router.

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaRouter\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\nrouter = KafkaRouter(prefix=\"prefix_\")\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker, RabbitRouter\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\nrouter = RabbitRouter(prefix=\"prefix_\")\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker, NatsRouter\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\nrouter = NatsRouter(prefix=\"prefix_\")\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker, RedisRouter\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\nrouter = RedisRouter(prefix=\"prefix_\")\n

Now you can use the created router to register handlers and publishers as if it were a regular broker

KafkaRabbitMQNATSRedis
@router.subscriber(\"test-topic\")\n@router.publisher(\"another-topic\")\nasync def handle(name: str, user_id: int) -> str:\n    assert name == \"John\"\n    assert user_id == 1\n    return \"Hi!\"\n\n\n@router.subscriber(\"another-topic\")\nasync def handle_response(msg: str):\n    assert msg == \"Hi!\"\n
@router.subscriber(\"test-queue\")\n@router.publisher(\"another-queue\")\nasync def handle(name: str, user_id: int) -> str:\n    assert name == \"John\"\n    assert user_id == 1\n    return \"Hi!\"\n\n\n@router.subscriber(\"another-queue\")\nasync def handle_response(msg: str):\n    assert msg == \"Hi!\"\n
@router.subscriber(\"test-subject\")\n@router.publisher(\"another-subject\")\nasync def handle(name: str, user_id: int) -> str:\n    assert name == \"John\"\n    assert user_id == 1\n    return \"Hi!\"\n\n\n@router.subscriber(\"another-subject\")\nasync def handle_response(msg: str):\n    assert msg == \"Hi!\"\n
@router.subscriber(\"test-channel\")\n@router.publisher(\"another-channel\")\nasync def handle(name: str, user_id: int) -> str:\n    assert name == \"John\"\n    assert user_id == 1\n    return \"Hi!\"\n\n\n@router.subscriber(\"another-channel\")\nasync def handle_response(msg: str):\n    assert msg == \"Hi!\"\n

Then you can simply include all the handlers declared using the router in your broker

broker.include_router(router)\n

Please note that when publishing a message, you now need to specify the same prefix that you used when creating the router

KafkaRabbitMQNATSRedis
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    topic=\"prefix_test-topic\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    queue=\"prefix_test-queue\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    subject=\"prefix_test-subject\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    channel=\"prefix_test-channel\",\n)\n

Tip

Also, when creating a Broker Router, you can specify middleware, dependencies, parser and decoder to apply them to all subscribers declared via this router.

","boost":10},{"location":"getting-started/routers/#delay-handler-registration","title":"Delay Handler Registration","text":"

If you want to separate your application's core logic from FastStream's routing logic, you can write some core functions and use them as Broker Router handlers later:

KafkaRabbitMQNATSRedis
from faststream.kafka import KafkaRoute, KafkaRouter\n\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\nrouter = KafkaRouter(\n    handlers=(\n        KafkaRoute(handle, \"test-topic\"),\n    )\n)\n
from faststream.rabbit import RabbitRoute, RabbitRouter\n\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\nrouter = RabbitRouter(\n    handlers=(\n        RabbitRoute(handle, \"test-queue\"),\n    )\n)\n
from faststream.nats import NatsRoute, NatsRouter\n\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\nrouter = NatsRouter(\n    handlers=(\n        NatsRoute(handle, \"test-subject\"),\n    )\n)\n
from faststream.redis import RedisRouter, RedisRoute\n\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\nrouter = RedisRouter(\n    handlers=(\n        RedisRoute(handle, \"test-channel\"),\n    )\n)\n

Warning

Be careful, this way you won't be able to test your handlers with a mock object.

","boost":10},{"location":"getting-started/serialization/","title":"Custom Serialization","text":"

By default, FastStream uses the JSON format to send and receive messages. However, if you need to handle messages in other formats or with additional serialization steps, such as gzip, lz4, Avro, Protobuf or Msgpack, you can easily modify the serialization logic.

","boost":10},{"location":"getting-started/serialization/#serialization-steps","title":"Serialization Steps","text":"

Before the message reaches your subscriber, FastStream applies two functions to it sequentially: parse_message and decode_message. You can modify one or both stages depending on your needs.

","boost":10},{"location":"getting-started/serialization/#message-parsing","title":"Message Parsing","text":"

At this stage, FastStream serializes an incoming message from the broker's framework into a general format called - StreamMessage. During this stage, the message body remains in the form of raw bytes.

This stage is closely related to the features of the broker used, and in most cases, redefining it is not necessary.

The parser declared at the broker level will be applied to all subscribers. The parser declared at the subscriber level is applied only to that specific subscriber and overrides the `broker' parser if specified.

","boost":10},{"location":"getting-started/serialization/#message-decoding","title":"Message Decoding","text":"

At this stage, the body of the StreamMessage is transformed into a format suitable for processing within your subscriber function. This is the stage you may need to redefine more often.

","boost":10},{"location":"getting-started/serialization/decoder/","title":"Custom Decoder","text":"

At this stage, the body of a StreamMessage is transformed into the format that it will take when it enters your handler function. This stage is the one you will need to redefine more often.

","boost":10},{"location":"getting-started/serialization/decoder/#signature","title":"Signature","text":"

The original decoder function has a relatively simple signature (this is a simplified version):

KafkaRabbitMQNATSRedis
from faststream.types import DecodedMessage\nfrom faststream.kafka import KafkaMessage\n\ndef decoder(msg: KafkaMessage) -> DecodedMessage:\n    ...\n
from faststream.types import DecodedMessage\nfrom faststream.rabbit import RabbitMessage\n\ndef decoder(msg: RabbitMessage) -> DecodedMessage:\n    ...\n
from faststream.types import DecodedMessage\nfrom faststream.nats import NatsMessage\n\ndef decoder(msg: NatsMessage) -> DecodedMessage:\n    ...\n
from faststream.types import DecodedMessage\nfrom faststream.redis import RedisMessage\n\ndef decoder(msg: RedisMessage) -> DecodedMessage:\n    ...\n

Alternatively, you can reuse the original decoder function with the following signature:

KafkaRabbitMQNATSRedis
from types import Callable, Awaitable\nfrom faststream.types import DecodedMessage\nfrom faststream.kafka import KafkaMessage\n\nasync def decoder(\n    msg: KafkaMessage,\n    original_decoder: Callable[[KafkaMessage], Awaitable[DecodedMessage]],\n) -> DecodedMessage:\n    return await original_decoder(msg)\n
from types import Callable, Awaitable\nfrom faststream.types import DecodedMessage\nfrom faststream.rabbit import RabbitMessage\n\nasync def decoder(\n    msg: RabbitMessage,\n    original_decoder: Callable[[RabbitMessage], Awaitable[DecodedMessage]],\n) -> DecodedMessage:\n    return await original_decoder(msg)\n
from types import Callable, Awaitable\nfrom faststream.types import DecodedMessage\nfrom faststream.nats import NatsMessage\n\nasync def decoder(\n    msg: NatsMessage,\n    original_decoder: Callable[[NatsMessage], Awaitable[DecodedMessage]],\n) -> DecodedMessage:\n    return await original_decoder(msg)\n
from types import Callable, Awaitable\nfrom faststream.types import DecodedMessage\nfrom faststream.redis import RedisMessage\n\nasync def decoder(\n    msg: RedisMessage,\n    original_decoder: Callable[[RedisMessage], Awaitable[DecodedMessage]],\n) -> DecodedMessage:\n    return await original_decoder(msg)\n

Note

The original decoder is always an asynchronous function, so your custom decoder should also be asynchronous.

Afterward, you can set this custom decoder at the broker or subscriber level.

","boost":10},{"location":"getting-started/serialization/decoder/#example","title":"Example","text":"

You can find examples of Protobuf, Msgpack and Avro serialization in the next article.

","boost":10},{"location":"getting-started/serialization/examples/","title":"Serialization examples","text":"","boost":10},{"location":"getting-started/serialization/examples/#protobuf","title":"Protobuf","text":"

In this section, we will explore an example using Protobuf. However, this approach is also applicable to other serialization methods.

Protobuf

Protobuf is an alternative message serialization method commonly used in GRPC. Its main advantage is that it results in much smaller message sizes1 compared to JSON, but it requires a message schema (.proto files) on both the client and server sides.

To begin, install the necessary dependencies:

pip install grpcio-tools\n

Next, let's define the schema for our message:

message.proto
syntax = \"proto3\";\n\nmessage Person {\n    string name = 1;\n    float age = 2;\n}\n

Now, generate a Python class to work with messages in Protobuf format:

python -m grpc_tools.protoc --python_out=. --pyi_out=. -I . message.proto\n

This generates two files: message_pb2.py and message_pb2.pyi. We can use the generated class to serialize our messages:

from message_pb2 import Person\n\nfrom faststream import FastStream, Logger, NoCast\nfrom faststream.rabbit import RabbitBroker, RabbitMessage\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\n\nasync def decode_message(msg: RabbitMessage) -> Person:\n    decoded = Person()\n    decoded.ParseFromString(msg.body)\n    return decoded\n\n\n@broker.subscriber(\"test\", decoder=decode_message)\nasync def consume(body: NoCast[Person], logger: Logger):\n    logger.info(body)\n\n\n@app.after_startup\nasync def publish():\n    body = Person(name=\"John\", age=25).SerializeToString()\n    await broker.publish(body, \"test\")\n

Note that we used the NoCast annotation to exclude the message from the pydantic representation of our handler.

async def consume(body: NoCast[Person], logger: Logger):\n
","boost":10},{"location":"getting-started/serialization/examples/#msgpack","title":"Msgpack","text":"

Msgpack is another alternative binary data format. Its main advantage is that it results in smaller message sizes2 compared to JSON, although slightly larger than Protobuf. The key advantage is that it doesn't require a message schema, making it easy to use in most cases.

To get started, install the necessary dependencies:

pip install msgpack\n

Since there is no need for a schema, you can easily write a Msgpack decoder:

import msgpack\n\nfrom faststream import FastStream, Logger\nfrom faststream.rabbit import RabbitBroker, RabbitMessage\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\n\nasync def decode_message(msg: RabbitMessage):\n    return msgpack.loads(msg.body)\n\n\n@broker.subscriber(\"test\", decoder=decode_message)\nasync def consume(name: str, age: int, logger: Logger):\n    logger.info(f\"{name}: {age}\")\n\n\n@app.after_startup\nasync def publish():\n    body = msgpack.dumps({\"name\": \"John\", \"age\": 25}, use_bin_type=True)\n    await broker.publish(body, \"test\")\n

Using Msgpack is much simpler than using Protobuf schemas. Therefore, if you don't have strict message size limitations, you can use Msgpack serialization in most cases.

","boost":10},{"location":"getting-started/serialization/examples/#avro","title":"Avro","text":"

In this section, let's explore how to use Avro encoding and decoding to encode/decode our messages as part of FastStream.

Avro

Apache Avro uses JSON to define data types and protocols and serializes data in a compact binary format. Avro utilizes a schema to structure the data that is being encoded. Schemas are composed of primitive types (null, boolean, int, long, float, double, bytes, and string) and complex types (record, enum, array, map, union, and fixed).

To get started, install the necessary dependencies:

pip install fastavro\n

Next, let's define the schema for our message. You can either define it in the Python file itself as:

person_schema = {\n    \"type\": \"record\",\n    \"namespace\": \"Person\",\n    \"name\": \"Person\",\n    \"fields\": [\n        {\"doc\": \"Name\", \"type\": \"string\", \"name\": \"name\"},\n        {\"doc\": \"Age\", \"type\": \"int\", \"name\": \"age\"},\n    ],\n}\n

Or you can load the schema from an avsc file as:

person_schema = fastavro.schema.load_schema(\"person.avsc\")\n

The contents of the person.avsc file are:

person.avsc
{\n    \"type\": \"record\",\n    \"namespace\": \"Person\",\n    \"name\": \"Person\",\n    \"fields\": [\n        {\"doc\": \"Name\", \"type\": \"string\", \"name\": \"name\"},\n        {\"doc\": \"Age\", \"type\": \"int\", \"name\": \"age\"}\n    ]\n}\n

Finally, let's use Avro's schemaless_reader and schemaless_writer to decode and encode messages in the FastStream app.

import io\n\nimport fastavro\n\nfrom faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker, KafkaMessage\n\nbroker = KafkaBroker()\napp = FastStream(broker)\n\n\n# person_schema = ...\nschema = fastavro.schema.parse_schema(person_schema)\n\nasync def decode_message(msg: KafkaMessage):\n    bytes_reader = io.BytesIO(msg.body)\n    msg_dict = fastavro.schemaless_reader(bytes_reader, schema)\n    return msg_dict\n\n\n@broker.subscriber(\"test\", decoder=decode_message)\nasync def consume(name: str, age: int, logger: Logger):\n    logger.info(f\"{name}: {age}\")\n\n\n@app.after_startup\nasync def publish():\n    msg = {\"name\": \"John\", \"age\": 25}\n\n    bytes_writer = io.BytesIO()\n    fastavro.schemaless_writer(bytes_writer, schema, msg)\n    raw_bytes = bytes_writer.getvalue()\n\n    await broker.publish(raw_bytes, \"test\")\n
","boost":10},{"location":"getting-started/serialization/examples/#tips","title":"Tips","text":"","boost":10},{"location":"getting-started/serialization/examples/#data-compression","title":"Data Compression","text":"

If you are dealing with very large messages, consider compressing them as well. You can explore libraries such as lz4 or zstd for compression algorithms.

Compression can significantly reduce message size, especially if there are repeated blocks. However, in the case of small message bodies, data compression may increase the message size. Therefore, you should assess the compression impact based on your specific application requirements.

","boost":10},{"location":"getting-started/serialization/examples/#broker-level-serialization","title":"Broker-Level Serialization","text":"

You can still set a custom decoder at the Broker or Router level. However, if you want to automatically encode publishing messages as well, you should explore Middleware for serialization implimentation.

  1. For example, a message like { \"name\": \"John\", \"age\": 25 } in JSON takes 27 bytes, while in Protobuf, it takes only 11 bytes. With lists and more complex structures, the savings can be even more significant (up to 20x times).\u00a0\u21a9

  2. A message with Msgpack serialization, such as { \"name\": \"John\", \"age\": 25 }, takes 16 bytes.\u00a0\u21a9

","boost":10},{"location":"getting-started/serialization/parser/","title":"Custom Parser","text":"

At this stage, FastStream serializes an incoming message from the broker's framework into a general format called StreamMessage. During this stage, the message body remains in the form of raw bytes.

StreamMessage is a general representation of a message within FastStream. It contains all the information required for message processing within FastStreams. It is even used to represent message batches, so the primary reason to customize it is to redefine the metadata associated with FastStream messages.

For example, you can specify your own header with the message_id semantic. This allows you to inform FastStream about this custom header through parser customization.

","boost":10},{"location":"getting-started/serialization/parser/#signature","title":"Signature","text":"

To create a custom message parser, you should write a regular Python function (synchronous or asynchronous) with the following signature:

KafkaRabbitMQNATSRedis
from aiokafka import ConsumerRecord\nfrom faststream.kafka import KafkaMessage\n\ndef parser(msg: ConsumerRecord) -> KafkaMessage:\n    ...\n
from aio_pika import IncomingMessage\nfrom faststream.rabbit import RabbitMessage\n\ndef parser(msg: IncomingMessage) -> RabbitMessage:\n    ...\n
from nats.aio.msg import Msg\nfrom faststream.nats import NatsMessage\n\ndef parser(msg: Msg) -> NatsMessage:\n    ...\n
from faststream.redis import RedisMessage\nfrom faststream.redis.message import PubSubMessage\n\ndef parser(msg: PubSubMessage) -> RedisMessage:\n    ...\n

Alternatively, you can reuse the original parser function with the following signature:

KafkaRabbitMQNATSRedis
from types import Callable, Awaitable\nfrom aiokafka import ConsumerRecord\nfrom faststream.kafka import KafkaMessage\n\nasync def parser(\n    msg: ConsumerRecord,\n    original_parser: Callable[[ConsumerRecord], Awaitable[KafkaMessage]],\n) -> KafkaMessage:\n    return await original_parser(msg)\n
from types import Callable, Awaitable\nfrom aio_pika import IncomingMessage\nfrom faststream.rabbit import RabbitMessage\n\nasync def parser(\n    msg: IncomingMessage,\n    original_parser: Callable[[IncomingMessage], Awaitable[RabbitMessage]],\n) -> RabbitMessage:\n    return await original_parser(msg)\n
from types import Callable, Awaitable\nfrom nats.aio.msg import Msg\nfrom faststream.nats import NatsMessage\n\nasync def parser(\n    msg: Msg,\n    original_parser: Callable[[Msg], Awaitable[NatsMessage]],\n) -> NatsMessage:\n    return await original_parser(msg)\n
from types import Callable, Awaitable\nfrom faststream.redis import RedisMessage\nfrom faststream.redis.message import PubSubMessage\n\nasync def parser(\n    msg: PubSubMessage,\n    original_parser: Callable[[PubSubMessage], Awaitable[RedisMessage]],\n) -> RedisMessage:\n    return await original_parser(msg)\n

The argument naming doesn't matter; the parser will always be placed as the second argument.

Note

The original parser is always an asynchronous function, so your custom parser should also be asynchronous.

Afterward, you can set this custom parser at the broker or subscriber level.

","boost":10},{"location":"getting-started/serialization/parser/#example","title":"Example","text":"

As an example, let's redefine message_id to a custom header:

KafkaRabbitMQNATSRedis
from typing import Awaitable, Callable\n\nfrom aiokafka import ConsumerRecord\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaMessage\n\n\nasync def custom_parser(\n    msg: ConsumerRecord,\n    original_parser: Callable[[ConsumerRecord], Awaitable[KafkaMessage]],\n) -> KafkaMessage:\n    parsed_msg = await original_parser(msg)\n    parsed_msg.message_id = parsed_msg.headers[\"custom_message_id\"]\n    return parsed_msg\n\n\nbroker = KafkaBroker(parser=custom_parser)\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def handle():\n    ...\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", \"test\", headers={\"custom_message_id\": \"1\"})\n
from typing import Awaitable, Callable\n\nfrom aio_pika import IncomingMessage\n\nfrom faststream import FastStream\nfrom faststream.rabbit import RabbitBroker, RabbitMessage\n\n\nasync def custom_parser(\n    msg: IncomingMessage,\n    original_parser: Callable[[IncomingMessage], Awaitable[RabbitMessage]],\n) -> RabbitMessage:\n    parsed_msg = await original_parser(msg)\n    parsed_msg.message_id = parsed_msg.headers[\"custom_message_id\"]\n    return parsed_msg\n\n\nbroker = RabbitBroker(parser=custom_parser)\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def handle():\n    ...\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", \"test\", headers={\"custom_message_id\": \"1\"})\n
from typing import Awaitable, Callable\n\nfrom nats.aio.msg import Msg\n\nfrom faststream import FastStream\nfrom faststream.nats import NatsBroker, NatsMessage\n\n\nasync def custom_parser(\n    msg: Msg,\n    original_parser: Callable[[Msg], Awaitable[NatsMessage]],\n) -> NatsMessage:\n    parsed_msg = await original_parser(msg)\n    parsed_msg.message_id = parsed_msg.headers[\"custom_message_id\"]\n    return parsed_msg\n\n\nbroker = NatsBroker(parser=custom_parser)\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def handle():\n    ...\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", \"test\", headers={\"custom_message_id\": \"1\"})\n
from typing import Awaitable, Callable\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker, RedisMessage\nfrom faststream.redis.message import PubSubMessage\n\n\nasync def custom_parser(\n    msg: PubSubMessage,\n    original_parser: Callable[[PubSubMessage], Awaitable[RedisMessage]],\n) -> RedisMessage:\n    parsed_msg = await original_parser(msg)\n    parsed_msg.message_id = parsed_msg.headers[\"custom_message_id\"]\n    return parsed_msg\n\n\nbroker = RedisBroker(parser=custom_parser)\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def handle():\n    ...\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", \"test\", headers={\"custom_message_id\": \"1\"})\n
","boost":10},{"location":"getting-started/subscription/","title":"Subscription Basics","text":"

FastStream provides a Message Broker agnostic way to subscribe to event streams.

You need not even know about topics/queues/subjects or any broker inner objects you use. The basic syntax is the same for all brokers:

KafkaRabbitMQNATSRedis
from faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker()\n\n@broker.subscriber(\"test\")  # topic name\nasync def handle_msg(msg_body):\n    ...\n
from faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker()\n\n@broker.subscriber(\"test\")  # queue name\nasync def handle_msg(msg_body):\n    ...\n
from faststream.nats import NatsBroker\n\nbroker = NatsBroker()\n\n@broker.subscriber(\"test\")  # subject name\nasync def handle_msg(msg_body):\n    ...\n
from faststream.redis import RedisBroker\n\nbroker = RedisBroker()\n\n@broker.subscriber(\"test\")  # channel name\nasync def handle_msg(msg_body):\n    ...\n

Tip

If you want to use Message Broker specific features, please visit the corresponding broker documentation section. In the Tutorial section, the general features are described.

Also, synchronous functions are supported as well:

KafkaRabbitMQNATSRedis
from faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker()\n\n@broker.subscriber(\"test\")  # topic name\ndef handle_msg(msg_body):\n    ...\n
from faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker()\n\n@broker.subscriber(\"test\")  # queue name\ndef handle_msg(msg_body):\n    ...\n
from faststream.nats import NatsBroker\n\nbroker = NatsBroker()\n\n@broker.subscriber(\"test\")  # subject name\ndef handle_msg(msg_body):\n    ...\n
from faststream.redis import RedisBroker\n\nbroker = RedisBroker()\n\n@broker.subscriber(\"test\")  # channel name\ndef handle_msg(msg_body):\n    ...\n
","boost":10},{"location":"getting-started/subscription/#message-body-serialization","title":"Message Body Serialization","text":"

Generally, FastStream uses your function type annotation to serialize incoming message body with Pydantic. This is similar to how FastAPI works (if you are familiar with it).

@broker.subscriber(\"test\")\nasync def handle_str(\n    msg_body: str,\n):\n    ...\n

You can also access some extra features through the function arguments, such as Depends and Context if required.

However, you can easily disable Pydantic validation by creating a broker with the following option Broker(apply_types=False) (this also disables Context and Depends features).

This way FastStream still consumes json.loads result, but without pydantic validation and casting.

KafkaRabbitMQNATSRedis
from faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(apply_types=False)\n\n@broker.subscriber(\"test\")\nasync def handle_msg(msg_body: str):  # just an annotation, has no real effect\n    ...\n
from faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(apply_types=False)\n\n@broker.subscriber(\"test\")\nasync def handle_msg(msg_body: str):  # just an annotation, has no real effect\n    ...\n
from faststream.nats import NatsBroker\n\nbroker = NatsBroker(apply_types=False)\n\n@broker.subscriber(\"test\")\nasync def handle_msg(msg_body: str):  # just an annotation, has no real effect\n    ...\n
from faststream.redis import RedisBroker\n\nbroker = RedisBroker(apply_types=False)\n\n@broker.subscriber(\"test\")\nasync def handle_msg(msg_body: str):  # just an annotation, has no real effect\n    ...\n
","boost":10},{"location":"getting-started/subscription/#multiple-subscriptions","title":"Multiple Subscriptions","text":"

You can also subscribe to multiple event streams at the same time with one function. Just wrap it with multiple @broker.subscriber(...) decorators (they have no effect on each other).

@broker.subscriber(\"first_sub\")\n@broker.subscriber(\"second_sub\")\nasync def handler(msg):\n    ...\n
","boost":10},{"location":"getting-started/subscription/annotation/","title":"Annotation Serialization","text":"","boost":10},{"location":"getting-started/subscription/annotation/#basic-usage","title":"Basic usage","text":"

As you already know, FastStream serializes your incoming message body according to the function type annotations using Pydantic.

So, there are some valid usecases:

@broker.subscriber(\"test\")\nasync def handle(\n    msg: str,\n):\n    ...\n\n@broker.subscriber(\"test\")\nasync def handle(\n    msg: bytes,\n):\n    ...\n\n@broker.subscriber(\"test\")\nasync def handle(\n    msg: int,\n):\n    ...\n

As with other Python primitive types as well (float, bool, datetime, etc)

Note

If the incoming message cannot be serialized by the described schema, FastStream raises a pydantic.ValidationError with a correct log message.

Also, thanks to Pydantic (again), FastStream is able to serialize (and validate) more complex types like pydantic.HttpUrl, pydantic.PostitiveInt, etc.

","boost":10},{"location":"getting-started/subscription/annotation/#json-basic-serialization","title":"JSON Basic Serialization","text":"

But how can we serialize more complex message, like { \"name\": \"John\", \"user_id\": 1 } ?

For sure, we can serialize it as a simple dict

from typing import Dict, Any\n\n@broker.subscriber(\"test\")\nasync def handle(\n    msg: dict[str, Any],\n):\n    ...\n

But it doesn't looks like a correct message validation, does it?

For this reason, FastStream supports per-argument message serialization: you can declare multiple arguments with various types and your message will unpack to them:

KafkaRabbitMQNATSRedis
@broker.subscriber(\"test-topic\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
@broker.subscriber(\"test-queue\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
@broker.subscriber(\"test-subject\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
@broker.subscriber(\"test-channel\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
","boost":10},{"location":"getting-started/subscription/filtering/","title":"Application-level Filtering","text":"

FastStream also allows you to specify the message processing way using message headers, body type or something else. The filter feature enables you to consume various messages with different schemas within a single event stream.

Tip

Message must be consumed at ONCE (crossing filters are not allowed)

As an example, let's create a subscriber for both JSON and non-JSON messages:

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    \"test-topic\",\n    filter=lambda msg: msg.content_type == \"application/json\",\n)\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\n\n@broker.subscriber(\"test-topic\")\nasync def default_handler(msg: str):\n    assert msg == \"Hello, FastStream!\"\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    \"test-queue\",\n    filter=lambda msg: msg.content_type == \"application/json\",\n)\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\n\n@broker.subscriber(\"test-queue\")\nasync def default_handler(msg: str):\n    assert msg == \"Hello, FastStream!\"\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    \"test-subject\",\n    filter=lambda msg: msg.content_type == \"application/json\",\n)\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\n\n@broker.subscriber(\"test-subject\")\nasync def default_handler(msg: str):\n    assert msg == \"Hello, FastStream!\"\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    \"test-channel\",\n    filter=lambda msg: msg.content_type == \"application/json\",\n)\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\n\n@broker.subscriber(\"test-channel\")\nasync def default_handler(msg: str):\n    assert msg == \"Hello, FastStream!\"\n

Note

A subscriber without a filter is a default subscriber. It consumes messages that have not been consumed yet.

For now, the following message will be delivered to the handle function

KafkaRabbitMQNATSRedis
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    topic=\"test-topic\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    queue=\"test-queue\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    subject=\"test-subject\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    channel=\"test-channel\",\n)\n

And this one will be delivered to the default_handler

KafkaRabbitMQNATSRedis
await broker.publish(\n    \"Hello, FastStream!\",\n    topic=\"test-topic\",\n)\n
await broker.publish(\n    \"Hello, FastStream!\",\n    queue=\"test-queue\",\n)\n
await broker.publish(\n    \"Hello, FastStream!\",\n    subject=\"test-subject\",\n)\n
await broker.publish(\n    \"Hello, FastStream!\",\n    channel=\"test-channel\",\n)\n
","boost":10},{"location":"getting-started/subscription/pydantic/","title":"Pydantic Serialization","text":"","boost":10},{"location":"getting-started/subscription/pydantic/#pydanticfield","title":"pydantic.Field","text":"

Besides, FastStream uses your handlers' annotations to collect information about the application schema and generate AsyncAPI schema.

You can access this information with extra details using pydantic.Field (such as title, description and examples). Additionally, Fields usage allows you to add extra validations to your message schema.

Just use pydantic.Field as a function default argument:

KafkaRabbitMQNATSRedis
from pydantic import Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    ),\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    ),\n):\n    assert name == \"John\"\n    assert user_id == 1\n
from pydantic import Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    ),\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    ),\n):\n    assert name == \"John\"\n    assert user_id == 1\n
from pydantic import Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    ),\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    ),\n):\n    assert name == \"John\"\n    assert user_id == 1\n
from pydantic import Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    ),\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    ),\n):\n    assert name == \"John\"\n    assert user_id == 1\n

Tip

Also you can use typing.Annotated (python 3.9+) or typing_extensions.Annotated to declare your handler fields

name: Annotated[\n    str,\n    Field(..., examples=[\"John\"], description=\"Registered user name\")\n],\nuser_id: Annotated[\n    NonNegativeInt,\n    Field(..., examples=[1], description=\"Registered user id\"),\n]\n
","boost":10},{"location":"getting-started/subscription/pydantic/#pydanticbasemodel","title":"pydantic.BaseModel","text":"

To make your message schema reusable between different subscribers and publishers, you can decalre it as a pydantic.BaseModel and use it as a single message annotation:

KafkaRabbitMQNATSRedis
from pydantic import BaseModel, Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\nclass UserInfo(BaseModel):\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    )\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    )\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    user: UserInfo,\n):\n    assert user.name == \"John\"\n    assert user.user_id == 1\n
from pydantic import BaseModel, Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\nclass UserInfo(BaseModel):\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    )\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    )\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    user: UserInfo,\n):\n    assert user.name == \"John\"\n    assert user.user_id == 1\n
from pydantic import BaseModel, Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\nclass UserInfo(BaseModel):\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    )\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    )\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    user: UserInfo,\n):\n    assert user.name == \"John\"\n    assert user.user_id == 1\n
from pydantic import BaseModel, Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\nclass UserInfo(BaseModel):\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    )\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    )\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    user: UserInfo,\n):\n    assert user.name == \"John\"\n    assert user.user_id == 1\n
","boost":10},{"location":"getting-started/subscription/test/","title":"Subscriber Testing","text":"

Testability is a crucial part of any application, and FastStream provides you with the tools to test your code easily.

","boost":10},{"location":"getting-started/subscription/test/#original-application","title":"Original Application","text":"

Let's take a look at the original application to test

KafkaRabbitMQNATSRedis annotation_kafka.py
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
annotation_rabbit.py
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
annotation_nats.py
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
annotation_redis.py
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n

It consumes JSON messages like { \"name\": \"username\", \"user_id\": 1 }

You can test your consume function like a regular one, for sure:

@pytest.mark.asyncio\nasync def test_handler():\n    await handle(\"John\", 1)\n

But if you want to test your function closer to your real runtime, you should use the special FastStream test client.

","boost":10},{"location":"getting-started/subscription/test/#in-memory-testing","title":"In-Memory Testing","text":"

Deploying a whole service with a Message Broker is a bit too much just for testing purposes, especially in your CI environment. Not to mention the possible loss of messages due to network failures when working with real brokers.

For this reason, FastStream has a special TestClient to make your broker work in InMemory mode.

Just use it like a regular async context manager - all published messages will be routed in-memory (without any external dependencies) and consumed by the correct handler.

KafkaRabbitMQNATSRedis
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.kafka import TestKafkaBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestKafkaBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, topic=\"test-topic\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.rabbit import TestRabbitBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRabbitBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, queue=\"test-queue\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.nats import TestNatsBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestNatsBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, subject=\"test-subject\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.redis import TestRedisBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRedisBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, channel=\"test-channel\")\n
","boost":10},{"location":"getting-started/subscription/test/#catching-exceptions","title":"Catching Exceptions","text":"

This way you can catch any exceptions that occur inside your handler:

KafkaRabbitMQNATSRedis
@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestKafkaBroker(broker) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", topic=\"test-topic\")\n
@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestRabbitBroker(broker) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", queue=\"test-queue\")\n
@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestNatsBroker(broker) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", subject=\"test-subject\")\n
@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestRedisBroker(broker) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", channel=\"test-channel\")\n
","boost":10},{"location":"getting-started/subscription/test/#validates-input","title":"Validates Input","text":"

Also, your handler has a mock object to validate your input or call counts.

KafkaRabbitMQNATSRedis
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestKafkaBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, topic=\"test-topic\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRabbitBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, queue=\"test-queue\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestNatsBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, subject=\"test-subject\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRedisBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, channel=\"test-channel\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n

Note

The Handler mock has a not-serialized JSON message body. This way you can validate the incoming message view, not python arguments.

Thus our example checks not mock.assert_called_with(name=\"John\", user_id=1), but mock.assert_called_with({ \"name\": \"John\", \"user_id\": 1 }).

You should be careful with this feature: all mock objects will be cleared when the context manager exits.

KafkaRabbitMQNATSRedis
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestKafkaBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, topic=\"test-topic\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRabbitBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, queue=\"test-queue\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestNatsBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, subject=\"test-subject\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRedisBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, channel=\"test-channel\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n
","boost":10},{"location":"getting-started/subscription/test/#real-broker-testing","title":"Real Broker Testing","text":"

If you want to test your application in a real environment, you shouldn't have to rewrite all your tests: just pass with_real optional parameter to your TestClient context manager. This way, TestClient supports all the testing features but uses an unpatched broker to send and consume messages.

KafkaRabbitMQNATSRedis
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.kafka import TestKafkaBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestKafkaBroker(broker, with_real=True) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, topic=\"test-topic\")\n        await handle.wait_call(timeout=3)\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n\n@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestKafkaBroker(broker, with_real=True) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", topic=\"test-topic\")\n            await handle.wait_call(timeout=3)\n\n        handle.mock.assert_called_once_with(\"wrong message\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.rabbit import TestRabbitBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRabbitBroker(broker, with_real=True) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, queue=\"test-queue\")\n        await handle.wait_call(timeout=3)\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n\n@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestRabbitBroker(broker, with_real=True) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", queue=\"test-queue\")\n            await handle.wait_call(timeout=3)\n\n        handle.mock.assert_called_once_with(\"wrong message\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.nats import TestNatsBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestNatsBroker(broker, with_real=True) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, subject=\"test-subject\")\n        await handle.wait_call(timeout=3)\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n\n@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestNatsBroker(broker, with_real=True) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", subject=\"test-subject\")\n            await handle.wait_call(timeout=3)\n\n        handle.mock.assert_called_once_with(\"wrong message\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.redis import TestRedisBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRedisBroker(broker, with_real=True) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, channel=\"test-channel\")\n        await handle.wait_call(timeout=3)\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n\n@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestRedisBroker(broker, with_real=True) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", channel=\"test-channel\")\n            await handle.wait_call(timeout=3)\n\n        handle.mock.assert_called_once_with(\"wrong message\")\n

Tip

When you're using a patched broker to test your consumers, the publish method is called synchronously with a consumer one, so you need not wait until your message is consumed. But in the real broker's case, it doesn't.

For this reason, you have to wait for message consumption manually with the special handler.wait_call(timeout) method. Also, inner handler exceptions will be raised in this function, not broker.publish(...).

","boost":10},{"location":"getting-started/subscription/test/#a-little-tip","title":"A Little Tip","text":"

It can be very helpful to set the with_real flag using an environment variable. This way, you will be able to choose the testing mode right from the command line:

WITH_REAL=True/False pytest ...\n

To learn more about managing your application configiruation visit this page.

","boost":10},{"location":"getting-started/template/","title":"Using Cookiecutter FastStream Template","text":"

Cookiecutter FastStream is a versatile repository that provides a solid foundation for your Python projects. It comes with a basic application, testing infrastructure, linting scripts, and various development tools to kickstart your development process. Whether you're building a new application from scratch or want to enhance an existing one, this template will save you time and help you maintain high code quality.

","boost":5},{"location":"getting-started/template/#features","title":"Features","text":"","boost":5},{"location":"getting-started/template/#getting-started","title":"Getting Started","text":"

To set up your development environment, follow these steps:

  1. Install the cookiecutter package using the following command:

    pip install cookiecutter\n

  2. Run the provided cookiecutter command and fill out the relevant details to generate a new FastStream project:

    cookiecutter https://github.com/airtai/cookiecutter-faststream.git\n
    The following screenshot illustrates the process of creating a new FastStream app with Kafka using the above command:

  3. Change the working directory to the newly created directory:

    cd <directory-name>\n

    NOTE: Replace <directory-name> with the name of your directory.

  4. Install all development requirements using pip:

    pip install -e \".[dev]\"\n

  5. Create a new repository for our FastStream app on GitHub.

  6. Add all the files, commit and push using the following commands:

    git init\ngit add .\ngit commit -m \"first commit\"\ngit branch -M main\ngit remote add origin git@github.com:<username>/<repo-name>.git\ngit push -u origin main\n

    NOTE: Replace <username> with your GitHub username and <repo-name> with the name of your repository in the above commands.

","boost":5},{"location":"getting-started/template/#development","title":"Development","text":"

The application code is located in the app/ directory. You can add new features or fix bugs in this directory. However, remember that code changes must be accompanied by corresponding updates to the tests located in the tests/ directory.

","boost":5},{"location":"getting-started/template/#running-tests","title":"Running Tests","text":"

Once you have updated tests, you can execute the tests using pytest:

pytest\n
","boost":5},{"location":"getting-started/template/#running-faststream-application-locally","title":"Running FastStream Application Locally","text":"

To run the FastStream application locally, follow these steps:

  1. Start the Kafka Docker container locally using the provided script:

    ./scripts/start_kafka_broker_locally.sh\n

  2. Start the FastStream application with the following command:

    faststream run <directory-name>.application:app --workers 1\n

    NOTE: Replace <directory-name> with the directory that is automatically generated from the project slug name and contains the app.py file.

  3. You can now send messages to the Kafka topic and can test the application. Optionally, if you want to view messages in a topic, you can subscribe to it using the provided script:

    ./scripts/subscribe_to_kafka_broker_locally.sh <topic_name>\n

  4. To stop the FastStream application, press Ctrl+C.

  5. Finally, stop the Kafka Docker container by running the script:

    ./scripts/stop_kafka_broker_locally.sh\n

","boost":5},{"location":"getting-started/template/#building-and-testing-docker-image-locally","title":"Building and Testing Docker Image Locally","text":"

If you'd like to build and test the Docker image locally, follow these steps:

  1. Run the provided script to build the Docker image locally. Use the following command:

    ./scripts/build_docker.sh <username> <repo-name>\n
    This script will build the Docker image locally with the same name as the one built in CI.

  2. Before starting the Docker container, ensure that a Kafka Docker container is running locally. You can start it using the provided script:

    ./scripts/start_kafka_broker_locally.sh\n

  3. Once Kafka is up and running, you can start the local Docker container using the following command:

    docker run --rm --name faststream-app --net=host ghcr.io/<username>/<repo-name>:latest\n
    --rm: This flag removes the container once it stops running, ensuring that it doesn't clutter your system with unused containers. --name faststream-app: Assigns a name to the running container, in this case, \"faststream-app\". --net=host: This flag allows the Docker container to share the host's network namespace.

  4. To stop the local Docker container, simply press Ctrl+C in your terminal.

  5. Finally, stop the Kafka Docker container by running the provided script:

    ./scripts/stop_kafka_broker_locally.sh\n

NOTE: Replace <username> with your GitHub username and <repo-name> with the name of your repository in the above commands.

","boost":5},{"location":"getting-started/template/#code-linting","title":"Code Linting","text":"

After making changes to the code, it's essential to ensure it adheres to coding standards. We provide a script to help you with code formatting and linting. Run the following script to automatically fix linting issues:

./scripts/lint.sh\n
","boost":5},{"location":"getting-started/template/#static-analysis","title":"Static Analysis","text":"

Static analysis tools mypy and bandit can help identify potential issues in your code. To run static analysis, use the following script:

./scripts/static-analysis.sh\n

If there are any static analysis errors, resolve them in your code and rerun the script until it passes successfully.

","boost":5},{"location":"getting-started/template/#viewing-asyncapi-documentation","title":"Viewing AsyncAPI Documentation","text":"

FastStream framework supports AsyncAPI documentation. To ensure that your changes are reflected in the AsyncAPI documentation, follow these steps:

  1. Run the following command to view the AsyncAPI documentation:

    faststream docs serve <directory-name>.application:app\n
    This command builds the AsyncAPI specification file, generates AsyncAPI documentation based on the specification, and serves it at localhost:8000.

    NOTE: Replace <directory-name> with the directory that is automatically generated from the project slug name and contains the app.py file.

  2. Open your web browser and navigate to http://localhost:8000 to view the AsyncAPI documentation reflecting your changes.

  3. To stop the AsyncAPI documentation server, press Ctrl+C.

","boost":5},{"location":"getting-started/template/#contributing","title":"Contributing","text":"

Once you have successfully completed all the above steps, you are ready to contribute your changes:

  1. Add and commit your changes:

    git add .\ngit commit -m \"Your commit message\"\n

  2. Push your changes to GitHub:

    git push origin your-branch\n

  3. Create a merge request on GitHub.

","boost":5},{"location":"getting-started/template/#continuous-integration-ci","title":"Continuous Integration (CI)","text":"

This repository is equipped with GitHub Actions that automate static analysis and pytest in the CI pipeline. Even if you forget to perform any of the required steps, CI will catch any issues before merging your changes.

This repository has three workflows, each triggered when code is pushed:

  1. Tests Workflow: This workflow is named \"Tests\" and consists of two jobs. The first job runs static analysis tools mypy and bandit to identify potential issues in the codebase. The second job runs tests using pytest to ensure the functionality of the application. Both jobs run simultaneously to expedite the CI process.

  2. Build Docker Image Workflow: This workflow is named \"Build Docker Image\" and has one job. In this job, a Docker image is built based on the provided Dockerfile. The built image is then pushed to the GitHub Container Registry, making it available for deployment or other purposes.

  3. Deploy FastStream AsyncAPI Docs Workflow: The final workflow is named \"Deploy FastStream AsyncAPI Docs\" and also consists of a single job. In this job, the AsyncAPI documentation is built from the specification, and the resulting documentation is deployed to GitHub Pages. This allows for easy access and sharing of the AsyncAPI documentation with the project's stakeholders.

","boost":5},{"location":"getting-started/template/#viewing-asyncapi-documentation-hosted-at-github-pages","title":"Viewing AsyncAPI Documentation Hosted at GitHub Pages","text":"

After the Deploy FastStream AsyncAPI Docs workflow in CI has been successfully completed, the AsyncAPI documentation is automatically deployed to GitHub Pages. This provides a convenient way to access and share the documentation with project stakeholders.

To view the deployed AsyncAPI documentation, open your web browser and navigate to the following URL:

https://<username>.github.io/<repo-name>/\n

NOTE: Replace <username> with your GitHub username and <repo-name> with the name of your repository.

You will be directed to the GitHub Pages site where your AsyncAPI documentation is hosted. This hosted documentation allows you to easily share your AsyncAPI specifications with others and provides a centralized location for reviewing the AsyncAPI documentation.

","boost":5},{"location":"getting-started/template/#deploying-docker-container","title":"Deploying Docker Container","text":"

Once the Build Docker Image workflow in CI has successfully completed, the built Docker image is pushed to the GitHub Container Registry. You can then deploy this image on your server by following these steps:

  1. Pull the Docker image from the GitHub Container Registry to your server using the following command:

    docker pull ghcr.io/<username>/<repo-name>:latest\n

    NOTE: Replace <username> with your GitHub username and <repo-name> with the name of your repository.

  2. After successfully pulling the image, start the Docker container using the following command:

    docker run --rm --name faststream-app --env-file /path/to/env-file ghcr.io/<username>/<repo-name>:latest\n
    --rm: This flag removes the container once it stops running, ensuring that it doesn't clutter your system with unused containers. --name faststream-app: Assigns a name to the running container, in this case, \"faststream-app\". --env-file /path/to/env-file: Specifies the path to an environment file (commonly a .env file) that contains environment variables required by your FastStream application. Storing secrets and configuration in an environment file is a secure and best practice for handling sensitive information such as Kafka host, port, and authentication details.

By following these steps, you can easily deploy your FastStream application as a Docker container on your server. Remember to customize the env-file and other environment variables as needed to suit your specific application requirements.

","boost":5},{"location":"kafka/","title":"Kafka Routing","text":"","boost":10},{"location":"kafka/#kafka-overview","title":"Kafka Overview","text":"","boost":10},{"location":"kafka/#what-is-kafka","title":"What is Kafka?","text":"

Kafka is an open-source distributed streaming platform developed by the Apache Software Foundation. It is designed to handle high-throughput, fault-tolerant, real-time data streaming. Kafka is widely used for building real-time data pipelines and streaming applications.

","boost":10},{"location":"kafka/#key-kafka-concepts","title":"Key Kafka Concepts","text":"","boost":10},{"location":"kafka/#1-publish-subscribe-model","title":"1. Publish-Subscribe Model","text":"

Kafka is built around the publish-subscribe messaging model. In this model, data is published to topics, and multiple consumers can subscribe to these topics to receive the data. This decouples the producers of data from the consumers, allowing for flexibility and scalability.

","boost":10},{"location":"kafka/#2-topics","title":"2. Topics","text":"

A topic in Kafka is a logical channel or category to which messages are published by producers and from which messages are consumed by consumers. Topics are used to organize and categorize data streams. Each topic can have multiple partitions, which enable Kafka to distribute data and provide parallelism for both producers and consumers.

","boost":10},{"location":"kafka/#kafka-topics","title":"Kafka Topics","text":"","boost":10},{"location":"kafka/#understanding-kafka-topics","title":"Understanding Kafka Topics","text":"

Topics are fundamental to Kafka and serve as the central point of data distribution. Here are some key points about topics:

","boost":10},{"location":"kafka/#faststream-kafkabroker","title":"FastStream KafkaBroker","text":"

The FastStream KafkaBroker is a key component of the FastStream framework that enables seamless integration with Apache Kafka. With the KafkaBroker, developers can easily connect to Kafka brokers, produce messages to Kafka topics, and consume messages from Kafka topics within their FastStream applications.

","boost":10},{"location":"kafka/#establishing-a-connection","title":"Establishing a Connection","text":"

To connect to Kafka using the FastStream KafkaBroker module, follow these steps:

  1. Initialize the KafkaBroker instance: Start by initializing a KafkaBroker instance with the necessary configuration, including Kafka broker address.

  2. Create your processing logic: Write a function that will consume the incoming messages in the defined format and produce a response to the defined topic

  3. Decorate your processing function: To connect your processing function to the desired Kafka topics you need to decorate it with @broker.subscriber(...) and @broker.publisher(...) decorators. Now, after you start your application, your processing function will be called whenever a new message in the subscribed topic is available and produce the function return value to the topic defined in the publisher decorator.

Here's a simplified code example demonstrating how to establish a connection to Kafka using FastStream's KafkaBroker module:

from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-topic\")\n@broker.publisher(\"out-topic\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n

This minimal example illustrates how FastStream simplifies the process of connecting to Kafka and performing basic message processing from the in_topic to the out-topic. Depending on your specific use case and requirements, you can further customize your Kafka integration with FastStream to build robust and efficient streaming applications.

For more advanced configuration options and detailed usage instructions, please refer to the FastStream Kafka documentation and the offical Kafka documentation.

","boost":10},{"location":"kafka/ack/","title":"Consuming Acknowledgements","text":"

As you may know, Kafka consumer should commit a topic offset when consuming a message.

The default behaviour, also implemented as such in the FastStream, automatically commits (acks) topic offset on message consumption. This is the at most once consuming strategy.

However, if you wish to use at least once strategy, you should commit offset AFTER the message is processed correctly. To accomplish that, set a consumer group and disable auto_commit option like this:

@broker.subscriber(\n    \"test\", group_id=\"group\", auto_commit=False\n)\nasync def base_handler(body: str):\n    ...\n

This way, upon successful return of the processing function, the message processed will be acknowledged. In the case of an exception being raised, the message will not be acknowledged.

However, there are situations where you might want to use a different acknowledgement logic.

","boost":10},{"location":"kafka/ack/#manual-acknowledgement","title":"Manual Acknowledgement","text":"

If you want to acknowledge a message manually, you can get direct access to the message object via the Context and acknowledge the message by calling the ack method:

from faststream.kafka.annotations import KafkaMessage\n\n\n@broker.subscriber(\n    \"test\", group_id=\"group\", auto_commit=False\n)\nasync def base_handler(body: str, msg: KafkaMessage):\n    await msg.ack()\n    # or\n    await msg.nack()\n

Tip

You can use the nack method to prevent offset commit and the message can be consumed by another consumer within the same group.

FastStream will see that the message was already acknowledged and will do nothing at the end of the process.

","boost":10},{"location":"kafka/ack/#interrupt-process","title":"Interrupt Process","text":"

If you wish to interrupt the processing of a message at any call stack level and acknowledge the message, you can achieve that by raising the faststream.exceptions.AckMessage.

from faststream import FastStream\nfrom faststream.exceptions import AckMessage\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    \"test-topic\", group_id=\"test-group\", auto_commit=False\n)\nasync def handle(body):\n    smth_processing(body)\n\n\ndef smth_processing(body):\n    if True:\n        raise AckMessage()\n\n\n@app.after_startup\nasync def test_publishing():\n    await broker.publish(\"Hello!\", \"test-topic\")\n

This way, FastStream interrupts the current message processing and acknowledges it immediately. Similarly, you can raise NackMessage as well to prevent the message from being committed.

Tip

If you want to disable FastStream Acknowledgement logic at all, you can use @broker.subscriber(..., no_ack=True) option. This way you should always process a message (ack/nack/terminate/etc) by yourself.

","boost":10},{"location":"kafka/message/","title":"Access to Message Information","text":"

As you may know, FastStream serializes a message body and provides you access to it through function arguments. However, there are times when you need to access additional message attributes such as offsets, headers, or other metadata.

","boost":10},{"location":"kafka/message/#message-access","title":"Message Access","text":"

You can easily access this information by referring to the message object in the Context

This object serves as a unified FastStream wrapper around the native broker library message (for example, aiokafka.ConsumerRecord in the case of Kafka). It contains most of the required information, including:

For example, if you would like to access the headers of an incoming message, you would do so like this:

from faststream.kafka import KafkaMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    msg: KafkaMessage,\n):\n    print(msg.headers)\n
","boost":10},{"location":"kafka/message/#message-fields-access","title":"Message Fields Access","text":"

In most cases, you don't need all message fields; you need to know just a part of them. You can use Context Fields access feature for this.

For example, you can get access to the headers like this:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    headers: str = Context(\"message.headers\"),\n):\n    print(headers)\n
","boost":10},{"location":"kafka/message/#headers-access","title":"Headers Access","text":"

Sure, you can get access to a raw message and get the headers dict itself, but more often you just need a single header field. So, you can easily access it using the Context:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Context(\"message.headers.user\"),\n):\n    ...\n

Using the special Header class is more convenient, as it also validates the header value using Pydantic. It works the same way as Context, but it is just a shorcut to Context with a default setup. So, you already know how to use it:

from faststream import Header\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Header(),\n):\n    ...\n
","boost":10},{"location":"kafka/security/","title":"FastStream Kafka Security","text":"

This chapter discusses the security options available in FastStream and how to use them.

","boost":10},{"location":"kafka/security/#security-objects","title":"Security Objects","text":"

FastStream allows you to enhance the security of applications by using security objects when creating brokers. These security objects encapsulate security-related configurations and mechanisms. Security objects supported in FastStream are (More are planned in the future such as SASL OAuth):

","boost":10},{"location":"kafka/security/#1-basesecurity-object","title":"1. BaseSecurity Object","text":"

Purpose: The BaseSecurity object wraps ssl.SSLContext object and is used to enable SSL/TLS encryption for secure communication between FastStream services and external components such as message brokers.

Usage:

import ssl\n\nfrom faststream.kafka import KafkaBroker\nfrom faststream.security import BaseSecurity\n\nssl_context = ssl.create_default_context()\nsecurity = BaseSecurity(ssl_context=ssl_context)\n\nbroker = KafkaBroker(\"localhost:9092\", security=security)\n
","boost":10},{"location":"kafka/security/#2-saslplaintext-object-with-ssltls","title":"2. SASLPlaintext Object with SSL/TLS","text":"

Purpose: The SASLPlaintext object is used for authentication in SASL (Simple Authentication and Security Layer) plaintext mode. It allows you to provide a username and password for authentication.

Usage:

import ssl\n\nfrom faststream.kafka import KafkaBroker\nfrom faststream.security import SASLPlaintext\n\nssl_context = ssl.create_default_context()\nsecurity = SASLPlaintext(\n    ssl_context=ssl_context,\n    username=\"admin\",\n    password=\"password\", \n)\n\nbroker = KafkaBroker(\"localhost:9092\", security=security)\n

Using any SASL authentication without SSL:

The following example will log a RuntimeWarning:

SASLPlaintext(username=\"admin\", password=\"password\")\n

If the user does not want to use SSL encryption without the waringning getting logged, they must explicitly set the use_ssl parameter to False when creating a SASL object.

SASLPlaintext(username=\"admin\", password=\"password\", use_ssl=False) \n
","boost":10},{"location":"kafka/security/#3-saslscram256512-object-with-ssltls","title":"3. SASLScram256/512 Object with SSL/TLS","text":"

Purpose: The SASLScram256 and SASLScram512 objects are used for authentication using the Salted Challenge Response Authentication Mechanism (SCRAM).

Usage:

SCRAM256SCRAM512
import ssl\n\nfrom faststream.kafka import KafkaBroker\nfrom faststream.security import SASLScram256\n\nssl_context = ssl.create_default_context()\nsecurity = SASLScram256(\n    ssl_context=ssl_context,\n    username=\"admin\",\n    password=\"password\", \n)\n\nbroker = KafkaBroker(\"localhost:9092\", security=security)\n
import ssl\n\nfrom faststream.kafka import KafkaBroker\nfrom faststream.security import SASLScram512\n\nssl_context = ssl.create_default_context()\nsecurity = SASLScram512(\n    ssl_context=ssl_context,\n    username=\"admin\",\n    password=\"password\", \n)\n\nbroker = KafkaBroker(\"localhost:9092\", security=security)\n
","boost":10},{"location":"kafka/Publisher/","title":"Publishing","text":"

The FastStream KafkaBroker supports all regular publishing use cases, and you can use them without any changes.

However, if you wish to further customize the publishing logic, you should take a closer look at specific KafkaBroker parameters.

","boost":10},{"location":"kafka/Publisher/#basic-kafka-publishing","title":"Basic Kafka Publishing","text":"

The KafkaBroker uses the unified publish method (from a producer object) to send messages.

In this case, you can use Python primitives and pydantic.BaseModel to define the content of the message you want to publish to the Kafka broker.

You can specify the topic to send by its name.

  1. Create your KafkaBroker instance

    broker = KafkaBroker(\"localhost:9092\")\n
  2. Publish a message using the publish method

    msg = Data(data=0.5)\n\nawait broker.publish(\n    model_to_json(msg),\n    \"input_data\",\n    headers={\"content-type\": \"application/json\"},\n)\n

This is the most basic way of using the KafkaBroker to publish a message.

","boost":10},{"location":"kafka/Publisher/#creating-a-publisher-object","title":"Creating a publisher object","text":"

The simplest way to use a KafkaBroker for publishing has a significant limitation: your publishers won't be documented in the AsyncAPI documentation. This might be acceptable for sending occasional one-off messages. However, if you're building a comprehensive service, it's recommended to create publisher objects. These objects can then be parsed and documented in your service's AsyncAPI documentation. Let's go ahead and create those publisher objects!

  1. Create your KafkaBroker instance

    broker = KafkaBroker(\"localhost:9092\")\n
  2. Create a publisher instance

    prepared_publisher = broker.publisher(\"input_data\")\n
  3. Publish a message using the publish method of the prepared publisher

    msg = Data(data=0.5)\n\nawait prepared_publisher.publish(\n    model_to_json(msg),\n    headers={\"content-type\": \"application/json\"},\n)\n

Now, when you wrap your broker into a FastStream object, the publisher will be exported to the AsyncAPI documentation.

","boost":10},{"location":"kafka/Publisher/#decorating-your-publishing-functions","title":"Decorating your publishing functions","text":"

To publish messages effectively in the Kafka context, consider utilizing the Publisher Decorator. This approach offers an AsyncAPI representation and is ideal for rapidly developing applications.

The Publisher Decorator creates a structured DataPipeline unit with both input and output components. The sequence in which you apply Subscriber and Publisher decorators does not affect their functionality. However, note that these decorators can only be applied to functions decorated by a Subscriber as well.

This method relies on the return type annotation of the handler function to properly interpret the function's return value before sending it. Hence, it's important to ensure accuracy in defining the return type.

Let's start by examining the entire application that utilizes the Publisher Decorator and then proceed to walk through it step by step.

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\nto_output_data = broker.publisher(\"output_data\")\n\n\n@to_output_data\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
  1. Initialize the KafkaBroker instance: Start by initializing a KafkaBroker instance with the necessary configuration, including Kafka broker address.

    broker = KafkaBroker(\"localhost:9092\")\n
  2. Prepare your publisher object to use later as a decorator:

    to_output_data = broker.publisher(\"output_data\")\n
  3. Create your processing logic: Write a function that will consume the incoming messages in the defined format and produce a response to the defined topic

    async def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
  4. Decorate your processing function: To connect your processing function to the desired Kafka topics you need to decorate it with @broker.subscriber(...) and @broker.publisher(...) decorators. Now, after you start your application, your processing function will be called whenever a new message in the subscribed topic is available and produce the function return value to the topic defined in the publisher decorator.

    @to_output_data\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
","boost":10},{"location":"kafka/Publisher/batch_publisher/","title":"Publishing in Batches","text":"","boost":10},{"location":"kafka/Publisher/batch_publisher/#general-overview","title":"General Overview","text":"

If you need to send your data in batches, the @broker.publisher(...) decorator offers a convenient way to achieve this. To enable batch production, you need to perform two crucial steps:

  1. When creating your publisher, set the batch argument to True. This configuration tells the publisher that you intend to send messages in batches.

  2. In your producer function, return a tuple containing the messages you want to send as a batch. This action triggers the producer to gather the messages and transmit them as a batch to a Kafka broker.

Let's delve into a detailed example illustrating how to produce messages in batches to the \"output_data\" topic while consuming from the \"input_data_1\" topic.

","boost":10},{"location":"kafka/Publisher/batch_publisher/#code-example","title":"Code Example","text":"

First, let's take a look at the whole app creation and then dive deep into the steps for producing in batches. Here is the application code:

from typing import Tuple\n\nfrom pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\ndecrease_and_increase = broker.publisher(\"output_data\", batch=True)\n\n\n@decrease_and_increase\n@broker.subscriber(\"input_data_1\")\nasync def on_input_data_1(msg: Data, logger: Logger) -> Tuple[Data, Data]:\n    logger.info(msg)\n    return Data(data=(msg.data * 0.5)), Data(data=(msg.data * 2.0))\n\n\n@broker.subscriber(\"input_data_2\")\nasync def on_input_data_2(msg: Data, logger: Logger) -> None:\n    logger.info(msg)\n    await decrease_and_increase.publish(\n        Data(data=(msg.data * 0.5)), Data(data=(msg.data * 2.0))\n    )\n

Below, we have highlighted key lines of code that demonstrate the steps involved in creating and using a batch publisher:

Step 1: Creation of the Publisher

decrease_and_increase = broker.publisher(\"output_data\", batch=True)\n

Step 2: Publishing an Actual Batch of Messages

You can publish a batch by directly calling the publisher with a batch of messages you want to publish, as shown here:

await decrease_and_increase.publish(\n    Data(data=(msg.data * 0.5)), Data(data=(msg.data * 2.0))\n)\n

Or you can decorate your processing function and return a batch of messages, as shown here:

@decrease_and_increase\n@broker.subscriber(\"input_data_1\")\nasync def on_input_data_1(msg: Data, logger: Logger) -> Tuple[Data, Data]:\n    logger.info(msg)\n    return Data(data=(msg.data * 0.5)), Data(data=(msg.data * 2.0))\n

The application in the example imelements both of these ways, so feel free to use whichever option fits your needs better.

Note

Also, you can publishes messages in batches right from a broker object: just call broker.publish_batch(\"msg2\", \"msg2\", topic=\"output_data\")

","boost":10},{"location":"kafka/Publisher/batch_publisher/#why-publish-in-batches","title":"Why Publish in Batches?","text":"

In the above example, we've explored how to leverage the @broker.publisher(...) decorator to efficiently publish messages in batches using FastStream and Kafka. By following the two key steps outlined in the previous sections, you can significantly enhance the performance and reliability of your Kafka-based applications.

Publishing messages in batches offers several advantages when working with Kafka:

  1. Improved Throughput: Batch publishing allows you to send multiple messages in a single transmission, reducing the overhead associated with individual message delivery. This leads to improved throughput and lower latency in your Kafka applications.

  2. Reduced Network and Broker Load: Sending messages in batches reduces the number of network calls and broker interactions. This optimization minimizes the load on the Kafka brokers and network resources, making your Kafka cluster more efficient.

  3. Atomicity: Batches ensure that a group of related messages is processed together or not at all. This atomicity can be crucial in scenarios where message processing needs to maintain data consistency and integrity.

  4. Enhanced Scalability: With batch publishing, you can efficiently scale your Kafka applications to handle high message volumes. By sending messages in larger chunks, you can make the most of Kafka's parallelism and partitioning capabilities.

","boost":10},{"location":"kafka/Publisher/using_a_key/","title":"Using a Partition Key","text":"

Partition keys are a crucial concept in Apache Kafka, enabling you to determine the appropriate partition for a message. This ensures that related messages are kept together in the same partition, which can be invaluable for maintaining order or grouping related messages for efficient processing. Additionally, Kafka utilizes partitioning to distribute load across multiple brokers and scale horizontally, while replicating data across brokers provides fault tolerance.

You can specify your partition keys when utilizing the @KafkaBroker.publisher(...) decorator in FastStream. This guide will walk you through the process of using partition keys effectively.

","boost":10},{"location":"kafka/Publisher/using_a_key/#publishing-with-a-partition-key","title":"Publishing with a Partition Key","text":"

To publish a message to a Kafka topic using a partition key, follow these steps:

","boost":10},{"location":"kafka/Publisher/using_a_key/#step-1-define-the-publisher","title":"Step 1: Define the Publisher","text":"

In your FastStream application, define the publisher using the @KafkaBroker.publisher(...) decorator. This decorator allows you to configure various aspects of message publishing, including the partition key.

to_output_data = broker.publisher(\"output_data\")\n
","boost":10},{"location":"kafka/Publisher/using_a_key/#step-2-pass-the-key","title":"Step 2: Pass the Key","text":"

When you're ready to publish a message with a specific key, simply include the key parameter in the publish function call. This key parameter is used to determine the appropriate partition for the message.

await to_output_data.publish(Data(data=msg.data + 1.0), key=b\"key\")\n
","boost":10},{"location":"kafka/Publisher/using_a_key/#example-application","title":"Example Application","text":"

Let's examine a complete application example that consumes messages from the \"input_data\" topic and publishes them with a specified key to the \"output_data\" topic. This example will illustrate how to incorporate partition keys into your Kafka-based applications:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import Context, FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\nto_output_data = broker.publisher(\"output_data\")\n\n\n@broker.subscriber(\"input_data\")\nasync def on_input_data(\n    msg: Data, logger: Logger, key: bytes = Context(\"message.raw_message.key\")\n) -> None:\n    logger.info(f\"on_input_data({msg=})\")\n    await to_output_data.publish(Data(data=msg.data + 1.0), key=b\"key\")\n

As you can see, the primary difference from standard publishing is the inclusion of the key parameter in the publish call. This key parameter is essential for controlling how Kafka partitions and processes your messages.

In summary, using partition keys in Apache Kafka is a fundamental practice for optimizing message distribution, maintaining order, and achieving efficient processing. It is a key technique for ensuring that your Kafka-based applications scale gracefully and handle large volumes of data effectively.

","boost":10},{"location":"kafka/Subscriber/","title":"Basic Subscriber","text":"

To start consuming from a Kafka topic, simply decorate your consuming function with a @broker.subscriber(...) decorator, passing a string as a topic key.

In the folowing example, we will create a simple FastStream app that will consume HelloWorld messages from a \"hello_world\" topic.

The full app code looks like this:

from pydantic import BaseModel, Field\n\nfrom faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n\n\nclass HelloWorld(BaseModel):\n    msg: str = Field(\n        ...,\n        examples=[\"Hello\"],\n        description=\"Demo hello world message\",\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"hello_world\")\nasync def on_hello_world(msg: HelloWorld, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"kafka/Subscriber/#import-faststream-and-kafkabroker","title":"Import FastStream and KafkaBroker","text":"

To use the @broker.subscriber(...) decorator, first, we need to import the base FastStream app KafkaBroker to create our broker.

from faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n
","boost":10},{"location":"kafka/Subscriber/#define-the-helloworld-message-structure","title":"Define the HelloWorld Message Structure","text":"

Next, you need to define the structure of the messages you want to consume from the topic using Pydantic. For the guide, we\u2019ll stick to something basic, but you are free to define any complex message structure you wish in your project.

class HelloWorld(BaseModel):\n    msg: str = Field(\n        ...,\n        examples=[\"Hello\"],\n        description=\"Demo hello world message\",\n    )\n
","boost":10},{"location":"kafka/Subscriber/#create-a-kafkabroker","title":"Create a KafkaBroker","text":"

Next, we will create a KafkaBroker object and wrap it into the FastStream object so that we can start our app using CLI later.

broker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n
","boost":10},{"location":"kafka/Subscriber/#create-a-function-that-will-consume-messages-from-a-kafka-hello-world-topic","title":"Create a Function that will Consume Messages from a Kafka hello-world Topic","text":"

Let\u2019s create a consumer function that will consume HelloWorld messages from \"hello_world\" topic and log them.

@broker.subscriber(\"hello_world\")\nasync def on_hello_world(msg: HelloWorld, logger: Logger):\n    logger.info(msg)\n

The function decorated with the @broker.subscriber(...) decorator will be called when a message is produced to Kafka.

The message will then be injected into the typed msg argument of the function, and its type will be used to parse the message.

In this example case, when the message is sent to a \"hello_world\" topic, it will be parsed into a HelloWorld class, and the on_hello_world function will be called with the parsed class as the msg argument value.

","boost":10},{"location":"kafka/Subscriber/batch_subscriber/","title":"Batch Subscriber","text":"

If you want to consume data in batches, the @broker.subscriber(...) decorator makes it possible. By defining your consumed msg object as a list of messages and setting the batch parameter to True, the subscriber will call your consuming function with a batch of messages consumed from a single partition. Let's walk through how to achieve this.

","boost":10},{"location":"kafka/Subscriber/batch_subscriber/#using-the-subscriber-with-batching","title":"Using the Subscriber with Batching","text":"

To consume messages in batches, follow these steps:

","boost":10},{"location":"kafka/Subscriber/batch_subscriber/#step-1-define-your-subscriber","title":"Step 1: Define Your Subscriber","text":"

In your FastStream application, define the subscriber using the @broker.subscriber(...) decorator. Ensure that you configure the msg object as a list and set the batch parameter to True. This configuration tells the subscriber to handle message consumption in batches.

@broker.subscriber(\"test_batch\", batch=True)\n
","boost":10},{"location":"kafka/Subscriber/batch_subscriber/#step-2-implement-your-consuming-function","title":"Step 2: Implement Your Consuming Function","text":"

Create a consuming function that accepts the list of messages. The @broker.subscriber(...) decorator will take care of collecting and grouping messages into batches based on the partition.

@broker.subscriber(\"test_batch\", batch=True)\nasync def handle_batch(msg: List[HelloWorld], logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"kafka/Subscriber/batch_subscriber/#example-of-consuming-in-batches","title":"Example of Consuming in Batches","text":"

Let's illustrate how to consume messages in batches from the \"test_batch\" topic with a practical example:

from typing import List\n\nfrom pydantic import BaseModel, Field\n\nfrom faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\nclass HelloWorld(BaseModel):\n    msg: str = Field(\n        ...,\n        examples=[\"Hello\"],\n        description=\"Demo hello world message\",\n    )\n\n\n@broker.subscriber(\"test_batch\", batch=True)\nasync def handle_batch(msg: List[HelloWorld], logger: Logger):\n    logger.info(msg)\n

In this example, the subscriber is configured to process messages in batches, and the consuming function is designed to handle these batches efficiently.

Consuming messages in batches is a valuable technique when you need to optimize the processing of high volumes of data in your Kafka-based applications. It allows for more efficient resource utilization and can enhance the overall performance of your data pipelines.

","boost":10},{"location":"nats/","title":"NATS","text":"

FastStream NATS support is implemented on top of nats-py. You can always get access to objects of it if you need to use some low-level methods not represented in FastStream.

","boost":10},{"location":"nats/#advantages-and-disadvantages","title":"Advantages and Disadvantages","text":"

NATS is an easy-to-use, high-performance message broker written in Golang. If your application does not require complex routing logic, can cope with high loads, scales, and does not require large hardware costs, NATS will be an excellent choice for you.

Also NATS has a zero-cost new entities creation (to be honest, all subjects are just routing fields), so it can be used as a RPC over MQ tool.

Note

More information about NATS can be found on the official website.

However, NATS has disadvantages that you should be aware of:

","boost":10},{"location":"nats/#nats-jetstream","title":"NATS JetStream","text":"

These shortcomings are corrected by using the persistent level - JetStream. If you need strict guarantees for the delivery and processing of messages at the small detriment of speed and resources consumed, you can use NatsJS.

Also, NatsJS supports some high-level features like Key-Value and Object storages (with subscription to changes on it) and provides you with rich abilities to build your logic on top of it.

","boost":10},{"location":"nats/#routing-rules","title":"Routing Rules","text":"

NATS does not have the ability to configure complex routing rules. The only entity in NATS is subject, which can be subscribed to either directly by name or by a regular expression pattern.

Both examples are discussed a little further.

In order to support the ability to scale consumers horizontally, NATS supports the queue group functionality: a message sent to subject will be processed by a random consumer from the queue group subscribed to this subject. This approach allows you to increase the processing speed of subject by N times when starting N consumers with one group.

","boost":10},{"location":"nats/message/","title":"Access to Message Information","text":"

As you know, FastStream serializes a message body and provides you access to it through function arguments. But sometimes you need to access message_id, headers, or other meta-information.

","boost":10},{"location":"nats/message/#message-access","title":"Message Access","text":"

You can get it in a simple way: just acces the message object in the Context.

It contains the required information such as:

It is a FastStream wrapper around a native broker library message (nats.aio.msg.Msg in the NATS' case) that you can access with raw_message.

from faststream.nats import NatsMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    msg: NatsMessage,\n):\n    print(msg.correlation_id)\n

Also, if you can't find the information you require, you can get access directly to the wrapped nats.aio.msg.Msg, which contains complete message information.

from nats.aio.msg import Msg\nfrom faststream.nats import NatsMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(body: str, msg: NatsMessage):\n    raw: Msg = msg.raw_message\n    print(raw)\n
","boost":10},{"location":"nats/message/#message-fields-access","title":"Message Fields Access","text":"

But in most cases, you don't need all message fields; you need to access some of them. You can use Context Fields access feature for this reason.

For example, you can access the correlation_id like this:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: str = Context(\"message.correlation_id\"),\n):\n    print(cor_id)\n

Or even directly from the raw message:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: str = Context(\"message.raw_message.correlation_id\"),\n):\n    print(cor_id)\n

But this code is too long to reuse everywhere. In this case, you can use a Python Annotated feature:

python 3.9+python 3.6+
from types import Annotated\nfrom faststream import Context\n\nCorrelationId = Annotated[str, Context(\"message.correlation_id\")]\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: CorrelationId,\n):\n    print(cor_id)\n
from typing_extensions import Annotated\nfrom faststream import Context\n\nCorrelationId = Annotated[str, Context(\"message.correlation_id\")]\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: CorrelationId,\n):\n    print(cor_id)\n
","boost":10},{"location":"nats/message/#headers-access","title":"Headers Access","text":"

Sure, you can get access to a raw message and get the headers dict itself, but more often you just need a single header field. So, you can easily access it using the Context:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Context(\"message.headers.user\"),\n):\n    ...\n

Using the special Header class is more convenient, as it also validates the header value using Pydantic. It works the same way as Context, but it is just a shorcut to Context with a default setup. So, you already know how to use it:

from faststream import Header\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Header(),\n):\n    ...\n
","boost":10},{"location":"nats/message/#subject-pattern-access","title":"Subject Pattern Access","text":"

As you know, NATS allows you to use a pattern like this \"logs.*\" to subscriber to subjects. Getting access to the real * value is an often-used scenario, and FastStream provide it to you with the Path object (which is a shortcut to Context(\"message.path.*\")).

To use it, you just need to replace your * with {variable-name} and use Path as a regular Context object:

from faststream import Path\n\n@broker.subscriber(\"logs.{level}\")\nasync def base_handler(\n    body: str,\n    level: str = Path(),\n):\n    ...\n
","boost":10},{"location":"nats/rpc/","title":"RPC over NATS","text":"

Because NATS has zero cost for creating new subjects, we can easily set up a new subject consumer just for the one response message. This way, your request message will be published to one topic, and the response message will be consumed from another one (temporary subject), which allows you to use regular FastStream RPC syntax in the NATS case too.

Tip

FastStream RPC over NATS works in both the NATS-Core and NATS-JS cases as well, but in the NATS-JS case, you have to specify the expected stream as a publish argument.

","boost":10},{"location":"nats/rpc/#blocking-request","title":"Blocking Request","text":"

FastStream provides you with the ability to send a blocking RPC request over NATS in a very simple way.

Just send a message like a regular one and get a response synchronously.

It is very close to the common requests syntax:

msg = await broker.publish(\n    \"Hi!\",\n    subject=\"test\",\n    rpc=True,\n)\n

Also, you have two extra options to control this behavior:

","boost":10},{"location":"nats/rpc/#reply-to","title":"Reply-To","text":"

Also, if you want to create a permanent request-reply data flow, probably, you should create a permanent subject to consume responses.

So, if you have such one, you can specify it with the reply_to argument. This way, FastStream will send a response to this subject automatically.

@broker.subscriber(\"response-subject\")\nasync def consume_responses(msg):\n    ...\n\nmsg = await broker.publish(\n    \"Hi!\",\n    subject=\"test\",\n    reply_to=\"response-subject\",\n)\n
","boost":10},{"location":"nats/examples/direct/","title":"Direct","text":"

The Direct Subject is the basic way to route messages in NATS. Its essence is very simple: a subject sends messages to all consumers subscribed to it.

","boost":10},{"location":"nats/examples/direct/#scaling","title":"Scaling","text":"

If one subject is being listened to by several consumers with the same queue group, the message will go to a random consumer each time.

Thus, NATS can independently balance the load on queue consumers. You can increase the processing speed of the message flow from the queue by simply launching additional instances of the consumer service. You don't need to make changes to the current infrastructure configuration: NATS will take care of how to distribute messages between your services.

","boost":10},{"location":"nats/examples/direct/#example","title":"Example","text":"

The Direct Subject is the type used in FastStream by default: you can simply declare it as follows

@broker.handler(\"test_subject\")\nasync def handler():\n...\n

Full example:

from faststream import FastStream, Logger\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n@broker.subscriber(\"test-subj-1\", \"workers\")\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n@broker.subscriber(\"test-subj-1\", \"workers\")\nasync def base_handler2(logger: Logger):  \n    logger.info(\"base_handler2\")\n\n@broker.subscriber(\"test-subj-2\", \"workers\")\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(\"\", \"test-subj-1\")  # handlers: 1 or 2\n    await broker.publish(\"\", \"test-subj-1\")  # handlers: 1 or 2\n    await broker.publish(\"\", \"test-subj-2\")  # handlers: 3\n
","boost":10},{"location":"nats/examples/direct/#consumer-announcement","title":"Consumer Announcement","text":"

To begin with, we have declared several consumers for two subjects: \"test-subj-1\" and \"test-subj-2\":

@broker.subscriber(\"test-subj-1\", \"workers\")\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n@broker.subscriber(\"test-subj-1\", \"workers\")\nasync def base_handler2(logger: Logger):  \n    logger.info(\"base_handler2\")\n\n@broker.subscriber(\"test-subj-2\", \"workers\")\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n

Note

Note that all consumers are subscribed using the same queue_group. Within the same service, this does not make sense, since messages will come to these handlers in turn. Here, we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"nats/examples/direct/#message-distribution","title":"Message Distribution","text":"

Now the distribution of messages between these consumers will look like this:

await broker.publish(\"\", \"test-subj-1\")  # handlers: 1 or 2\n

The message 1 will be sent to handler1 or handler2 because they are listening to one \"test-subj-1\" subject within one queue group.

await broker.publish(\"\", \"test-subj-1\")  # handlers: 1 or 2\n

Message 2 will be sent similarly to message 1.

await broker.publish(\"\", \"test-subj-2\")  # handlers: 3\n

The message 3 will be sent to handler3 because it is the only one listening to \"test-subj-2\".

","boost":10},{"location":"nats/examples/pattern/","title":"Pattern","text":"

Pattern Subject is a powerful NATS routing engine. This type of subject routes messages to consumers based on the pattern specified when they connect to the subject and a message key.

","boost":10},{"location":"nats/examples/pattern/#scaling","title":"Scaling","text":"

If one subject is being listened to by several consumers with the same queue group, the message will go to a random consumer each time.

Thus, NATS can independently balance the load on queue consumers. You can increase the processing speed of the message flow from the queue by simply launching additional instances of the consumer service. You don't need to make changes to the current infrastructure configuration: NATS will take care of how to distribute messages between your services.

","boost":10},{"location":"nats/examples/pattern/#example","title":"Example","text":"
from faststream import FastStream, Logger\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n@broker.subscriber(\"*.info\", \"workers\")\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n@broker.subscriber(\"*.info\", \"workers\")\nasync def base_handler2(logger: Logger):  \n    logger.info(\"base_handler2\")\n\n@broker.subscriber(\"*.error\", \"workers\")\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(\"\", \"logs.info\")  # handlers: 1 or 2\n    await broker.publish(\"\", \"logs.info\")  # handlers: 1 or 2\n    await broker.publish(\"\", \"logs.error\") # handlers: 3\n
","boost":10},{"location":"nats/examples/pattern/#consumer-announcement","title":"Consumer Announcement","text":"

To begin with, we have announced several consumers for two subjects: \"*.info\" and \"*.error\":

@broker.subscriber(\"*.info\", \"workers\")\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n@broker.subscriber(\"*.info\", \"workers\")\nasync def base_handler2(logger: Logger):  \n    logger.info(\"base_handler2\")\n\n@broker.subscriber(\"*.error\", \"workers\")\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n

At the same time, in the subject of our consumers, we specify the pattern that will be processed by these consumers.

Note

Note that all consumers are subscribed using the same queue_group. Within the same service, this does not make sense, since messages will come to these handlers in turn. Here, we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"nats/examples/pattern/#message-distribution","title":"Message Distribution","text":"

Now the distribution of messages between these consumers will look like this:

await broker.publish(\"\", \"logs.info\")  # handlers: 1 or 2\n

The message 1 will be sent to handler1 or handler2 because they listen to the same subject template within the same queue group.

await broker.publish(\"\", \"logs.info\")  # handlers: 1 or 2\n

Message 2 will be sent similarly to message 1.

await broker.publish(\"\", \"logs.error\") # handlers: 3\n

The message 3 will be sent to handler3 because it is the only one listening to the pattern \"*.error\".

","boost":10},{"location":"nats/jetstream/","title":"NATS JetStream","text":"

The default NATS usage is suitable for scenarios where:

If you need stricter restrictions, like:

You should use the NATS JetStream extension.

In fact, the JetStream extension is the same as NATS, with the addition of a persistent layer above the file system. Therefore, all interfaces for publishing and consuming messages are similar to regular NATS usage.

However, the JetStream layer has many possibilities for configuration, from the policy of deleting old messages to the maximum stored messages number limit. You can find out more about all JetStream features in the official documentation.

If you have worked with other message brokers, then you should know that the logic of JS is closer to Kafka than to RabbitMQ: messages, after confirmation, are not deleted from the queue but remain there until the queue is full, and it will start deleting old messages (or in accordance with other logic that you can configure yourself).

When connecting a consumer (and, especially, when reconnecting), you must determine for yourself according to what logic it will consume messages: from the subject beginning, starting with some message, starting from some time, only new ones, etc. Don't be surprised if a connection is restored, and your consumer starts to process all messages received earlier again - you haven't defined the rule.

Also, NATS JetStream has built-in key-value (similar to Redis) and object (similar to Minio) storages, which, in addition to the interface for put/get, have the ability to subscribe to events, which can be extremely useful in various scenarios.

FastStream does not provide access to this functionality directly, but it is covered by the nats-py library used. You can access the JS object from the application context:

from faststream import FastStream, Logger\nfrom faststream.nats import JStream, NatsBroker\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\nstream = JStream(name=\"stream\")\n\n@broker.subscriber(\n    \"js-subject\",\n    stream=stream,\n    deliver_policy=\"new\",\n)\nasync def handler(msg: str, logger: Logger):\n    logger.info(msg)\n\n@app.after_startup\nasync def test_send():\n    await broker.publish(\"Hi!\", \"js-subject\")\n    # publish with stream verification\n    await broker.publish(\"Hi!\", \"js-subject\", stream=\"stream\")\n

Tip

Using JStream object FastStream is trying to create/update stream with the object settings. To prevent this behavior and just get already created stream, please use JStream(..., declare=False) option.

","boost":10},{"location":"nats/jetstream/ack/","title":"Consuming Acknowledgements","text":"

As you may know, Nats employs a rather extensive Acknowledgement policy.

In most cases, FastStream automatically acknowledges (acks) messages on your behalf. When your function executes correctly, including sending all responses, a message will be acknowledged (and rejected in case of an exception).

However, there are situations where you might want to use different acknowledgement logic.

","boost":10},{"location":"nats/jetstream/ack/#retries","title":"Retries","text":"

If you prefer to use a nack instead of a reject when there's an error in message processing, you can specify the retry flag in the @broker.subscriber(...) method, which is responsible for error handling logic.

By default, this flag is set to False, indicating that if an error occurs during message processing, the message can still be retrieved from the queue:

@broker.subscriber(\"test\", retry=False) # don't handle exceptions\nasync def base_handler(body: str):\n    ...\n

If this flag is set to True, the message will be nacked and placed back in the queue each time an error occurs. In this scenario, the message can be processed by another consumer (if there are several of them) or by the same one:

@broker.subscriber(\"test\", retry=True)  # try again indefinitely\nasync def base_handler(body: str):\n    ...\n

Tip

For more complex error handling cases, you can use tenacity

","boost":10},{"location":"nats/jetstream/ack/#manual-acknowledgement","title":"Manual Acknowledgement","text":"

If you want to acknowledge a message manually, you can get access directy to the message object via the Context and call the method.

from faststream.nats.annotations import NatsMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(body: str, msg: NatsMessage):\n    await msg.ack()\n    # or\n    await msg.nack()\n    # or\n    await msg.reject()\n

FastStream will see that the message was already acknowledged and will do nothing at the end of the process.

","boost":10},{"location":"nats/jetstream/ack/#interrupt-process","title":"Interrupt Process","text":"

If you want to interrupt message processing at any call stack, you can raise faststream.exceptions.AckMessage

from faststream import FastStream\nfrom faststream.exceptions import AckMessage\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\", stream=\"test-stream\")\nasync def handle(body):\n    smth_processing(body)\n\n\ndef smth_processing(body):\n    if True:\n        raise AckMessage()\n\n\n@app.after_startup\nasync def test_publishing():\n    await broker.publish(\"Hello!\", \"test-subject\")\n

This way, FastStream interrupts the current message proccessing and acknowledges it immediately. Also, you can raise NackMessage and RejectMessage too.

Tip

If you want to disable FastStream Acknowledgement logic at all, you can use @broker.subscriber(..., no_ack=True) option. This way you should always process a message (ack/nack/terminate/etc) by yourself.

","boost":10},{"location":"nats/jetstream/key-value/","title":"Key-Value Storage","text":"","boost":10},{"location":"nats/jetstream/key-value/#overview","title":"Overview","text":"

Key-Value storage is just a high-level interface on top of NatsJS.

It is a regular JetStream, where the KV key is a subject.

Put/Update an object to KV by key - it's like publishing a new message to the corresponding subject in the stream.

Thus, the Get command returns not only the current key value but the latest one with an offset of it. Additionally, you can ask for a specific value based on its offset in the KV stream.

This interface provides you with rich abilities to use it like a regular KV storage (ignoring offset) + subscribe to KV key changes + ask for an old KV value revision. So you can use this feature in your application in a really different way. You can find some examples on the NATS developers' official YouTube channel

","boost":10},{"location":"nats/jetstream/key-value/#faststream-details","title":"FastStream Details","text":"

FastStream has no native interfaces to this NatsJS functionality (yet), but it allows you to get access into the inner JetStream object to create it manually.

First of all, you need to create a Key-Value storage object and pass it into the context:

from faststream import Context, FastStream, Logger\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import ContextRepo\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n@app.on_startup\nasync def setup_broker(context: ContextRepo):\n    await broker.connect()\n\n    kv = await broker.stream.create_key_value(bucket=\"bucket\")\n    context.set_global(\"kv\", kv)\n

Tip

We placed this code in @app.on_startup hook because @app.after_startup will be triggered AFTER your handlers start consuming messages. So, if you need to have access to any custom context objects, you should set them up in the @app.on_startup hook.

Also, we call await broker.connect() method manually to establish the connection to be able to create a storage.

Next, we are ready to use this object right in our handlers.

Let's create an annotated object to shorten context object access:

from nats.js.kv import KeyValue as KV\nfrom typing_extensions import Annotated\n\nKeyValue = Annotated[KV, Context(\"kv\")]\n

And just use it in a handler:

from faststream import Logger\n\n@broker.subscriber(\"subject\")\nasync def handler(msg: str, kv: KeyValue, logger: Logger):\n    logger.info(msg)\n    kv_data = await kv.get(\"key\")\n    assert kv_data.value == b\"Hello!\"\n

Finally, let's test our code behavior by putting something into the KV storage and sending a message:

@app.after_startup\nasync def test_send(kv: KeyValue):\n    await kv.put(\"key\", b\"Hello!\")\n    await broker.publish(\"Hi!\", \"subject\")\n
Full listing
from nats.js.kv import KeyValue as KV\nfrom typing_extensions import Annotated\n\nfrom faststream import Logger\nfrom faststream import Context, FastStream, Logger\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import ContextRepo\n\nKeyValue = Annotated[KV, Context(\"kv\")]\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\"subject\")\nasync def handler(msg: str, kv: KeyValue, logger: Logger):\n    logger.info(msg)\n    kv_data = await kv.get(\"key\")\n    assert kv_data.value == b\"Hello!\"\n\n\n@app.on_startup\nasync def setup_broker(context: ContextRepo):\n    await broker.connect()\n\n    kv = await broker.stream.create_key_value(bucket=\"bucket\")\n    context.set_global(\"kv\", kv)\n\n\n@app.after_startup\nasync def test_send(kv: KeyValue):\n    await kv.put(\"key\", b\"Hello!\")\n    await broker.publish(\"Hi!\", \"subject\")\n
","boost":10},{"location":"nats/jetstream/object/","title":"Object Storage","text":"

Object storage is almost identical to the Key-Value stroge concept, so you can reuse the guide.

","boost":10},{"location":"nats/jetstream/object/#overview","title":"Overview","text":"

Object Storage is just a high-level interface on top of NatsJS.

It is a regular JetStream, where the Object key is a subject.

The main difference between KV and Object storages is that in the Object storage, you can store files greater than 1MB (a limitation of KV). It has no limit on the maximum object size and stores it in chunks (each message is an object chunk), so you can literally stream huge objects through NATS.

","boost":10},{"location":"nats/jetstream/object/#faststream-details","title":"FastStream Details","text":"

FastStream has no native interfaces to this NatsJS functionality (yet), but it allows you to access the inner JetStream object to create in manually.

First of all, you need to create an Object storage object and pass in to the context:

from faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import ContextRepo\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n@app.on_startup\nasync def setup_broker(context: ContextRepo):\n    await broker.connect()\n\n    os = await broker.stream.create_object_store(\"bucket\")\n    context.set_global(\"OS\", os)\n

Tip

We placed this code in the @app.on_startup hook because @app.after_startup will be triggered AFTER your handlers start consuming messages. So, if you need to have access to any custom context objects, you should set them up in the @app.on_startup hook.

Also, we call await broker.connect() method manually to establish the connection to be able to create a storage.

Next, we are ready to use this object right in the our handlers.

Let's create an Annotated object to shorten Context object access:

from nats.js.object_store import ObjectStore as OS\nfrom typing_extensions import Annotated\n\nObjectStorage = Annotated[OS, Context(\"OS\")]\n

And just use it in a handler:

from io import BytesIO\n\nfrom faststream import Logger\n\n@broker.subscriber(\"subject\")\nasync def handler(msg: str, os: ObjectStorage, logger: Logger):\n    logger.info(msg)\n    obj = await os.get(\"file\")\n    assert obj.data == b\"File mock\"\n

Finally, let's test our code behavior by putting something into the Object storage and sending a message:

@app.after_startup\nasync def test_send(os: ObjectStorage):\n    await os.put(\"file\", BytesIO(b\"File mock\"))\n    await broker.publish(\"Hi!\", \"subject\")\n

Tip

BytesIO - is a Readable object used to emulate a file opened for reading.

Full listing
from io import BytesIO\n\nfrom nats.js.object_store import ObjectStore as OS\nfrom typing_extensions import Annotated\n\nfrom faststream import Logger\nfrom faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import ContextRepo\n\nObjectStorage = Annotated[OS, Context(\"OS\")]\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\"subject\")\nasync def handler(msg: str, os: ObjectStorage, logger: Logger):\n    logger.info(msg)\n    obj = await os.get(\"file\")\n    assert obj.data == b\"File mock\"\n\n\n@app.on_startup\nasync def setup_broker(context: ContextRepo):\n    await broker.connect()\n\n    os = await broker.stream.create_object_store(\"bucket\")\n    context.set_global(\"OS\", os)\n\n\n@app.after_startup\nasync def test_send(os: ObjectStorage):\n    await os.put(\"file\", BytesIO(b\"File mock\"))\n    await broker.publish(\"Hi!\", \"subject\")\n
","boost":10},{"location":"nats/jetstream/pull/","title":"Pull Subscriber","text":"","boost":10},{"location":"nats/jetstream/pull/#overview","title":"Overview","text":"

NATS JetStream supports two various way to consume messages: Push and Pull consumers.

The Push consumer is used by default to consume messages with the FastStream. It means that the NATS server delivers messages to your consumer as far as possible by itself. However, it also means that NATS should control all current consumer connections and increase server load.

Thus, the Pull consumer is the recommended way to consume JetStream messages by the NATS TEAM. Using it, you simply ask NATS for new messages at some interval. It may sound a little less convenient than automatic message delivery, but it provides several advantages, such as:

So, if you want to consume a large flow of messages without strict time limitations, the Pull consumer is the right choice for you.

","boost":10},{"location":"nats/jetstream/pull/#faststream-details","title":"FastStream Details","text":"

The Pull consumer is just a regular Stream consumer, but with the pull_sub argument, which controls consuming messages with batch size and block interval.

from faststream import FastStream, Logger\nfrom faststream.nats import NatsBroker, PullSub\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    subject=\"test\",\n    stream=\"stream\",\n    pull_sub=PullSub(batch_size=10),\n)\nasync def handle(msg, logger: Logger):\n    logger.info(msg)\n

The batch size doesn't mean that your msg argument is a list of messages, but it means that you consume up to 10 messages for one request to NATS and call your handler for each message in an asyncio.gather pool.

Tip

If you want to consume list of messages, just set the batch=True in PullSub class.

So, your subject will be processed much faster, without blocking for each message processing. However, if your subject has fewer than 10 messages, your request to NATS will be blocked for timeout (5 seconds by default) while trying to collect the required number of messages. Therefor, you should choose batch_size and timeout accurately to optimize your consumer efficiency.

","boost":10},{"location":"nats/publishing/","title":"Publishing","text":"

FastStream NatsBroker supports all regular publishing usecases. You can use them without any changes.

However, if you wish to further customize the publishing logic, you should take a deeper look at specific NatsBroker parameters.

","boost":10},{"location":"nats/publishing/#nats-publishing","title":"NATS Publishing","text":"

NatsBroker also uses the unified publish method (from a publisher object) to send messages.

import asyncio\nfrom faststream.nats import NatsBroker\n\nasync def pub():\n    async with NatsBroker() as broker:\n        await broker.publish(\n            \"Hi!\",\n            subject=\"test\",\n        )\n\nasyncio.run(pub())\n
","boost":10},{"location":"nats/publishing/#basic-arguments","title":"Basic Arguments","text":"

The publish method accepts the following arguments:

","boost":10},{"location":"nats/publishing/#message-parameters","title":"Message Parameters","text":"","boost":10},{"location":"nats/publishing/#natsjs-parameters","title":"NatsJS Parameters","text":"","boost":10},{"location":"rabbit/","title":"Rabbit Routing","text":"

FastStream RabbitMQ support is implemented on top of aio-pika. You can always get access to objects of it, if you need to use some low-level methods, not represented in FastStream.

","boost":10},{"location":"rabbit/#advantages","title":"Advantages","text":"

The advantage of RabbitMQ is the ability to configure flexible and complex message routing scenarios.

RabbitMQ covers the whole range of routing: from one queue - one consumer, to a queue retrieved from several sources, including message prioritization.

Note

For more information about RabbitMQ, please visit the official documentation

It supports the ability to successfully process messages, mark them as processed with an error, remove them from the queue (it is also impossible to re-receive processed messages, unlike Kafka), lock it for the processing duration, and monitor its current status.

Having to keep track of the current status of all messages is a cause of the RabbitMQ performance issues. With really large message volumes, RabbitMQ starts to degrade. However, if this was a \"one-time influx\", then consumers will free the queue of messages and the \"health\" of RabbitMQ will be stable.

If your scenario is not based on processing millions of messages and also requires building complex routing logic, RabbitMQ will be the right choice.

","boost":10},{"location":"rabbit/#basic-concepts","title":"Basic Concepts","text":"

If you want to totally understand how RabbitMQ works, you should visit their official website. There you will find top-level comments about the basic concepts and usage examples.

","boost":10},{"location":"rabbit/#entities","title":"Entities","text":"

RabbitMQ works with three main entities:

","boost":10},{"location":"rabbit/#routing-rules","title":"Routing Rules","text":"

The rules for delivering messages to consumers depend on the type of exchange and binding parameters. All the main options will be discussed at examples.

In general, the message path looks so:

  1. Publisher sends a message to exchange, specify its routing_key and headers according to which routing will take place.
  2. Exchange, depending on the message parameters, determines which of the subscribed bindings to send the message to.
  3. Binding delivers the message to queue or another exchange (in this case it will send it further by its own rules).
  4. Queue, after receiving a message, sends it to one of subscribed consumers (PUSH API).

Tip

By default, all queues have a binding to the default exchange (Direct type) with a routing key corresponding to their name. In FastStream, queues are connected to this exchange, and messages are sent by default unless another exchange is explicitly specified.

Connecting the queue to any other exchange will still leave it subscribed to the `default exchange'. Be careful with this.

At this stage, the message gets into your application - and you start processing it.

","boost":10},{"location":"rabbit/#message-statuses","title":"Message Statuses","text":"

RabbitMQ requires confirmation of message processing: only after that, it will be removed from the queue.

Confirmation can be either positive (Acknowledgment - ack) if the message was successfully processed or negative (Negative Acknowledgment - nack) if the message was processed with an error.

At the same time, in case of an error, the message can also be extracted from the queue (reject); otherwise, after a negative confirmation, it will be requeued for processing again.

In most cases, FastStream performs all the necessary actions by itself. However, if you want to manage the message lifecycle directly, you can access the message object itself and call the appropriate methods directly. This can be useful if you want to implement an \"at most once\" policy and you need to confirm the consuming of the message before it is actually processed.

","boost":10},{"location":"rabbit/#faststream-specific","title":"FastStream Specific","text":"

FastStream omits the ability to create bindings directly, since in most cases, you do not need to subscribe one queue to several exchanges or subscribe exchanges to each other. On the contrary, this practice leads to over-complication of the message routing scheme, which makes it difficult to maintain and further develop the entire infrastructure of services.

FastStream suggests you adhere to the scheme exchange:queue as 1:N, which will greatly simplify the scheme of interaction between your services. It is better to create an additional queue for a new exchange than to subscribe to an existing one.

However, if you want to reduce the number of entities in your RabbitMQ, and thereby optimize its performance (or you know exactly what you are doing), FastStream leaves you the option to create bindings directly. In other cases, the connection parameters are an integral part of the entities RabbitQueue and RabbitExchange in FastStream.

","boost":10},{"location":"rabbit/ack/","title":"Consuming Acknowledgements","text":"

As you may know, RabbitMQ employs a rather extensive Acknowledgement policy.

In most cases, FastStream automatically acknowledges (acks) messages on your behalf. When your function executes correctly, including sending all responses, a message will be acknowledged (and rejected in case of an exception).

However, there are situations where you might want to use a different acknowledgement logic.

","boost":10},{"location":"rabbit/ack/#retries","title":"Retries","text":"

If you prefer to use a nack instead of a reject when there's an error in message processing, you can specify the retry flag in the @broker.subscriber(...) method, which is responsible for error handling logic.

By default, this flag is set to False, indicating that if an error occurs during message processing, the message can still be retrieved from the queue:

@broker.subscriber(\"test\", retry=False) # don't handle exceptions\nasync def base_handler(body: str):\n    ...\n

If this flag is set to True, the message will be nacked and placed back in the queue each time an error occurs. In this scenario, the message can be processed by another consumer (if there are several of them) or by the same one:

@broker.subscriber(\"test\", retry=True)  # try again indefinitely\nasync def base_handler(body: str):\n    ...\n

If the retry flag is set to an int, the message will be placed back in the queue, and the number of retries will be limited to this number:

@broker.subscriber(\"test\", retry=3)     # make up to 3 attempts\nasync def base_handler(body: str):\n    ...\n

Bug

At the moment, attempts are counted only by the current consumer. If the message goes to another consumer, it will have its own counter. Subsequently, this logic will be reworked.

Tip

For more complex error handling cases, you can use tenacity

","boost":10},{"location":"rabbit/ack/#manual-acknowledgement","title":"Manual acknowledgement","text":"

If you want to acknowledge a message manually, you can get access directy to the message object via the Context and call the method.

from faststream.rabbit.annotations import RabbitMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(body: str, msg: RabbitMessage):\n    await msg.ack()\n    # or\n    await msg.nack()\n    # or\n    await msg.reject()\n

FastStream will see that the message was already acknowledged and will do nothing at process end.

","boost":10},{"location":"rabbit/ack/#interrupt-process","title":"Interrupt Process","text":"

If you want to interrupt message processing at any call stack, you can raise faststream.exceptions.AckMessage

from faststream import FastStream\nfrom faststream.exceptions import AckMessage\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(body):\n    smth_processing(body)\n\n\ndef smth_processing(body):\n    if True:\n        raise AckMessage()\n\n\n@app.after_startup\nasync def test_publishing():\n    await broker.publish(\"Hello!\", \"test-queue\")\n

This way, FastStream interrupts the current message proccessing and acknowledges it immediately. Also, you can raise NackMessage and RejectMessage too.

Tip

If you want to disable FastStream Acknowledgement logic at all, you can use @broker.subscriber(..., no_ack=True) option. This way you should always process a message (ack/nack/terminate/etc) by yourself.

","boost":10},{"location":"rabbit/declare/","title":"RabbitMQ Queue/Exchange Declaration","text":"

FastStream declares and validates all exchanges and queues using publishers and subscribers RabbitMQ objects, but sometimes you need to declare them manually.

RabbitBroker provides a way to achieve this easily.

from faststream import FastStream\nfrom faststream.rabbit import (\n    ExchangeType,\n    RabbitBroker,\n    RabbitExchange,\n    RabbitQueue,\n)\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\n\n@app.after_startup\nasync def declare_smth():\n    await broker.declare_exchange(\n        RabbitExchange(\n            name=\"some-exchange\",\n            type=ExchangeType.FANOUT,\n        )\n    )\n\n    await broker.declare_queue(\n        RabbitQueue(\n            name=\"some-queue\",\n            durable=True,\n        )\n    )\n

These methods require just one argument (RabbitQueue/RabbitExchange) containing information about your RabbitMQ required objects. They declare/validate RabbitMQ objects and return low-level aio-pika robust objects to interact with.

Tip

Also, these methods are idempotent, so you can call them with the same arguments multiple times, but the objects will be created once; next time the method will return an already stored object. This way you can get access to any queue/exchange created automatically.

","boost":10},{"location":"rabbit/message/","title":"Access to Message Information","text":"

As you know, FastStream serializes a message body and provides you access to it through function arguments. But sometimes you need access to a message_id, headers, or other meta-information.

","boost":10},{"location":"rabbit/message/#message-access","title":"Message Access","text":"

You can get it in a simple way: just acces the message object in the Context.

This message contains the required information such as:

Also, it is a FastStream wrapper around a native broker library message (aio_pika.IncomingMessage in the RabbitMQ case) that you can access with raw_message.

from faststream.rabbit import RabbitMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    msg: RabbitMessage,\n):\n    print(msg.correlation_id)\n

Also, if you can't find the information you require, you can get access directly to the wrapped aio_pika.IncomingMessage, which contains complete message information.

from aio_pika import IncomingMessage\nfrom faststream.rabbit import RabbitMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(body: str, msg: RabbitMessage):\n    raw: IncomingMessage = msg.raw_message\n    print(raw)\n
","boost":10},{"location":"rabbit/message/#message-fields-access","title":"Message Fields Access","text":"

But in most cases, you don't need all message fields; you need to access some of them. You can use Context Fields access feature for this reason.

For example, you can access the correlation_id like this:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: str = Context(\"message.correlation_id\"),\n):\n    print(cor_id)\n

Or even directly from the raw message:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: str = Context(\"message.raw_message.correlation_id\"),\n):\n    print(cor_id)\n

But this code is too long to be reused everywhere. In this case, you can use a Python Annotated feature:

python 3.9+python 3.6+
from types import Annotated\nfrom faststream import Context\n\nCorrelationId = Annotated[str, Context(\"message.correlation_id\")]\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: CorrelationId,\n):\n    print(cor_id)\n
from typing_extensions import Annotated\nfrom faststream import Context\n\nCorrelationId = Annotated[str, Context(\"message.correlation_id\")]\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: CorrelationId,\n):\n    print(cor_id)\n
","boost":10},{"location":"rabbit/message/#headers-access","title":"Headers Access","text":"

Sure, you can get access to a raw message and get the headers dict itself, but more often you just need a single header field. So, you can easily access it using the Context:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Context(\"message.headers.user\"),\n):\n    ...\n

Using the special Header class is more convenient, as it also validates the header value using Pydantic. It works the same way as Context, but it is just a shorcut to Context with a default setup. So, you already know how to use it:

from faststream import Header\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Header(),\n):\n    ...\n
","boost":10},{"location":"rabbit/message/#topic-pattern-access","title":"Topic Pattern Access","text":"

As you know, Rabbit allows you to use a pattern like this \"logs.*\" with a Topic exchange. Getting access to the real * value is an often-used scenario and FastStream provide it to you with the Path object (which is a shortcut to Context(\"message.path.*\")).

To use it, you just need to replace your * with {variable-name} and use Path as a regular Context object:

from faststream import Path\nfrom faststream import RabbitQueue, RabbitExchane, ExchangeType\n\n@broker.subscriber(\n    RabbitQueue(\n        \"test-queue\",\n        routing_key=\"logs.{level}\",\n    ),\n    RabbitExchange(\n        \"test-exchange\",\n        type=ExchangeType.TOPIC,\n    )\n)\nasync def base_handler(\n    body: str,\n    level: str = Path(),\n):\n    ...\n
","boost":10},{"location":"rabbit/publishing/","title":"Publishing","text":"

FastStream RabbitBroker supports all regular publishing usecases. you can use them without any changes.

However, if you wish to further customize the publishing logic further, you should take a more deep-dive look at specific RabbitBroker parameters.

","boost":10},{"location":"rabbit/publishing/#rabbit-publishing","title":"Rabbit Publishing","text":"

RabbitBroker also uses the unified publish method (from a publisher object) to send messages.

However, in this case, an object of the aio_pika.Message class (if necessary) can be used as a message (in addition to python primitives and pydantic.BaseModel).

You can specify queue (used as a routing_key) and exchange (optionally) to send by their name.

import asyncio\nfrom faststream.rabbit import RabbitBroker\n\nasync def pub():\n    async with RabbitBroker() as broker:\n        await broker.publish(\n            \"Hi!\",\n            queue=\"test\",\n            exchange=\"test\"\n        )\n\nasyncio.run(pub())\n

If you don't specify any exchange, the message will be send to the default one.

Also, you are able to use special RabbitQueue and RabbitExchange objects as queue and exchange arguments:

from faststream.rabbit import RabbitExchange, RabbitQueue\n\nawait broker.publish(\n    \"Hi!\",\n    queue=RabbitQueue(\"test\"),\n    exchange=RabbitExchange(\"test\")\n)\n

If you specify exchange that doesn't exist, RabbitBroker will create a required one and then publish a message to it.

Tip

Be accurate with it: if you have already created an Exchange with specific parameters and try to send a message by exchange name to it, the broker will try to create it. So, Exchange parameters conflict will occur.

If you are trying to send a message to a specific Exchange, sending it with a defined RabbitExchange object is the preffered way.

","boost":10},{"location":"rabbit/publishing/#basic-arguments","title":"Basic Arguments","text":"

The publish method takes the following arguments:

","boost":10},{"location":"rabbit/publishing/#message-parameters","title":"Message Parameters","text":"

You can read more about all the available flags in the RabbitMQ documentation

","boost":10},{"location":"rabbit/publishing/#send-flags","title":"Send Flags","text":"

Arguments for sending a message:

","boost":10},{"location":"rabbit/rpc/","title":"RPC over RMQ","text":"","boost":10},{"location":"rabbit/rpc/#blocking-request","title":"Blocking Request","text":"

FastStream provides you with the ability to send a blocking RPC request over RabbitMQ in a very simple way.

It uses the Direct Reply-To RabbitMQ feature, so you don't need to create any queues to consume a response.

Just send a message like a regular one and get a response synchronously.

It is very close to common requests syntax:

msg = await broker.publish(\n    \"Hi!\",\n    queue=\"test\",\n    rpc=True,\n)\n

Also, you have two extra options to control this behavior:

","boost":10},{"location":"rabbit/rpc/#reply-to","title":"Reply-To","text":"

Also, if you want to create a permanent request-reply data flow, probably, you should create a permanent queue to consume responses.

So, if you have such one, you can specify it with the reply_to argument. This way, FastStream will send a response to this queue automatically.

@broker.subscriber(\"response-queue\")\nasync def consume_responses(msg):\n    ...\n\nmsg = await broker.publish(\n    \"Hi!\",\n    queue=\"test\",\n    reply_to=\"response-queue\",\n)\n
","boost":10},{"location":"rabbit/security/","title":"FastStream RabbitMQ Security","text":"

This chapter discusses the security options available in FastStream and how to use them.

","boost":10},{"location":"rabbit/security/#security-objects","title":"Security Objects","text":"

FastStream allows you to enhance the security of applications by using security objects when creating brokers. These security objects encapsulate security-related configurations and mechanisms. Security objects supported in FastStream for RabbitMQ are:

","boost":10},{"location":"rabbit/security/#1-basesecurity-object","title":"1. BaseSecurity Object","text":"

Purpose: The BaseSecurity object wraps ssl.SSLContext object and is used to enable SSL/TLS encryption for secure communication between FastStream services and external components such as message brokers.

Usage:

import ssl\n\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.security import BaseSecurity\n\nssl_context = ssl.create_default_context()\nsecurity = BaseSecurity(ssl_context=ssl_context)\n\nbroker = RabbitBroker(security=security)\n
","boost":10},{"location":"rabbit/security/#2-saslplaintext-object-with-ssltls","title":"2. SASLPlaintext Object with SSL/TLS","text":"

Purpose: The SASLPlaintext object is used for authentication in SASL (Simple Authentication and Security Layer) plaintext mode. It allows you to provide a username and password for authentication.

Usage:

import ssl\n\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.security import SASLPlaintext\n\nssl_context = ssl.create_default_context()\nsecurity = SASLPlaintext(\n    ssl_context=ssl_context,\n    username=\"admin\",\n    password=\"password\", \n)\n\nbroker = RabbitBroker(security=security)\n
","boost":10},{"location":"rabbit/examples/","title":"Basic Subscriber","text":"

If you know nothing about RabbitMQ and how it works, you will still able to use FastStream RabbitBroker.

Just use the @broker.subscriber(...) method with a string as a routing key.

from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\"routing_key\")  # handle messages by routing key\nasync def handle(msg):\n    print(msg)\n\n\n@app.after_startup\nasync def test_publish():\n    await broker.publish(\n        \"message\",\n        \"routing_key\",  # publish message with routing key\n    )\n

This is the principle all FastStream brokers work by: you don't need to learn them in-depth if you want to just send a message.

","boost":10},{"location":"rabbit/examples/#rabbitmq-details","title":"RabbitMQ Details","text":"

If you are already familiar with RabbitMQ logic, you should also be acquainted with the inner workings of the example mentioned above.

In this case, FastStream either creates or validates a queue with a specified routing_key and binds it to the default RabbitMQ exchange.

If you want to specify a queue-exchange pair with additional arguments, FastStream provides you with the ability to do so. You can use special RabbitQueue and RabbitExchange objects to configure RabbitMQ queues, exchanges, and binding properties. For examples of using various types of exchanges, please refer to the following articles.

","boost":10},{"location":"rabbit/examples/direct/","title":"Direct Exchange","text":"

The Direct Exchange is the basic way to route messages in RabbitMQ. Its core is very simple: the exchange sends messages to those queues whose routing_key matches the routing_key of the message being sent.

Note

The Default Exchange, to which all queues in RabbitMQ are subscribed, has the Direct type by default.

","boost":10},{"location":"rabbit/examples/direct/#scaling","title":"Scaling","text":"

If several consumers are listening to the same queue, messages will be distributed to one of them (round-robin). This behavior is common for all types of exchange because it refers to the queue itself. The type of exchange affects which queues the message gets into.

Thus, RabbitMQ can independently balance the load on queue consumers. You can increase the processing speed of the message flow from the queue by launching additional instances of a consumer service. You don't need to make changes to the current infrastructure configuration: RabbitMQ will take care of how to distribute messages between your services.

","boost":10},{"location":"rabbit/examples/direct/#example","title":"Example","text":"

Tip

The Direct Exchange is the type used in FastStream by default. You can simply declare it as follows:

@broker.subscriber(\"test_queue\", \"test_exchange\")\nasync def handler():\n    ...\n

The argument auto_delete=True in this and subsequent examples is used only to clear the state of RabbitMQ after example runs.

from faststream import FastStream, Logger\nfrom faststream.rabbit import RabbitBroker, RabbitExchange, RabbitQueue\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\nexch = RabbitExchange(\"exchange\", auto_delete=True)\n\nqueue_1 = RabbitQueue(\"test-q-1\", auto_delete=True)\nqueue_2 = RabbitQueue(\"test-q-2\", auto_delete=True)\n\n\n@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 1\n    await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 2\n    await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 1\n    await broker.publish(queue=\"test-q-2\", exchange=exch)  # handlers: 3\n
","boost":10},{"location":"rabbit/examples/direct/#consumer-announcement","title":"Consumer Announcement","text":"

First, we announce our Direct exchange and several queues that will listen to it:

exch = RabbitExchange(\"exchange\", auto_delete=True)\n\nqueue_1 = RabbitQueue(\"test-q-1\", auto_delete=True)\nqueue_2 = RabbitQueue(\"test-q-2\", auto_delete=True)\n

Then we sign up several consumers using the advertised queues to the exchange we created:

@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n

Note

handler1 and handler2 are subscribed to the same exchange using the same queue: within a single service, this does not make sense, since messages will come to these handlers in turn. Here we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"rabbit/examples/direct/#message-distribution","title":"Message Distribution","text":"

Now, the distribution of messages between these consumers will look like this:

await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 1\n

Message 1 will be sent to handler1 because it listens to the \"exchange\" using a queue with the routing key \"test-q-1\".

await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 2\n

Message 2 will be sent to handler2 because it listens to the \"exchange\" using the same queue, but handler1 is busy.

await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 1\n

Message 3 will be sent to handler1 again because it is currently free.

await broker.publish(queue=\"test-q-2\", exchange=exch)  # handlers: 3\n

Message 4 will be sent to handler3 because it is the only one listening to the \"exchange\" using a queue with the routing key \"test-q-2\".

","boost":10},{"location":"rabbit/examples/fanout/","title":"Fanout Exchange","text":"

The Fanout Exchange is an even simpler, but slightly less popular way of routing in RabbitMQ. This type of exchange sends messages to all queues subscribed to it, ignoring any arguments of the message.

At the same time, if the queue listens to several consumers, messages will also be distributed among them.

","boost":10},{"location":"rabbit/examples/fanout/#example","title":"Example","text":"
from faststream import FastStream, Logger\nfrom faststream.rabbit import ExchangeType, RabbitBroker, RabbitExchange, RabbitQueue\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\nexch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.FANOUT)\n\nqueue_1 = RabbitQueue(\"test-q-1\", auto_delete=True)\nqueue_2 = RabbitQueue(\"test-q-2\", auto_delete=True)\n\n\n@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(exchange=exch)  # handlers: 1, 2, 3\n    await broker.publish(exchange=exch)  # handlers: 1, 2, 3\n    await broker.publish(exchange=exch)  # handlers: 1, 2, 3\n    await broker.publish(exchange=exch)  # handlers: 1, 2, 3\n
","boost":10},{"location":"rabbit/examples/fanout/#consumer-announcement","title":"Consumer Announcement","text":"

To begin with, we announced our Fanout exchange and several queues that will listen to it:

exch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.FANOUT)\n\nqueue_1 = RabbitQueue(\"test-q-1\", auto_delete=True)\nqueue_2 = RabbitQueue(\"test-q-2\", auto_delete=True)\n

Then we signed up several consumers using the advertised queues to the exchange we created:

@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n

Note

handler1 and handler2 are subscribed to the same exchange using the same queue: within a single service, this does not make sense, since messages will come to these handlers in turn. Here we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"rabbit/examples/fanout/#message-distribution","title":"Message Distribution","text":"

Now the all messages will be send to all subscribers due they are binded to the same FANOUT exchange:

await broker.publish(exchange=exch)  # handlers: 1, 2, 3\nawait broker.publish(exchange=exch)  # handlers: 1, 2, 3\nawait broker.publish(exchange=exch)  # handlers: 1, 2, 3\nawait broker.publish(exchange=exch)  # handlers: 1, 2, 3\n

Note

When sending messages to Fanout exchange, it makes no sense to specify the arguments queue or routing_key, because they will be ignored.

","boost":10},{"location":"rabbit/examples/headers/","title":"Header Exchange","text":"

The Header Exchange is the most complex and flexible way to route messages in RabbitMQ. This exchange type sends messages to queues according by matching the queue binding arguments with message headers.

At the same time, if several consumers are subscribed to the queue, messages will also be distributed among them.

","boost":10},{"location":"rabbit/examples/headers/#example","title":"Example","text":"
from faststream import FastStream, Logger\nfrom faststream.rabbit import ExchangeType, RabbitBroker, RabbitExchange, RabbitQueue\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\nexch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.HEADERS)\n\nqueue_1 = RabbitQueue(\n    \"test-queue-1\",\n    auto_delete=True,\n    bind_arguments={\"key\": 1},\n)\nqueue_2 = RabbitQueue(\n    \"test-queue-2\",\n    auto_delete=True,\n    bind_arguments={\"key\": 2, \"key2\": 2, \"x-match\": \"any\"},\n)\nqueue_3 = RabbitQueue(\n    \"test-queue-3\",\n    auto_delete=True,\n    bind_arguments={\"key\": 2, \"key2\": 2, \"x-match\": \"all\"},\n)\n\n\n@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n\n@broker.subscriber(queue_3, exch)\nasync def base_handler4(logger: Logger):\n    logger.info(\"base_handler4\")\n\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 1\n    await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 2\n    await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 1\n    await broker.publish(exchange=exch, headers={\"key\": 2})  # handlers: 3\n    await broker.publish(exchange=exch, headers={\"key2\": 2})  # handlers: 3\n    await broker.publish(\n        exchange=exch, headers={\"key\": 2, \"key2\": 2.0}\n    )  # handlers: 3, 4\n
","boost":10},{"location":"rabbit/examples/headers/#consumer-announcement","title":"Consumer Announcement","text":"

First, we announce our Header exchange and several queues that will listen to it:

exch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.HEADERS)\n\nqueue_1 = RabbitQueue(\n    \"test-queue-1\",\n    auto_delete=True,\n    bind_arguments={\"key\": 1},\n)\nqueue_2 = RabbitQueue(\n    \"test-queue-2\",\n    auto_delete=True,\n    bind_arguments={\"key\": 2, \"key2\": 2, \"x-match\": \"any\"},\n)\nqueue_3 = RabbitQueue(\n    \"test-queue-3\",\n    auto_delete=True,\n    bind_arguments={\"key\": 2, \"key2\": 2, \"x-match\": \"all\"},\n)\n

The x-match argument indicates whether the arguments should match the message headers in whole or in part.

Then we signed up several consumers using the advertised queues to the exchange we created:

@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n\n@broker.subscriber(queue_3, exch)\nasync def base_handler4(logger: Logger):\n    logger.info(\"base_handler4\")\n

Note

handler1 and handler2 are subscribed to the same exchange using the same queue: within a single service, this does not make sense, since messages will come to these handlers in turn. Here we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"rabbit/examples/headers/#message-distribution","title":"Message Distribution","text":"

Now the distribution of messages between these consumers will look like this:

await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 1\n

Message 1 will be sent to handler1 because it listens to a queue whose \"key\" header matches the \"key\" header of the message.

await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 2\n

Message 2 will be sent to handler2 because it listens to exchange using the same queue, but handler1 is busy.

await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 1\n

Message 3 will be sent to handler1 again because it is currently free.

await broker.publish(exchange=exch, headers={\"key\": 2})  # handlers: 3\n

Message 4 will be sent to handler3 because it listens to a queue whose \"key\" header coincided with the \"key\" header of the message.

await broker.publish(exchange=exch, headers={\"key2\": 2})  # handlers: 3\n

Message 5 will be sent to handler3 because it listens to a queue whose header \"key2\" coincided with the header \"key2\" of the message.

await broker.publish(\n    exchange=exch, headers={\"key\": 2, \"key2\": 2.0}\n)  # handlers: 3, 4\n

Message 6 will be sent to handler3 and handler4 because the message headers completely match the queue keys.

Note

When sending messages to Header exchange, it makes no sense to specify the arguments queue or routing_key, because they will be ignored

Warning

For incredibly complex routes, you can use the option to bind an exchange to another exchange. In this case, all the same rules apply as for queues subscribed to exchange. The only difference is that the signed exchange can further distribute messages according to its own rules.

So, for example, you can combine Topic and Header exchange types.

","boost":10},{"location":"rabbit/examples/stream/","title":"RabbitMQ Streams","text":"

RabbitMQ has a Streams feature, which is closely related to Kafka topics.

The main difference from regular RabbitMQ queues is that the messages are not deleted after consuming.

And FastStream supports this feature as well!

from faststream import FastStream, Logger\nfrom faststream.rabbit import RabbitBroker, RabbitQueue\n\nbroker = RabbitBroker(max_consumers=10)\napp = FastStream(broker)\n\nqueue = RabbitQueue(\n    name=\"test-stream\",\n    durable=True,\n    arguments={\n        \"x-queue-type\": \"stream\",\n    },\n)\n\n\n@broker.subscriber(\n    queue,\n    consume_args={\"x-stream-offset\": \"first\"},\n)\nasync def handle(msg, logger: Logger):\n    logger.info(msg)\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"Hi!\", queue)\n
","boost":10},{"location":"rabbit/examples/topic/","title":"Topic Exchange","text":"

The Topic Exchange is a powerful RabbitMQ routing tool. This type of exchange sends messages to the queue in accordance with the pattern specified when they are connected to exchange and the routing_key of the message itself.

At the same time, if several consumers are subscribed to the queue, messages will be distributed among them.

","boost":10},{"location":"rabbit/examples/topic/#example","title":"Example","text":"
from faststream import FastStream, Logger\nfrom faststream.rabbit import ExchangeType, RabbitBroker, RabbitExchange, RabbitQueue\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\nexch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.TOPIC)\n\nqueue_1 = RabbitQueue(\"test-queue-1\", auto_delete=True, routing_key=\"*.info\")\nqueue_2 = RabbitQueue(\"test-queue-2\", auto_delete=True, routing_key=\"*.debug\")\n\n\n@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 1\n    await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 2\n    await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 1\n    await broker.publish(routing_key=\"logs.debug\", exchange=exch)  # handlers: 3\n
","boost":10},{"location":"rabbit/examples/topic/#consumer-announcement","title":"Consumer Announcement","text":"

First, we announce our Topic exchange and several queues that will listen to it:

exch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.TOPIC)\n\nqueue_1 = RabbitQueue(\"test-queue-1\", auto_delete=True, routing_key=\"*.info\")\nqueue_2 = RabbitQueue(\"test-queue-2\", auto_delete=True, routing_key=\"*.debug\")\n

At the same time, in the routing_key of our queues, we specify the pattern of routing keys that will be processed by this queue.

Then we sign up several consumers using the advertised queues to the exchange we created:

@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n

Note

handler1 and handler2 are subscribed to the same exchange using the same queue: within a single service, this does not make sense, since messages will come to these handlers in turn. Here we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"rabbit/examples/topic/#message-distribution","title":"Message Distribution","text":"

Now the distribution of messages between these consumers will look like this:

await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 1\n

Message 1 will be sent to handler1 because it listens to \"exchange\" using a queue with the routing key \"*.info\".

await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 2\n

Message 2 will be sent to handler2 because it listens to \"exchange\" using the same queue, but handler1 is busy.

await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 1\n

Message 3 will be sent to handler1 again because it is currently free.

await broker.publish(routing_key=\"logs.debug\", exchange=exch)  # handlers: 3\n

Message 4 will be sent to handler3 because it is the only one listening to \"exchange\" using a queue with the routing key \"*.debug\".

","boost":10},{"location":"redis/","title":"Redis Broker","text":"","boost":10},{"location":"redis/#redis-overview","title":"Redis Overview","text":"","boost":10},{"location":"redis/#what-is-redis","title":"What is Redis?","text":"

Redis is an open-source, in-memory data structure store, used as a database, cache, and message broker. It supports various data structures such as strings, hashes, lists, sets, sorted sets, bitmaps, hyperloglogs, and geospatial indexes with radius queries. Redis has built-in replication, Lua scripting, LRU eviction, transactions, and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.

","boost":10},{"location":"redis/#key-redis-concepts","title":"Key Redis Concepts","text":"

Redis is not just a key-value store; it is a data structures server, supporting different kinds of values. This makes Redis flexible and suitable for a wide range of problems. It offers versatile approaches for message handling through Pub/Sub, List, and Stream structures.

","boost":10},{"location":"redis/#1-pubsub","title":"1. Pub/Sub","text":"

Redis Pub/Sub implements the Publish/Subscribe messaging paradigm where senders (publishers) are not programmed to send their messages to specific receivers (subscribers). Instead, published messages are characterized into channels, without knowledge of what (if any) subscribers there may be.

","boost":10},{"location":"redis/#2-list","title":"2. List","text":"

In contrast, Redis List capitalizes on a straightforward list data structure. Messages, pushed by producers, form a first-in, first-out (FIFO) queue. Consumers, in turn, retrieve messages from this ordered list, providing a simplified mechanism for sequential message processing.

","boost":10},{"location":"redis/#3-streams","title":"3. Streams","text":"

Redis Streams introduce a more advanced concept, embracing an append-only log-like structure. Messages, organized as entries, allow for nuanced features like consumer groups, enabling parallel processing, and acknowledgment for precise message handling. Streams excel in scenarios demanding scalability, persistence, and ordered message processing.

Ultimately, the choice between Pub/Sub, List, or Streams hinges on the specific needs of the application. Redis Pub/Sub suits real-time communication, List offers simplicity in ordered processing, while Streams cater to complex, scalable, and ordered message handling, each providing tailored solutions based on distinct use case requirements.

","boost":10},{"location":"redis/#redis-in-faststream","title":"Redis in FastStream","text":"","boost":10},{"location":"redis/#faststream-redisbroker","title":"FastStream RedisBroker","text":"

The FastStream RedisBroker is a key component of the FastStream framework that enables seamless integration with Redis. With the RedisBroker, developers can easily connect to Redis instances, publish messages to Redis channels, and subscribe to Redis channels within their FastStream applications.

","boost":10},{"location":"redis/#establishing-a-connection","title":"Establishing a Connection","text":"

To connect to Redis using the FastStream RedisBroker module, follow these steps:

  1. Initialize the RedisBroker instance: Start by initializing a RedisBroker instance with the necessary configuration, including Redis server address and port.

  2. Create your processing logic: Write a function that will consume the incoming messages from the subscribed channel and optionally publish a response to another channel.

  3. Decorate your processing function: To connect your processing function to the desired Redis channels, you need to decorate it with @broker.subscriber(...) and @broker.publisher(...) decorators. Now, after you start your application, your processing function will be called whenever a new message in the subscribed channel is available and produce the function return value to the channel defined in the publisher decorator.

Here's a simplified code example demonstrating how to establish a connection to Redis using FastStream's RedisBroker module:

from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-channel\")\n@broker.publisher(\"out-channel\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n

This minimal example illustrates how FastStream simplifies the process of connecting to Redis and performing basic message processing from the in-channel to the out-channel. Depending on your specific use case and requirements, you can further customize your Redis integration with FastStream to build efficient and responsive applications.

For more advanced configuration options and detailed usage instructions, please refer to the FastStream Redis documentation and the official Redis documentation.

","boost":10},{"location":"redis/message/","title":"Accessing Redis Message Information with FastStream","text":"

In FastStream, messages passed through a Redis broker are serialized and can be interacted with just like function parameters. However, you might occasionally need to access more than just the message content, such as metadata and other attributes.

","boost":10},{"location":"redis/message/#redis-message-access","title":"Redis Message Access","text":"

When dealing with Redis broker in FastStream, you can easily access message details by using the RedisMessage object which wraps the underlying message with additional context information. This object is specifically tailored for Redis and contains relevant message attributes:

For instance, if you need to retrieve headers from an incoming Redis message, here\u2019s how you might do it:

from faststream.redis import RedisMessage\n\n@broker.subscriber(\"test-stream\")\nasync def stream_handler(msg: str, message: RedisMessage):\n    print(message.headers)\n
","boost":10},{"location":"redis/message/#targeted-message-fields-access","title":"Targeted Message Fields Access","text":"

It's common to require only specific elements of the message rather than the entire data structure. For this purpose, FastStream allows you to access individual message fields by specifying the field you are interested in as an argument in your handler function.

For example, if you want to access the headers directly, you might do it as follows:

from faststream import Context\n\n@broker.subscriber(\"test-stream\")\nasync def stream_handler(\n    msg: str,\n    headers: AnyDict = Context(\"message.headers\"),\n):\n    print(headers)\n

The Context object lets you reference message attributes directly, making your handler functions neater and reducing the amount of boilerplate code needed.

","boost":10},{"location":"redis/rpc/","title":"Redis RPC with FastStream","text":"

FastStream RedisBroker provides the powerful capability to perform Remote Procedure Calls (RPC) using Redis. This feature enables you to send a message and await a response, effectively creating a synchronous request-response pattern over the inherently asynchronous Redis messaging system. Below is the guide to set up and utilize the Redis RPC publishing feature with FastStream.

Note

The RPC feature is implemented over Redis Pub/Sub indepenently of the original subscriber type.

","boost":10},{"location":"redis/rpc/#rpc-with-redis-overview","title":"RPC with Redis Overview","text":"

In a traditional publish/subscribe setup, the publishing party sends messages without expecting any direct response from the subscribers. However, with RPC, the publisher sends a message and waits for a response from the subscriber, which can then be used for subsequent operations or processing.

FastStream allows you to define RPC-style communication channels, lists, or streams by using the RedisBroker's publishing function with the rpc flag set to True.

","boost":10},{"location":"redis/rpc/#implementing-redis-rpc-in-faststream","title":"Implementing Redis RPC in FastStream","text":"

To implement Redis RPC with RedisBroker in FastStream, follow the steps below:

  1. Initiate your FastStream application with RedisBroker

    broker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n
  2. Define subscriber handlers for various Redis data types (e.g., channel, list, stream) that can process incoming messages and return responses.

    @broker.subscriber(channel=\"test-channel\")\nasync def handle_channel(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n\n\n@broker.subscriber(list=\"test-list\")\nasync def handle_list(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n\n\n@broker.subscriber(stream=\"test-stream\")\nasync def handle_stream(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n
  3. Send RPC messages through RedisBroker and await responses on the correct data type.

    After your application has started and the subscribers are ready to receive messages, you can publish messages with the rpc option enabled. Additionally, you can set an rpc_timeout to decide how long the publisher should wait for a response before timing out.

    @app.after_startup\nasync def t():\n    msg = \"Hi!\"\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        channel=\"test-channel\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        list=\"test-list\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        stream=\"test-stream\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n

In this example, we assert that the msg sent is the same as the response received from the subscriber, demonstrating an operational RPC pattern over three different Redis data types.

","boost":10},{"location":"redis/rpc/#full-example-of-redis-rpc-with-faststream","title":"Full Example of Redis RPC with FastStream","text":"

Combining all the code snippets above, here is the complete example of how to set up Redis RPC with FastStream RedisBroker:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(channel=\"test-channel\")\nasync def handle_channel(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n\n\n@broker.subscriber(list=\"test-list\")\nasync def handle_list(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n\n\n@broker.subscriber(stream=\"test-stream\")\nasync def handle_stream(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n\n\n@app.after_startup\nasync def t():\n    msg = \"Hi!\"\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        channel=\"test-channel\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        list=\"test-list\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        stream=\"test-stream\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n

By embracing Redis RPC with FastStream, you can build sophisticated message-based architectures that require direct feedback from message processors. This feature is particularly suitable for cases where immediate processing is necessary or calling functions across different services is essential.

","boost":10},{"location":"redis/security/","title":"FastStream Redis Security","text":"

This chapter discusses the security options available in FastStream and how to use them.

","boost":10},{"location":"redis/security/#security-objects","title":"Security Objects","text":"

FastStream allows you to enhance the security of applications by using security objects when creating brokers. These security objects encapsulate security-related configurations and mechanisms. Security objects supported in FastStream for Redis are:

","boost":10},{"location":"redis/security/#1-basesecurity-object","title":"1. BaseSecurity Object","text":"

Purpose: The BaseSecurity object wraps ssl.SSLContext object and is used to enable SSL/TLS encryption for secure communication between FastStream services and external components such as message brokers.

Usage:

import ssl\n\nfrom faststream.redis import RedisBroker\nfrom faststream.security import BaseSecurity\n\nssl_context = ssl.create_default_context()\nsecurity = BaseSecurity(ssl_context=ssl_context)\n\nbroker = RedisBroker(security=security)\n
","boost":10},{"location":"redis/security/#2-saslplaintext-object-with-ssltls","title":"2. SASLPlaintext Object with SSL/TLS","text":"

Purpose: The SASLPlaintext object is used for authentication in SASL (Simple Authentication and Security Layer) plaintext mode. It allows you to provide a username and password for authentication.

Usage:

import ssl\n\nfrom faststream.redis import RedisBroker\nfrom faststream.security import SASLPlaintext\n\nssl_context = ssl.create_default_context()\nsecurity = SASLPlaintext(\n    ssl_context=ssl_context,\n    username=\"admin\",\n    password=\"password\", \n)\n\nbroker = RedisBroker(security=security)\n
","boost":10},{"location":"redis/list/","title":"Redis Lists","text":"

Redis Lists are a simple and flexible data structure that function as ordered collections of strings. They are similar to lists in programming languages, and Redis provides commands to perform a variety of operations such as adding, retrieving, and removing elements from either end of the list.

Redis Lists are particularly useful for scenarios such as implementing queues, effectively using the list as a FIFO (First-In-First-Out) structure.

","boost":10},{"location":"redis/list/batch/","title":"Redis List Batch Subscriber","text":"

If you want to consume data in batches from a Redis list, the @broker.subscriber(...) decorator makes it possible. By defining your consumed msg object as a list of messages and setting the batch parameter to True within the ListSub object, the subscriber will call your consuming function with a batch of messages. Let's walk through how to achieve this with the FastStream library.

","boost":10},{"location":"redis/list/batch/#using-the-subscriber-with-batching","title":"Using the Subscriber with Batching","text":"

To consume messages in batches from a Redis list, follow these steps:

","boost":10},{"location":"redis/list/batch/#step-1-define-your-subscriber","title":"Step 1: Define Your Subscriber","text":"

In your FastStream application, define the subscriber using the @broker.subscriber(...) decorator. Ensure that you pass a ListSub object with the batch parameter set to True. This configuration tells the subscriber to handle message consumption in batches from the specified Redis list.

@broker.subscriber(list=ListSub(\"test-list\", batch=True))\n
","boost":10},{"location":"redis/list/batch/#step-2-implement-your-consuming-function","title":"Step 2: Implement Your Consuming Function","text":"

Create a consuming function that accepts the list of messages. The @broker.subscriber(...) decorator will take care of collecting and grouping messages into batches.

@broker.subscriber(list=ListSub(\"test-list\", batch=True))\nasync def handle(msg: list[str], logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/list/batch/#example-of-consuming-in-batches","title":"Example of Consuming in Batches","text":"

Let's illustrate how to consume messages in batches from the \"test-list\" Redis list with a practical example:

from faststream import FastStream, Logger\nfrom faststream.redis import ListSub, RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(list=ListSub(\"test-list\", batch=True))\nasync def handle(msg: list[str], logger: Logger):\n    logger.info(msg)\n

In this example, the subscriber is configured to process messages in batches from the Redis list, and the consuming function is designed to handle these batches efficiently.

Consuming messages in batches is a valuable technique when you need to optimize the processing of high volumes of data in your Redis-based applications. It allows for more efficient resource utilization and can enhance the overall performance of your data processing tasks.

","boost":10},{"location":"redis/list/batch/#batch-publishing","title":"Batch publishing","text":"

Also, Redis List is the only data structure supporting publishing in batches with FastStream. To send multiple messages in a single request, you just need to:

","boost":10},{"location":"redis/list/publishing/","title":"Redis List Publishing with FastStream","text":"

Utilizing the FastStream library, you can effectively publish data to Redis lists, which act as queues in Redis-based messaging systems.

","boost":10},{"location":"redis/list/publishing/#understanding-redis-list-publishing","title":"Understanding Redis List Publishing","text":"

Just like with Redis streams, messages can be published to Redis lists. FastStream utilizes the @broker.publisher(...) decorator, along with a list's name, to push messages onto the list.

  1. Instantiate your RedisBroker

    broker = RedisBroker(\"localhost:6379\")\n
  2. Create your FastStream application with the instantiated RedisBroker

    app = FastStream(broker)\n
  3. Define a Pydantic model for your data

    class Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n
  4. Implement a data processing function for publishing to Redis lists

    Use the @broker.publisher(list=\"...\") decorator alongside the @broker.subscriber(list=\"...\") decorator to create a function that processes incoming messages and pushes the results to an output list in Redis.

    @broker.subscriber(list=\"input-list\")\n@broker.publisher(list=\"output-list\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n

In this pattern, the function stands as a subscriber to the \"input-list\" and publishes the processed data as a new message to the \"output-list\". By using decorators, you establish a pipeline that reads messages from one Redis list, applies some logic, and then pushes outputs to another list.

","boost":10},{"location":"redis/list/publishing/#full-example-of-redis-list-publishing","title":"Full Example of Redis List Publishing","text":"

Here's an example that demonstrates Redis list publishing in action using decorators with FastStream:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = RedisBroker(\"localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(list=\"input-list\")\n@broker.publisher(list=\"output-list\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n

The provided example illustrates the ease of setting up publishing mechanisms to interact with Redis lists. In this environment, messages are dequeued from the input list, processed, and enqueued onto the output list seamlessly, empowering developers to leverage Redis lists as messaging queues.

By following these simple steps, you can perform list-based publish/subscribe operations in a Redis environment using the FastStream library, capitalizing on Redis' fast, in-memory data structure store capabilities.

","boost":10},{"location":"redis/list/subscription/","title":"Redis List Basic Subscriber","text":"

To start consuming from a Redis list, simply decorate your consuming function with the @broker.subscriber(...) decorator, passing a string as the list key.

In the following example, we will create a simple FastStream app that will consume messages from a \"test-list\" Redis list.

The full app code looks like this:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(list=\"test-list\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/list/subscription/#import-faststream-and-redisbroker","title":"Import FastStream and RedisBroker","text":"

To use the @broker.subscriber(...) decorator, first, we need to import the base FastStream app and RedisBroker to create our broker.

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n
","boost":10},{"location":"redis/list/subscription/#create-a-redisbroker","title":"Create a RedisBroker","text":"

Next, we will create a RedisBroker object and wrap it into the FastStream object so that we can start our app using CLI later.

broker = RedisBroker()\napp = FastStream(broker)\n
","boost":10},{"location":"redis/list/subscription/#create-a-function-that-will-consume-messages-from-a-redis-list","title":"Create a Function that will Consume Messages from a Redis list","text":"

Let\u2019s create a consumer function that will consume messages from \"test-list\" Redis list and log them.

@broker.subscriber(list=\"test-list\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n

The function decorated with the @broker.subscriber(...) decorator will be called when a message is pushed to the Redis list.

The message will then be injected into the typed msg argument of the function, and its type will be used to parse the message.

In this example case, when the message is pushed to a \"test-list\" list, it will be received by the handle function, and the logger will log the message content.

","boost":10},{"location":"redis/pubsub/","title":"Redis Channels","text":"

Redis Pub/Sub Channels are a feature of Redis that enables messaging between clients through a publish/subscribe (pub/sub) pattern. A Redis channel is essentially a medium through which messages are transmitted. Different clients can subscribe to these channels to listen for messages, while other clients can publish messages to these channels.

When a message is published to a Redis channel, all subscribers to that channel receive the message instantly. This makes Redis channels suitable for a variety of real-time applications such as chat rooms, notifications, live updates, and many more use cases where messages must be broadcast promptly to multiple clients.

","boost":10},{"location":"redis/pubsub/#limitations","title":"Limitations","text":"

Redis Pub/Sub Channels, while powerful for real-time communication in scenarios like chat rooms and live updates, have certain limitations when compared to Redis List and Redis Streams.

In summary, while Redis Pub/Sub excels in simplicity and real-time broadcast scenarios, Redis List and Redis Streams provide additional features such as message persistence, ordered processing, and scalability, making them better suited for certain use cases with specific requirements. The choice between these Redis features depends on the nature of the application and its messaging needs.

","boost":10},{"location":"redis/pubsub/publishing/","title":"Publishing","text":"

The FastStream RedisBroker supports all standard publishing use cases similar to the KafkaBroker, allowing you to publish messages to Redis channels with ease.

Below you will find guidance on how to utilize the RedisBroker for publishing messages, including creating publisher objects and using decorators for streamlined publishing workflows.

","boost":10},{"location":"redis/pubsub/publishing/#basic-redis-channel-publishing","title":"Basic Redis Channel Publishing","text":"

The RedisBroker allows you to publish messages directly to Redis channels. You can use Python primitives and pydantic.BaseModel to define the content of the message.

To publish a message to a Redis channel, follow these steps:

  1. Create your RedisBroker instance

    broker = RedisBroker(\"redis://localhost:6379\")\n
  2. Publish a message using the publish method

    await broker.publish(msg, \"input_data\")\n

This is the most straightforward way to use the RedisBroker to publish messages to Redis channels.

","boost":10},{"location":"redis/pubsub/publishing/#creating-a-publisher-object","title":"Creating a publisher object","text":"

For a more structured approach and to include your publishers in the AsyncAPI documentation, it's recommended to create publisher objects. Here's how to do it:

  1. Create your RedisBroker instance

    broker = RedisBroker(\"redis://localhost:6379\")\n
  2. Create a publisher instance for a specific channel

    prepared_publisher = broker.publisher(\"input_data\")\n
  3. Publish a message using the publish method of the prepared publisher

    await prepared_publisher.publish(msg)\n

When you encapsulate your broker within a FastStream object, the publisher will be documented in your service's AsyncAPI documentation.

","boost":10},{"location":"redis/pubsub/publishing/#decorating-your-publishing-functions","title":"Decorating your publishing functions","text":"

Decorators in FastStream provide a convenient way to define the data flow within your application. The RedisBroker allows you to use decorators to publish messages to Redis channels, similar to the KafkaBroker.

By decorating a function with both @broker.subscriber(...) and @broker.publisher(...), you create a DataPipeline unit that processes incoming messages and publishes the results to another channel. The order of decorators does not matter, but they must be applied to a function that has already been decorated by a @broker.subscriber(...).

The decorated function should have a return type annotation to ensure the correct interpretation of the return value before it's published.

Here's an example of using decorators with RedisBroker:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\nto_output_data = broker.publisher(\"output_data\")\n\n\n@to_output_data\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
  1. Initialize the RedisBroker instance: Start by creating a RedisBroker instance.

    broker = RedisBroker(\"redis://localhost:6379\")\n
  2. Prepare your publisher object to be used as a decorator:

    to_output_data = broker.publisher(\"output_data\")\n
  3. Create your processing logic: Implement a function that will process incoming messages and produce a response to be published to another Redis channel.

    async def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
  4. Decorate your processing function: Apply the @broker.subscriber(...) and @broker.publisher(...) decorators to your function to define the input channel and the output channel, respectively. Once your application is running, this decorated function will be triggered whenever a new message arrives on the \"input_data\" channel, and it will publish the result to the \"output_data\" channel.

    @to_output_data\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
","boost":10},{"location":"redis/pubsub/subscription/","title":"Channel Subscription","text":"","boost":10},{"location":"redis/pubsub/subscription/#basic-channel-subscription","title":"Basic Channel Subscription","text":"

Redis Pub/Sub is the default subscriber type in FastStream, so you can simply create a regular @broker.subscriber(\"channel_name\") with a channel name and it creates a subscriber using Redis Pub/Sub.

In this example, we will build a FastStream application that listens to messages from the Redis channel named \"test\".

The complete application code is presented below:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/pubsub/subscription/#import-faststream-and-redisbroker","title":"Import FastStream and RedisBroker","text":"

To utilize the @broker.subscriber(...) decorator for Redis channel subscription, you must first import FastStream and RedisBroker.

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n
","boost":10},{"location":"redis/pubsub/subscription/#create-a-redisbroker-instance","title":"Create a RedisBroker Instance","text":"

Create a RedisBroker object and pass it to the FastStream object. This setup prepares the application for launch using the FastStream CLI.

broker = RedisBroker()\napp = FastStream(broker)\n
","boost":10},{"location":"redis/pubsub/subscription/#define-the-message-handler-function","title":"Define the Message Handler Function","text":"

Construct a function that will act as the consumer of messages from the \"test\" channel and use the logger to output the message content.

@broker.subscriber(\"test\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n

When a message is published to the Redis channel \"test\", it will trigger the invocation of the decorated function. The message will be passed to the function's msg parameter, while the logger will be available for logging purposes.

","boost":10},{"location":"redis/pubsub/subscription/#pattern-channel-subscription","title":"Pattern Channel Subscription","text":"

For subscribing to multiple Redis channels matching a pattern, use the @broker.subscriber(channel=PubSub(\"pattern\", pattern=True)) decorator, where the channel argument receives a PubSub object with the pattern and pattern flag set to True.

Here's how to create a FastStream application that subscribes to all channels matching the \"test.*\" pattern:

from faststream import FastStream, Logger\nfrom faststream.redis import PubSub, RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(channel=PubSub(\"test.*\", pattern=True))\nasync def handle_test(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/pubsub/subscription/#use-pubsub-for-pattern-matching","title":"Use PubSub for Pattern Matching","text":"

Import the PubSub class from faststream.redis along with other necessary modules.

from faststream import FastStream, Logger\nfrom faststream.redis import PubSub, RedisBroker\n
","boost":10},{"location":"redis/pubsub/subscription/#specify-the-pattern-for-channel-subscription","title":"Specify the Pattern for Channel Subscription","text":"

To define the pattern subscription, create a PubSub object with the desired pattern (\"test.*\" in this case) and indicate that it's a pattern subscription by setting pattern=True.

@broker.subscriber(channel=PubSub(\"test.*\", pattern=True))\n
","boost":10},{"location":"redis/pubsub/subscription/#create-the-pattern-message-handler-function","title":"Create the Pattern Message Handler Function","text":"

Decide on a function that will act as the subscriber of messages from channels matching the specified pattern. Logging the messages is handled similarly as with basic channel subscription.

@broker.subscriber(channel=PubSub(\"test.*\", pattern=True))\nasync def handle_test(msg: str, logger: Logger):\n    logger.info(msg)\n

With pattern channel subscription, when a message is published to a channel that matches the specified pattern (\"test.*\"), our handler function will be invoked. The message is delivered to the msg argument of the function, similar to how it works in basic channel subscriptions.

","boost":10},{"location":"redis/pubsub/subscription/#pattern-data-access","title":"Pattern data access","text":"

You can also use the Redis Pub/Sub pattern feature to encode some data directly in the channel name. With FastStream you can easily access this data using the following code:

from faststream import FastStream, Logger, Path\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test.{data}\")\nasync def handle_test(\n    msg: str,\n    logger: Logger,\n    data: str = Path(),\n):\n    logger.info(f\"Channel `{data=}`, body `{msg=}`\")\n
","boost":10},{"location":"redis/streams/","title":"Redis Streams","text":"

Redis Streams are a data structure introduced in Redis 5.0 that offer a reliable and highly scalable way to handle streams of data. They are similar to logging systems like Apache Kafka, where data is stored in a log structure and can be consumed by multiple clients. Streams provide a sequence of ordered messages, and they are designed to handle a high volume of data by allowing partitioning and multiple consumers.

A Redis Stream is a collection of entries, each having an ID (which includes a timestamp) and a set of key-value pairs representing the message data. Clients can add to a stream by generating a new entry and can read from a stream to consume its messages.

Streams have unique features such as:

","boost":10},{"location":"redis/streams/ack/","title":"Stream Acknowledgement","text":"

When working with Redis streams in the FastStream library, it's important to manage message acknowledgements carefully to ensure that messages are not lost and that they have been processed as intended.

By default, when using the FastStream with a Redis stream, the library will automatically acknowledge (ack) that a message has been processed. This follows the at most once processing guarantee.

","boost":10},{"location":"redis/streams/ack/#manual-acknowledgement","title":"Manual Acknowledgement","text":"

In cases where you want explicit control over when a message is acknowledged, you can manually acknowledge a message by accessing the ack and nack methods provided:

from faststream.redis.annotations import RedisMessage, Redis\n\n# Setup broker and faststream app\n...\n\n@broker.subscriber(StreamSub(\"test-stream\", group=\"test-group\", consumer=\"1\"))\nasync def base_handler(body: dict, msg: RedisMessage, redis: Redis):\n    # Process the message\n    ...\n\n    # Manually acknowledge the message\n    await msg.ack(redis)\n    # or, if processing fails and you want to reprocess later\n    await msg.nack()\n

Using ack will mark the message as processed in the stream, while nack is useful for situations where you might need to reprocess a message due to a handling failure.

","boost":10},{"location":"redis/streams/ack/#interrupt-process","title":"Interrupt Process","text":"

If the need arises to instantly interrupt message processing at any point in the call stack and acknowledge the message, you can achieve this by raising the faststream.exceptions.AckMessage exception:

from faststream import FastStream\nfrom faststream.exceptions import AckMessage\nfrom faststream.redis import RedisBroker, StreamSub\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(stream=StreamSub(\"test-stream\", group=\"test-group\", consumer=\"1\"))\nasync def handle(body):\n    processing_logic(body)\n\n\ndef processing_logic(body):\n    if True:\n        raise AckMessage()\n\n\n@app.after_startup\nasync def test_publishing():\n    await broker.publish(\"Hello World!\", stream=\"test-stream\")\n

By raising AckMessage, FastStream will halt the current message processing routine and immediately acknowledge it. Analogously, raising NackMessage would prevent the message from being acknowledged and could lead to its subsequent reprocessing by the same or a different consumer.

Tip

If you want to disable FastStream Acknowledgement logic at all, you can use @broker.subscriber(..., no_ack=True) option. This way you should always process a message (ack/nack/terminate/etc) by yourself.

","boost":10},{"location":"redis/streams/batch/","title":"Redis Stream Batch Subscriber","text":"

If you want to consume data in batches from a Redis stream, the @broker.subscriber(...) decorator makes it possible. By defining your consumed msg object as a list of messages and setting the batch parameter to True within the StreamSub object, the subscriber will call your consuming function with a batch of messages. Let's walk through how to achieve this with the FastStream library.

","boost":10},{"location":"redis/streams/batch/#using-the-subscriber-with-batching","title":"Using the Subscriber with Batching","text":"

To consume messages in batches from a Redis stream, follow these steps:

","boost":10},{"location":"redis/streams/batch/#step-1-define-your-subscriber","title":"Step 1: Define Your Subscriber","text":"

In your FastStream application, define the subscriber using the @broker.subscriber(...) decorator. Ensure that you pass a StreamSub object with the batch parameter set to True. This configuration tells the subscriber to handle message consumption in batches from the specified Redis stream.

@broker.subscriber(stream=StreamSub(\"test-stream\", batch=True))\n
","boost":10},{"location":"redis/streams/batch/#step-2-implement-your-consuming-function","title":"Step 2: Implement Your Consuming Function","text":"

Create a consuming function that accepts the list of messages. The @broker.subscriber(...) decorator will take care of collecting and grouping messages into batches.

@broker.subscriber(stream=StreamSub(\"test-stream\", batch=True))\nasync def handle(msg: list[str], logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/streams/batch/#example-of-consuming-in-batches","title":"Example of Consuming in Batches","text":"

Let's illustrate how to consume messages in batches from the \"test-stream\" Redis stream with a practical example:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker, StreamSub\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(stream=StreamSub(\"test-stream\", batch=True))\nasync def handle(msg: list[str], logger: Logger):\n    logger.info(msg)\n

In this example, the subscriber is configured to process messages in batches from the Redis stream, and the consuming function is designed to handle these batches efficiently.

Consuming messages in batches is a valuable technique when you need to optimize the processing of high volumes of data in your Redis-based applications. It allows for more efficient resource utilization and can enhance the overall performance of your data processing tasks.

","boost":10},{"location":"redis/streams/groups/","title":"Redis Stream Consumer Groups","text":"

Consuming messages from a Redis stream can be accomplished by using a Consumer Group. This allows multiple consumers to divide the workload of processing messages in a stream and provides a form of message acknowledgment, ensuring that messages are not processed repeatedly.

Consumer Groups in Redis enable a group of clients to cooperatively consume different portions of the same stream of messages. When using group=\"...\" (which internally uses XREADGROUP), messages are distributed among different consumers in a group and are not delivered to any other consumer in that group again, unless they are not acknowledged (i.e., the client fails to process and does not call msg.ack() or XACK). This is in contrast to a normal consumer (also known as XREAD), where every consumer sees all the messages. XREAD is useful for broadcasting to multiple consumers, while XREADGROUP is better suited for workload distribution.

In the following example, we will create a simple FastStream app that utilizes a Redis stream with a Consumer Group. It will consume messages sent to the \"test-stream\" as part of the \"test-group\" consumer group.

The full app code is as follows:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker, StreamSub\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(stream=StreamSub(\"test-stream\", group=\"test-group\", consumer=\"1\"))\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n\n\n@app.after_startup\nasync def t():\n    await broker.publish(\"Hi!\", stream=\"test-stream\")\n
","boost":10},{"location":"redis/streams/groups/#import-faststream-and-redisbroker","title":"Import FastStream and RedisBroker","text":"

First, import the FastStream class and the RedisBroker from the faststream.redis module to define our broker.

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker, StreamSub\n
","boost":10},{"location":"redis/streams/groups/#create-a-redisbroker","title":"Create a RedisBroker","text":"

To establish a connection to Redis, instantiate a RedisBroker object and pass it to the FastStream app.

broker = RedisBroker()\napp = FastStream(broker)\n
","boost":10},{"location":"redis/streams/groups/#define-a-consumer-group-subscription","title":"Define a Consumer Group Subscription","text":"

Define a subscription to a Redis stream with a specific Consumer Group using the StreamSub object and the @broker.subscriber(...) decorator. Then, define a function that will be triggered when new messages are sent to the \"test-stream\" Redis stream. This function is decorated with @broker.subscriber(...) and will process the messages as part of the \"test-group\" consumer group.

@broker.subscriber(stream=StreamSub(\"test-stream\", group=\"test-group\", consumer=\"1\"))\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/streams/groups/#publishing-a-message","title":"Publishing a message","text":"

Publishing a message is the same as what's defined on Stream Publishing.

await broker.publish(\"Hi!\", stream=\"test-stream\")\n

By following the steps and code examples provided above, you can create a FastStream application that consumes messages from a Redis stream using a Consumer Group for distributed message processing.

","boost":10},{"location":"redis/streams/publishing/","title":"Redis Stream Publishing with FastStream","text":"","boost":10},{"location":"redis/streams/publishing/#publishing-data-to-redis-stream","title":"Publishing Data to Redis Stream","text":"

To publish messages to a Redis Stream, you implement a function that processes the incoming data and applies the @broker.publisher(...) decorator along with the Redis stream name to it. The function will then publish its return value to the specified stream.

  1. Create your RedisBroker instance

    broker = RedisBroker(\"redis://localhost:6379\")\n
  2. Initiate your FastStream application with the RedisBroker

    app = FastStream(broker)\n
  3. Define your data model

    class Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n
  4. Set up the function for data processing and publishing

    Using the @broker.publisher(...) decorator in conjunction with the @broker.subscriber(...) decorator allows seamless message processing and republishing to a different stream.

    @broker.subscriber(stream=\"input-stream\")\n@broker.publisher(stream=\"output-stream\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n

    By decorating a function with @broker.publisher(...), we tell FastStream to publish the function's returned data to the designated \"output stream\". The defined function also serves as a subscriber to the \"input-stream\", thereby setting up a straightforward data pipeline within Redis streams.

Here's the complete example that showcases the use of decorators for both subscribing and publishing to Redis streams:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(stream=\"input-stream\")\n@broker.publisher(stream=\"output-stream\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
","boost":10},{"location":"redis/streams/subscription/","title":"Redis Stream Basic Subscriber","text":"

To start consuming from a Redis stream, simply decorate your consuming function with the @broker.subscriber(...) decorator, passing a string as the stream key.

In the following example, we will create a simple FastStream app that will consume messages from a \"test-stream\" Redis stream.

The full app code looks like this:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(stream=\"test-stream\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/streams/subscription/#import-faststream-and-redisbroker","title":"Import FastStream and RedisBroker","text":"

To use the @broker.subscriber(...) decorator, first, we need to import the base FastStream app and RedisBroker to create our broker.

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n
","boost":10},{"location":"redis/streams/subscription/#create-a-redisbroker","title":"Create a RedisBroker","text":"

Next, we will create a RedisBroker object and wrap it into the FastStream object so that we can start our app using CLI later.

broker = RedisBroker()\napp = FastStream(broker)\n
","boost":10},{"location":"redis/streams/subscription/#create-a-function-that-will-consume-messages-from-a-redis-stream","title":"Create a Function that will Consume Messages from a Redis stream","text":"

Let\u2019s create a consumer function that will consume messages from \"test-stream\" Redis stream and log them.

@broker.subscriber(stream=\"test-stream\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n

The function decorated with the @broker.subscriber(...) decorator will be called when a message is produced to the Redis stream.

The message will then be injected into the typed msg argument of the function, and its type will be used to parse the message.

In this example case, when the message is sent to a \"test-stream\" stream, it will be received by the handle function, and the logger will log the message content.

","boost":10}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-,:!=\\[\\]()\"`/]+|\\.(?!\\d)|&[lg]t;|(?!\\b)(?=[A-Z][a-z])","pipeline":["stopWordFilter"]},"docs":[{"location":"release/","title":"Release Notes","text":"","boost":2},{"location":"release/#039","title":"0.3.9","text":"","boost":2},{"location":"release/#whats-changed","title":"What's Changed","text":"","boost":2},{"location":"release/#bug-fixes","title":"Bug fixes:","text":"","boost":2},{"location":"release/#chore","title":"Chore:","text":"

Full Changelog: #0.3.8...0.3.9

","boost":2},{"location":"release/#038","title":"0.3.8","text":"","boost":2},{"location":"release/#whats-changed_1","title":"What's Changed","text":"

Full Changelog: #0.3.7...0.3.8

","boost":2},{"location":"release/#037","title":"0.3.7","text":"","boost":2},{"location":"release/#whats-changed_2","title":"What's Changed","text":"

Support regular FastStream Context with FastAPI plugin

from fastapi import FastAPI\nfrom faststream.redis.fastapi import RedisRouter, Logger\n\nrouter = RedisRouter()\n\n@router.subscriber(\"test\")\nasync def handler(msg, logger: Logger):\n    logger.info(msg)\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n

Full Changelog: #0.3.6...0.3.7

","boost":2},{"location":"release/#036","title":"0.3.6","text":"","boost":2},{"location":"release/#whats-changed_3","title":"What's Changed","text":"

Full Changelog: #0.3.5...0.3.6

","boost":2},{"location":"release/#035","title":"0.3.5","text":"","boost":2},{"location":"release/#whats-changed_4","title":"What's Changed","text":"

A large update by @Lancetnik in #1048

Provides with the ability to setup graceful_timeout to wait for consumed messages processed correctly before apllication shutdown - Broker(graceful_timeout=30.0) (waits up to 30 seconds)

Full Changelog: #0.3.4...0.3.5

","boost":2},{"location":"release/#034","title":"0.3.4","text":"","boost":2},{"location":"release/#whats-changed_5","title":"What's Changed","text":"","boost":2},{"location":"release/#features","title":"Features:","text":"","boost":2},{"location":"release/#documentation","title":"Documentation","text":"","boost":2},{"location":"release/#chore_1","title":"Chore","text":"

Full Changelog: #0.3.3...0.3.4

","boost":2},{"location":"release/#033","title":"0.3.3","text":"","boost":2},{"location":"release/#whats-changed_6","title":"What's Changed","text":"

Features:

Chores:

Full Changelog: #0.3.2...0.3.3

","boost":2},{"location":"release/#032","title":"0.3.2","text":"","boost":2},{"location":"release/#whats-changed_7","title":"What's Changed","text":"","boost":2},{"location":"release/#new-features","title":"New features:","text":"","boost":2},{"location":"release/#chore_2","title":"Chore:","text":"

Full Changelog: #0.3.1...0.3.2

","boost":2},{"location":"release/#031","title":"0.3.1","text":"","boost":2},{"location":"release/#whats-changed_8","title":"What's Changed","text":"

Features:

Bug fixes:

Documentation:

","boost":2},{"location":"release/#new-contributors","title":"New Contributors","text":"

Full Changelog: #0.3.0...0.3.1

","boost":2},{"location":"release/#030","title":"0.3.0","text":"","boost":2},{"location":"release/#whats-changed_9","title":"What's Changed","text":"

The main feature of the 0.3.0 release is added Redis support by @Lancetnik in #1003

You can install it by the following command:

pip install \"faststream[redis]\"\n

Here is a little code example

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n@broker.subscriber(\n    channel=\"test\",  # or\n    # list=\"test\",     or\n    # stream=\"test\",\n)\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":2},{"location":"release/#other-features","title":"Other features","text":"","boost":2},{"location":"release/#testing","title":"Testing","text":"","boost":2},{"location":"release/#documentation_1","title":"Documentation","text":"","boost":2},{"location":"release/#chore_3","title":"Chore","text":"","boost":2},{"location":"release/#new-contributors_1","title":"New Contributors","text":"

Full Changelog: #0.2.15...0.3.0

","boost":2},{"location":"release/#030rc0","title":"0.3.0rc0","text":"","boost":2},{"location":"release/#whats-changed_10","title":"What's Changed","text":"

The main feature of the 0.3.x release is added Redis support by @Lancetnik in #1003

You can install it manually:

pip install faststream==0.3.0rc0 && pip install \"faststream[redis]\"\n
","boost":2},{"location":"release/#other-features_1","title":"Other features","text":"","boost":2},{"location":"release/#testing_1","title":"Testing","text":"","boost":2},{"location":"release/#documentation_2","title":"Documentation","text":"","boost":2},{"location":"release/#chore_4","title":"Chore","text":"","boost":2},{"location":"release/#new-contributors_2","title":"New Contributors","text":"

Full Changelog: #0.2.15...0.3.0rc0

","boost":2},{"location":"release/#0215","title":"0.2.15","text":"","boost":2},{"location":"release/#whats-changed_11","title":"What's Changed","text":"","boost":2},{"location":"release/#bug-fixes_1","title":"Bug fixes","text":"","boost":2},{"location":"release/#documentation_3","title":"Documentation","text":"","boost":2},{"location":"release/#misc","title":"Misc","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.14...0.2.15

","boost":2},{"location":"release/#0214","title":"0.2.14","text":"","boost":2},{"location":"release/#whats-changed_12","title":"What's Changed","text":"","boost":2},{"location":"release/#bug-fixes_2","title":"Bug fixes","text":"","boost":2},{"location":"release/#documentation_4","title":"Documentation","text":"","boost":2},{"location":"release/#misc_1","title":"Misc","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.13...0.2.14

","boost":2},{"location":"release/#0213","title":"0.2.13","text":"","boost":2},{"location":"release/#whats-changed_13","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.12...0.2.13

","boost":2},{"location":"release/#0212","title":"0.2.12","text":"","boost":2},{"location":"release/#whats-changed_14","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.11...0.2.12

","boost":2},{"location":"release/#0211","title":"0.2.11","text":"","boost":2},{"location":"release/#whats-changed_15","title":"What's Changed","text":"","boost":2},{"location":"release/#bug-fixes_3","title":"Bug fixes","text":"","boost":2},{"location":"release/#documentation_5","title":"Documentation","text":"","boost":2},{"location":"release/#new-contributors_3","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.10...0.2.11

","boost":2},{"location":"release/#documentation_6","title":"Documentation","text":"","boost":2},{"location":"release/#new-contributors_4","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.10...0.2.11

","boost":2},{"location":"release/#0210","title":"0.2.10","text":"","boost":2},{"location":"release/#whats-changed_16","title":"What's Changed","text":"

Now, you can hide your connection secrets in the AsyncAPI schema by manually setting up the server URL:

broker = RabbitBroker(\n    \"amqp://guest:guest@localhost:5672/\",  # Connection URL\n    asyncapi_url=\"amqp://****:****@localhost:5672/\",  # Public schema URL\n)\n

Additionally, the RabbitMQ AsyncAPI schema has been improved, adding support for faststream.security, and the connection scheme is now defined automatically.

RabbitMQ connection parameters are now merged, allowing you to define the main connection data as a URL string and customize it using kwargs:

broker = RabbitBroker(\n    \"amqp://guest:guest@localhost:5672/\",\n    host=\"127.0.0.1\",\n)\n\n# amqp://guest:guest@127.0.0.1:5672/ - The final URL\n
* A more suitable faststream.security import instead of faststream.broker.security * chore: add release notes for 0.2.9 by @kumaranvpl in https://github.com/airtai/faststream/pull/894 * chore: upgrade packages by @davorrunje in https://github.com/airtai/faststream/pull/901 * chore: use js redirect and redirect to version by @kumaranvpl in https://github.com/airtai/faststream/pull/902 * feat: add asyncapi_url broker arg by @Lancetnik in https://github.com/airtai/faststream/pull/903

Full Changelog: https://github.com/airtai/faststream/compare/0.2.9...0.2.10

","boost":2},{"location":"release/#029","title":"0.2.9","text":"","boost":2},{"location":"release/#whats-changed_17","title":"What's Changed","text":"","boost":2},{"location":"release/#new-contributors_5","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.8...0.2.9

","boost":2},{"location":"release/#028","title":"0.2.8","text":"","boost":2},{"location":"release/#whats-changed_18","title":"What's Changed","text":"","boost":2},{"location":"release/#new-contributors_6","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.7...0.2.8

","boost":2},{"location":"release/#027","title":"0.2.7","text":"","boost":2},{"location":"release/#whats-changed_19","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.6...0.2.7

","boost":2},{"location":"release/#026","title":"0.2.6","text":"","boost":2},{"location":"release/#whats-changed_20","title":"What's Changed","text":"","boost":2},{"location":"release/#new-contributors_7","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.5...0.2.6

","boost":2},{"location":"release/#025","title":"0.2.5","text":"","boost":2},{"location":"release/#whats-changed_21","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.4...0.2.5

","boost":2},{"location":"release/#024","title":"0.2.4","text":"","boost":2},{"location":"release/#new-functionalities","title":"New Functionalities","text":"

Now, Context provides access to inner dict keys too:

# headers is a `dict`\nasync def handler(\n  user_id: int = Context(\"message.headers.user_id\", cast=True),\n): ...\n

Added Header object as a shortcut to Context(\"message.headers.\") inner fields (NATS example):

# the same with the previous example\nasync def handler(\n  user_id: int = Header(),\n  u_id: int = Header(\"user_id\"),  # with custom name\n): ...\n

Added Path object to get access to NATS wildcard subject or RabbitMQ topic routing key (a shortcut to access Context(\"message.path.\") as well):

@nats_broker.subscriber(\"logs.{level}\")\nasync def handler(\n  level: str = Path(),\n)\n

Also, the original message Context annotation was copied from faststream.[broker].annotations.[Broker]Message to faststream.[broker].[Broker]Message to provide you with faster access to the most commonly used object (NATS example).

","boost":2},{"location":"release/#whats-changed_22","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.3...0.2.4

","boost":2},{"location":"release/#023","title":"0.2.3","text":"","boost":2},{"location":"release/#whats-changed_23","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.2...0.2.3

","boost":2},{"location":"release/#022","title":"0.2.2","text":"","boost":2},{"location":"release/#whats-changed_24","title":"What's Changed","text":"","boost":2},{"location":"release/#new-contributors_8","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.1...0.2.2

","boost":2},{"location":"release/#021","title":"0.2.1","text":"","boost":2},{"location":"release/#whats-changed_25","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.0...0.2.1

","boost":2},{"location":"release/#020","title":"0.2.0","text":"","boost":2},{"location":"release/#whats-changed_26","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.1.6...0.2.0

","boost":2},{"location":"release/#016","title":"0.1.6","text":"","boost":2},{"location":"release/#whats-changed_27","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.1.5...0.1.6

","boost":2},{"location":"release/#014","title":"0.1.4","text":"","boost":2},{"location":"release/#whats-changed_28","title":"What's Changed","text":"","boost":2},{"location":"release/#new-contributors_9","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.1.3...0.1.4

","boost":2},{"location":"release/#013","title":"0.1.3","text":"","boost":2},{"location":"release/#whats-changed_29","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.1.1...0.1.3

","boost":2},{"location":"release/#011","title":"0.1.1","text":"","boost":2},{"location":"release/#whats-changed_30","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/commits/0.1.1

","boost":2},{"location":"release/#010","title":"0.1.0","text":"

FastStream is a new package based on the ideas and experiences gained from FastKafka and Propan. By joining our forces, we picked up the best from both packages and created the unified way to write services capable of processing streamed data regardless of the underlying protocol. We'll continue to maintain both packages, but new development will be in this project. If you are starting a new service, this package is the recommended way to do it.

","boost":2},{"location":"release/#features_1","title":"Features","text":"

FastStream simplifies the process of writing producers and consumers for message queues, handling all the parsing, networking and documentation generation automatically.

Making streaming microservices has never been easier. Designed with junior developers in mind, FastStream simplifies your work while keeping the door open for more advanced use-cases. Here's a look at the core features that make FastStream a go-to framework for modern, data-centric microservices.

That's FastStream in a nutshell\u2014easy, efficient, and powerful. Whether you're just starting with streaming microservices or looking to scale, FastStream has got you covered.

","boost":2},{"location":"scheduling/","title":"Tasks Scheduling","text":"

FastStream is a framework for asynchronous service development. It allows you to build disturbed event-based systems in an easy way. Tasks scheduling is a pretty often usecase in such systems.

Unfortunatelly, this functional conflicts with the original FastStream ideology and can't be implemented as a part of the framework. But, you can integrate scheduling in your FastStream application by using some extra dependencies. And we have some reciepts how to make it.

","boost":10},{"location":"scheduling/#taskiq-faststream","title":"Taskiq-FastStream","text":"

Taskiq is an asynchronous distributed task queue for python. This project takes inspiration from big projects such as Celery and Dramatiq.

As a Celery replacement, Taskiq should support tasks sheduling and delayied publishing, of course. And it does!

By the way, you can easely integrate FastStream with the Taskiq. It allows you to create cron or delayied tasks to publish messages and trigger some functions this way.

We have a helpful project to provide you with this feature - Taskiq-FastStream.

You can install it by the following command

pip install taskiq-faststream\n

It has two hepfull classes BrokerWrapper and AppWrapper to make your FastStream App and Broker objects taskiq-compatible.

Let's take a look at the code example.

At first, we should create a regular FastStream application.

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-topic\")\n@broker.publisher(\"out-topic\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-queue\")\n@broker.publisher(\"out-queue\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-subject\")\n@broker.publisher(\"out-subject\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-channel\")\n@broker.publisher(\"out-channel\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n
","boost":10},{"location":"scheduling/#broker-wrapper","title":"Broker Wrapper","text":"

Now, if you want to make it just working, we should wrap our Broker to special BrokerWrapper object:

from taskiq_faststream import BrokerWrapper\n\ntaskiq_broker = BrokerWrapper(broker)\n

It creates a taskiq-compatible object, that can be used as an object to create a regular taskiq scheduler.

KafkaRabbitMQNATSRedis
from taskiq_faststream import StreamScheduler\nfrom taskiq.schedule_sources import LabelScheduleSource\n\ntaskiq_broker.task(\n    message={\"user\": \"John\", \"user_id\": 1},\n    topic=\"in-topic\",\n    schedule=[{\n        \"cron\": \"* * * * *\",\n    }],\n)\n\nscheduler = StreamScheduler(\n    broker=taskiq_broker,\n    sources=[LabelScheduleSource(taskiq_broker)],\n)\n
from taskiq_faststream import StreamScheduler\nfrom taskiq.schedule_sources import LabelScheduleSource\n\ntaskiq_broker.task(\n    message={\"user\": \"John\", \"user_id\": 1},\n    queue=\"in-queue\",\n    schedule=[{\n        \"cron\": \"* * * * *\",\n    }],\n)\n\nscheduler = StreamScheduler(\n    broker=taskiq_broker,\n    sources=[LabelScheduleSource(taskiq_broker)],\n)\n
from taskiq_faststream import StreamScheduler\nfrom taskiq.schedule_sources import LabelScheduleSource\n\ntaskiq_broker.task(\n    message={\"user\": \"John\", \"user_id\": 1},\n    subject=\"in-subject\",\n    schedule=[{\n        \"cron\": \"* * * * *\",\n    }],\n)\n\nscheduler = StreamScheduler(\n    broker=taskiq_broker,\n    sources=[LabelScheduleSource(taskiq_broker)],\n)\n
from taskiq_faststream import StreamScheduler\nfrom taskiq.schedule_sources import LabelScheduleSource\n\ntaskiq_broker.task(\n    message={\"user\": \"John\", \"user_id\": 1},\n    channel=\"in-channel\",\n    schedule=[{\n        \"cron\": \"* * * * *\",\n    }],\n)\n\nscheduler = StreamScheduler(\n    broker=taskiq_broker,\n    sources=[LabelScheduleSource(taskiq_broker)],\n)\n

We patched the original TaskiqScheduler to support message generation callbacks, but its signature remains the same.

broker.task(...) has the same with the original broker.publish(...) signature and allows you to plan your publishing tasks usign the great taskiq schedule option (you can learn more about it here).

Finally, to run the scheduler, please use the taskiq CLI command:

taskiq scheduler module:scheduler\n
","boost":10},{"location":"scheduling/#application-wrapper","title":"Application Wrapper","text":"

If you don't wont to lost application AsyncAPI schema or/and lifespans, you can wrap not the broker, but application by itself using AppWrapper class.

from taskiq_faststream import AppWrapper\n\ntaskiq_broker = AppWrapper(app)\n

It allows you to use taskiq_broker the same way with the previous example, but saves all original FastStream features.

Tip

Creating a separated Scheduler service is a best way to make really disturbed and susteinable system. In this case, you can just create an empty FastStream broker and use Taskiq-FastStream integration to publish your messages (consuming by another services).

","boost":10},{"location":"scheduling/#generate-message-payload","title":"Generate message payload","text":"

Also, you able to determine message payload right before sending and do not use the final one. To make it, just replace message option from the final value to function (sync or async), that returns data to send:

async def collect_information_to_send():\n    return \"Message to send\"\n\ntaskiq_broker.task(\n    message=collect_information_to_send,\n    ...\n)\n

It allows you to collect some data from database, request an outer API, or use another ways to generate data to send right before sending.

More than, you can send not one, but multiple messages per one task using this feature. Just turn your message callback function to generator (sync or async) - and Taskiq-FastStream will iterates over your payload and publishes all of your messages!

async def collect_information_to_send():\n    \"\"\"Publish 10 messages per task call.\"\"\"\n    for i in range(10):\n        yield i\n\ntaskiq_broker.task(\n    message=collect_information_to_send,\n    ...\n)\n
","boost":10},{"location":"scheduling/#rocketry","title":"Rocketry","text":"

Also, you can integrate your FastStream application with any other libraries provides you with a scheduling functional.

As an example, you can use Rocketry:

import asyncio\n\nfrom rocketry import Rocketry\nfrom rocketry.args import Arg\n\nfrom faststream.nats import NatsBroker\n\napp = Rocketry(execution=\"async\")\n\nbroker = NatsBroker()      # regular broker\napp.params(broker=broker)\n\nasync def start_app():\n    async with broker:     # connect broker\n        await app.serve()  # run rocketry\n\n@app.task(\"every 1 second\", execution=\"async\")\nasync def publish(br: NatsBroker = Arg(\"broker\")):\n    await br.publish(\"Hi, Rocketry!\", \"test\")\n\nif __name__ == \"__main__\":\n    asyncio.run(start_app())\n
","boost":10},{"location":"api/","title":"Reference - Code API","text":"

Here's the reference or code API, the classes, functions, parameters, attributes, and all the FastAPI parts you can use in your applications.

If you want to learn FastStream you are much better off reading the FastStream Tutorial.

"},{"location":"api/faststream/BaseMiddleware/","title":"BaseMiddleware","text":"","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware","title":"faststream.BaseMiddleware","text":"
BaseMiddleware(msg: Any)\n

A base middleware class.

METHOD DESCRIPTION on_receive

Called when a message is received.

after_processed

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) -> Optional[bool]: Called after processing a message.

__aenter__

Called when entering a context.

__aexit__

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) -> Optional[bool]: Called when exiting a context.

on_consume

DecodedMessage) -> DecodedMessage: Called before consuming a message.

after_consume

Optional[Exception]) -> None: Called after consuming a message.

consume_scope

DecodedMessage) -> AsyncIterator[DecodedMessage]: Context manager for consuming a message.

on_publish

SendableMessage) -> SendableMessage: Called before publishing a message.

after_publish

Optional[Exception]) -> None: Asynchronous function to handle the after publish event.

Initialize the class.

PARAMETER DESCRIPTION msg

Any message to be stored.

TYPE: Any

Source code in faststream/broker/middlewares.py
def __init__(self, msg: Any) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        msg: Any message to be stored.\n    \"\"\"\n    self.msg = msg\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.msg","title":"msg instance-attribute","text":"
msg = msg\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.after_consume","title":"after_consume async","text":"
after_consume(err: Optional[Exception]) -> None\n

A function to handle the result of consuming a resource asynchronously.

PARAMETER DESCRIPTION err

Optional exception that occurred during consumption

RAISES DESCRIPTION err

If an exception occurred during consumption

Source code in faststream/broker/middlewares.py
async def after_consume(self, err: Optional[Exception]) -> None:\n    \"\"\"A function to handle the result of consuming a resource asynchronously.\n\n    Args:\n        err : Optional exception that occurred during consumption\n\n    Raises:\n        err : If an exception occurred during consumption\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.after_processed","title":"after_processed async","text":"
after_processed(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> Optional[bool]\n

Asynchronously called after processing.

PARAMETER DESCRIPTION exc_type

Optional exception type

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

Optional exception value

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

Optional traceback

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION Optional[bool]

Optional boolean value indicating whether the processing was successful or not.

Source code in faststream/broker/middlewares.py
async def after_processed(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> Optional[bool]:\n    \"\"\"Asynchronously called after processing.\n\n    Args:\n        exc_type: Optional exception type\n        exc_val: Optional exception value\n        exec_tb: Optional traceback\n\n    Returns:\n        Optional boolean value indicating whether the processing was successful or not.\n    \"\"\"\n    return False\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.after_publish","title":"after_publish async","text":"
after_publish(err: Optional[Exception]) -> None\n

Asynchronous function to handle the after publish event.

PARAMETER DESCRIPTION err

Optional exception that occurred during the publish

TYPE: Optional[Exception]

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION Exception

If an error occurred during the publish

Source code in faststream/broker/middlewares.py
async def after_publish(self, err: Optional[Exception]) -> None:\n    \"\"\"Asynchronous function to handle the after publish event.\n\n    Args:\n        err: Optional exception that occurred during the publish\n\n    Returns:\n        None\n\n    Raises:\n        Exception: If an error occurred during the publish\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.consume_scope","title":"consume_scope async","text":"
consume_scope(\n    msg: DecodedMessage,\n) -> AsyncIterator[DecodedMessage]\n

Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.

PARAMETER DESCRIPTION msg

The decoded message to consume.

TYPE: DecodedMessage

YIELDS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RETURNS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RAISES DESCRIPTION Exception

If an error occurs while consuming the message.

AsyncIterator

An asynchronous iterator that yields decoded messages.

Note

This function is an async function.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def consume_scope(self, msg: DecodedMessage) -> AsyncIterator[DecodedMessage]:\n    \"\"\"Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.\n\n    Args:\n        msg: The decoded message to consume.\n\n    Yields:\n        An asynchronous iterator of decoded messages.\n\n    Returns:\n        An asynchronous iterator of decoded messages.\n\n    Raises:\n        Exception: If an error occurs while consuming the message.\n\n    AsyncIterator:\n        An asynchronous iterator that yields decoded messages.\n\n    Note:\n        This function is an async function.\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_consume(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_consume(err)\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.on_consume","title":"on_consume async","text":"
on_consume(msg: DecodedMessage) -> DecodedMessage\n

Asynchronously consumes a message.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: DecodedMessage

RETURNS DESCRIPTION DecodedMessage

The consumed message.

Source code in faststream/broker/middlewares.py
async def on_consume(self, msg: DecodedMessage) -> DecodedMessage:\n    \"\"\"Asynchronously consumes a message.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The consumed message.\n    \"\"\"\n    return msg\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.on_publish","title":"on_publish async","text":"
on_publish(msg: SendableMessage) -> SendableMessage\n

Asynchronously handle a publish event.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

RETURNS DESCRIPTION SendableMessage

The published message.

Source code in faststream/broker/middlewares.py
async def on_publish(self, msg: SendableMessage) -> SendableMessage:\n    \"\"\"Asynchronously handle a publish event.\n\n    Args:\n        msg: The message to be published.\n\n    Returns:\n        The published message.\n    \"\"\"\n    return msg\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.on_receive","title":"on_receive async","text":"
on_receive() -> None\n
Source code in faststream/broker/middlewares.py
async def on_receive(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.publish_scope","title":"publish_scope async","text":"
publish_scope(\n    msg: SendableMessage,\n) -> AsyncIterator[SendableMessage]\n

Publish a message and return an async iterator.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

YIELDS DESCRIPTION AsyncIterator[SendableMessage]

A sendable message.

RETURNS DESCRIPTION AsyncIterator[SendableMessage]

An async iterator of sendable messages.

RAISES DESCRIPTION Exception

If an error occurs during publishing.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def publish_scope(\n    self, msg: SendableMessage\n) -> AsyncIterator[SendableMessage]:\n    \"\"\"Publish a message and return an async iterator.\n\n    Args:\n        msg: The message to be published.\n\n    Yields:\n        A sendable message.\n\n    Returns:\n        An async iterator of sendable messages.\n\n    Raises:\n        Exception: If an error occurs during publishing.\n\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_publish(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_publish(err)\n
","boost":0.5},{"location":"api/faststream/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/Context/#faststream.Context","title":"faststream.Context","text":"
Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n    )\n
","boost":0.5},{"location":"api/faststream/Depends/","title":"Depends","text":"","boost":0.5},{"location":"api/faststream/Depends/#fast_depends.use.Depends","title":"fast_depends.use.Depends","text":"
Depends(\n    dependency: Callable[P, T],\n    *,\n    use_cache: bool = True,\n    cast: bool = True\n) -> Any\n
Source code in fast_depends/use.py
def Depends(\n    dependency: Callable[P, T],\n    *,\n    use_cache: bool = True,\n    cast: bool = True,\n) -> Any:\n    return model.Depends(\n        dependency=dependency,\n        use_cache=use_cache,\n        cast=cast,\n    )\n
","boost":0.5},{"location":"api/faststream/FastStream/","title":"FastStream","text":"","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream","title":"faststream.FastStream","text":"
FastStream(\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    lifespan: Optional[Lifespan] = None,\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[\n        Union[License, LicenseDict, AnyDict]\n    ] = None,\n    contact: Optional[\n        Union[Contact, ContactDict, AnyDict]\n    ] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[\n        Sequence[Union[Tag, TagDict, AnyDict]]\n    ] = None,\n    external_docs: Optional[\n        Union[ExternalDocs, ExternalDocsDict, AnyDict]\n    ] = None,\n)\n

Bases: ABCApp

A class representing a FastStream application.

METHOD DESCRIPTION __init__

initializes the FastStream application

on_startup

adds a hook to run before the broker is connected

on_shutdown

adds a hook to run before the broker is disconnected

after_startup

adds a hook to run after the broker is connected

after_shutdown

adds a hook to run after the broker is disconnected

run

runs the FastStream application

_init_async_cycle

initializes the async cycle

_start

starts the FastStream application

_stop

stops the FastStream application

_startup

runs the startup hooks

_shutdown

runs the shutdown hooks

__exit

exits the FastStream application

Asyncronous FastStream Application class

stores and run broker, control hooks

PARAMETER DESCRIPTION broker

async broker to run (may be None, then specify by set_broker)

TYPE: Optional[BrokerAsyncUsecase[Any, Any]] DEFAULT: None

logger

logger object to log startup/shutdown messages (None to disable)

TYPE: Optional[Logger] DEFAULT: logger

title

application title - for AsyncAPI docs

TYPE: str DEFAULT: 'FastStream'

version

application version - for AsyncAPI docs

TYPE: str DEFAULT: '0.1.0'

description

application description - for AsyncAPI docs

TYPE: str DEFAULT: ''

Source code in faststream/app.py
def __init__(\n    self,\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    lifespan: Optional[Lifespan] = None,\n    # AsyncAPI args,\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[Union[License, LicenseDict, AnyDict]] = None,\n    contact: Optional[Union[Contact, ContactDict, AnyDict]] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[Sequence[Union[Tag, TagDict, AnyDict]]] = None,\n    external_docs: Optional[Union[ExternalDocs, ExternalDocsDict, AnyDict]] = None,\n) -> None:\n    \"\"\"Asyncronous FastStream Application class\n\n    stores and run broker, control hooks\n\n    Args:\n        broker: async broker to run (may be `None`, then specify by `set_broker`)\n        logger: logger object to log startup/shutdown messages (`None` to disable)\n        title: application title - for AsyncAPI docs\n        version: application version - for AsyncAPI docs\n        description: application description - for AsyncAPI docs\n    \"\"\"\n    super().__init__(\n        broker=broker,\n        logger=logger,\n        title=title,\n        version=version,\n        description=description,\n        terms_of_service=terms_of_service,\n        license=license,\n        contact=contact,\n        identifier=identifier,\n        tags=tags,\n        external_docs=external_docs,\n    )\n\n    self._stop_event = None\n\n    self.lifespan_context = (\n        apply_types(\n            func=lifespan,\n            wrap_model=drop_response_type,\n        )\n        if lifespan is not None\n        else fake_context\n    )\n\n    set_exit(lambda *_: self.__exit())\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = tags\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.contact","title":"contact instance-attribute","text":"
contact = contact\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.context","title":"context instance-attribute","text":"
context = context\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.external_docs","title":"external_docs instance-attribute","text":"
external_docs = external_docs\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.identifier","title":"identifier instance-attribute","text":"
identifier = identifier\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.license","title":"license instance-attribute","text":"
license = license\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context = (\n    apply_types(\n        func=lifespan, wrap_model=drop_response_type\n    )\n    if lifespan is not None\n    else fake_context\n)\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = terms_of_service\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.title","title":"title instance-attribute","text":"
title = title\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.version","title":"version instance-attribute","text":"
version = version\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.after_shutdown","title":"after_shutdown","text":"
after_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker disconnected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def after_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker disconnected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().after_shutdown(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.after_startup","title":"after_startup","text":"
after_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker connected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def after_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker connected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().after_startup(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.on_shutdown","title":"on_shutdown","text":"
on_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker disconnected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def on_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker disconnected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().on_shutdown(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.on_startup","title":"on_startup","text":"
on_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker connected

This hook also takes an extra CLI options as a kwargs

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def on_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker connected\n\n    This hook also takes an extra CLI options as a kwargs\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().on_startup(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.run","title":"run async","text":"
run(\n    log_level: int = logging.INFO,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n) -> None\n

Run FastStream Application

PARAMETER DESCRIPTION log_level

force application log level

TYPE: int DEFAULT: INFO

RETURNS DESCRIPTION None

Block an event loop until stopped

Source code in faststream/app.py
async def run(\n    self,\n    log_level: int = logging.INFO,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Run FastStream Application\n\n    Args:\n        log_level: force application log level\n\n    Returns:\n        Block an event loop until stopped\n    \"\"\"\n    assert self.broker, \"You should setup a broker\"  # nosec B101\n\n    self._init_async_cycle()\n    async with self.lifespan_context(**(run_extra_options or {})):\n        try:\n            async with anyio.create_task_group() as tg:\n                tg.start_soon(self._start, log_level, run_extra_options)\n                await self._stop(log_level)\n                tg.cancel_scope.cancel()\n        except ExceptionGroup as e:\n            for ex in e.exceptions:\n                raise ex from None\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.set_broker","title":"set_broker","text":"
set_broker(broker: BrokerAsyncUsecase[Any, Any]) -> None\n

Set already existed App object broker Usefull then you create/init broker in on_startup hook

Source code in faststream/app.py
def set_broker(self, broker: BrokerAsyncUsecase[Any, Any]) -> None:\n    \"\"\"Set already existed App object broker\n    Usefull then you create/init broker in `on_startup` hook\"\"\"\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/Header/","title":"Header","text":"","boost":0.5},{"location":"api/faststream/Header/#faststream.Header","title":"faststream.Header","text":"
Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.headers.\",\n    )\n
","boost":0.5},{"location":"api/faststream/Path/","title":"Path","text":"","boost":0.5},{"location":"api/faststream/Path/#faststream.Path","title":"faststream.Path","text":"
Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.path.\",\n    )\n
","boost":0.5},{"location":"api/faststream/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/TestApp/#faststream.TestApp","title":"faststream.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/TestApp/#faststream.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/apply_types/","title":"apply_types","text":"","boost":0.5},{"location":"api/faststream/apply_types/#fast_depends.use.inject","title":"fast_depends.use.inject","text":"
inject(\n    func: Optional[Callable[P, T]] = None,\n    *,\n    cast: bool = True,\n    extra_dependencies: Sequence[model.Depends] = (),\n    pydantic_config: Optional[ConfigDict] = None,\n    dependency_overrides_provider: Optional[\n        Any\n    ] = dependency_provider,\n    wrap_model: Callable[\n        [CallModel[P, T]], CallModel[P, T]\n    ] = lambda: x\n) -> Union[Callable[P, T], _InjectWrapper[P, T]]\n
Source code in fast_depends/use.py
def inject(\n    func: Optional[Callable[P, T]] = None,\n    *,\n    cast: bool = True,\n    extra_dependencies: Sequence[model.Depends] = (),\n    pydantic_config: Optional[ConfigDict] = None,\n    dependency_overrides_provider: Optional[Any] = dependency_provider,\n    wrap_model: Callable[[CallModel[P, T]], CallModel[P, T]] = lambda x: x,\n) -> Union[Callable[P, T], _InjectWrapper[P, T],]:\n    decorator = _wrap_inject(\n        dependency_overrides_provider=dependency_overrides_provider,\n        wrap_model=wrap_model,\n        extra_dependencies=extra_dependencies,\n        cast=cast,\n        pydantic_config=pydantic_config,\n    )\n\n    if func is None:\n        return decorator\n\n    else:\n        return decorator(func)\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/","title":"ABCApp","text":"","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp","title":"faststream.app.ABCApp","text":"
ABCApp(\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[\n        Union[License, LicenseDict, AnyDict]\n    ] = None,\n    contact: Optional[\n        Union[Contact, ContactDict, AnyDict]\n    ] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[\n        Sequence[Union[Tag, TagDict, AnyDict]]\n    ] = None,\n    external_docs: Optional[\n        Union[ExternalDocs, ExternalDocsDict, AnyDict]\n    ] = None,\n)\n

Bases: ABC

A class representing an ABC App.

METHOD DESCRIPTION set_broker

Set the broker object

on_startup

Add a hook to be run before the broker is connected

on_shutdown

Add a hook to be run before the broker is disconnected

after_startup

Add a hook to be run after the broker is connected

after_shutdown

Add a hook to be run after the broker is disconnected

_log

Log a message at a specified

Initialize an instance of the class.

PARAMETER DESCRIPTION broker

An optional instance of the BrokerAsyncUsecase class.

TYPE: Optional[BrokerAsyncUsecase[Any, Any]] DEFAULT: None

logger

An optional instance of the logging.Logger class.

TYPE: Optional[Logger] DEFAULT: logger

title

A string representing the title of the AsyncAPI.

TYPE: str DEFAULT: 'FastStream'

version

A string representing the version of the AsyncAPI.

TYPE: str DEFAULT: '0.1.0'

description

A string representing the description of the AsyncAPI.

TYPE: str DEFAULT: ''

terms_of_service

An optional URL representing the terms of service of the AsyncAPI.

TYPE: Optional[AnyHttpUrl] DEFAULT: None

license

An optional instance of the License class.

TYPE: Optional[Union[License, LicenseDict, AnyDict]] DEFAULT: None

contact

An optional instance of the Contact class.

TYPE: Optional[Union[Contact, ContactDict, AnyDict]] DEFAULT: None

identifier

An optional string representing the identifier of the AsyncAPI.

TYPE: Optional[str] DEFAULT: None

tags

An optional sequence of Tag instances.

TYPE: Optional[Sequence[Union[Tag, TagDict, AnyDict]]] DEFAULT: None

external_docs

An optional instance of the ExternalDocs class.

TYPE: Optional[Union[ExternalDocs, ExternalDocsDict, AnyDict]] DEFAULT: None

Source code in faststream/app.py
def __init__(\n    self,\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    # AsyncAPI information\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[Union[License, LicenseDict, AnyDict]] = None,\n    contact: Optional[Union[Contact, ContactDict, AnyDict]] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[Sequence[Union[Tag, TagDict, AnyDict]]] = None,\n    external_docs: Optional[Union[ExternalDocs, ExternalDocsDict, AnyDict]] = None,\n) -> None:\n    \"\"\"Initialize an instance of the class.\n\n    Args:\n        broker: An optional instance of the BrokerAsyncUsecase class.\n        logger: An optional instance of the logging.Logger class.\n        title: A string representing the title of the AsyncAPI.\n        version: A string representing the version of the AsyncAPI.\n        description: A string representing the description of the AsyncAPI.\n        terms_of_service: An optional URL representing the terms of service of the AsyncAPI.\n        license: An optional instance of the License class.\n        contact: An optional instance of the Contact class.\n        identifier: An optional string representing the identifier of the AsyncAPI.\n        tags: An optional sequence of Tag instances.\n        external_docs: An optional instance of the ExternalDocs class.\n    \"\"\"\n    self.broker = broker\n    self.logger = logger\n    self.context = context\n    context.set_global(\"app\", self)\n\n    self._on_startup_calling = []\n    self._after_startup_calling = []\n    self._on_shutdown_calling = []\n    self._after_shutdown_calling = []\n\n    # AsyncAPI information\n    self.title = title\n    self.version = version\n    self.description = description\n    self.terms_of_service = terms_of_service\n    self.license = license\n    self.contact = contact\n    self.identifier = identifier\n    self.asyncapi_tags = tags\n    self.external_docs = external_docs\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = tags\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.contact","title":"contact instance-attribute","text":"
contact = contact\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.context","title":"context instance-attribute","text":"
context = context\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.external_docs","title":"external_docs instance-attribute","text":"
external_docs = external_docs\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.identifier","title":"identifier instance-attribute","text":"
identifier = identifier\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.license","title":"license instance-attribute","text":"
license = license\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = terms_of_service\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.title","title":"title instance-attribute","text":"
title = title\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.version","title":"version instance-attribute","text":"
version = version\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.after_shutdown","title":"after_shutdown","text":"
after_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker disconnected

Source code in faststream/app.py
def after_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker disconnected\"\"\"\n    self._after_shutdown_calling.append(apply_types(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.after_startup","title":"after_startup","text":"
after_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker connected

Source code in faststream/app.py
def after_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker connected\"\"\"\n    self._after_startup_calling.append(apply_types(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.on_shutdown","title":"on_shutdown","text":"
on_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker disconnected

Source code in faststream/app.py
def on_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker disconnected\"\"\"\n    self._on_shutdown_calling.append(apply_types(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.on_startup","title":"on_startup","text":"
on_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker connected This hook also takes an extra CLI options as a kwargs

Source code in faststream/app.py
def on_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker connected\n    This hook also takes an extra CLI options as a kwargs\"\"\"\n    self._on_startup_calling.append(apply_types(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.set_broker","title":"set_broker","text":"
set_broker(broker: BrokerAsyncUsecase[Any, Any]) -> None\n

Set already existed App object broker Usefull then you create/init broker in on_startup hook

Source code in faststream/app.py
def set_broker(self, broker: BrokerAsyncUsecase[Any, Any]) -> None:\n    \"\"\"Set already existed App object broker\n    Usefull then you create/init broker in `on_startup` hook\"\"\"\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/app/FastStream/","title":"FastStream","text":"","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream","title":"faststream.app.FastStream","text":"
FastStream(\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    lifespan: Optional[Lifespan] = None,\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[\n        Union[License, LicenseDict, AnyDict]\n    ] = None,\n    contact: Optional[\n        Union[Contact, ContactDict, AnyDict]\n    ] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[\n        Sequence[Union[Tag, TagDict, AnyDict]]\n    ] = None,\n    external_docs: Optional[\n        Union[ExternalDocs, ExternalDocsDict, AnyDict]\n    ] = None,\n)\n

Bases: ABCApp

A class representing a FastStream application.

METHOD DESCRIPTION __init__

initializes the FastStream application

on_startup

adds a hook to run before the broker is connected

on_shutdown

adds a hook to run before the broker is disconnected

after_startup

adds a hook to run after the broker is connected

after_shutdown

adds a hook to run after the broker is disconnected

run

runs the FastStream application

_init_async_cycle

initializes the async cycle

_start

starts the FastStream application

_stop

stops the FastStream application

_startup

runs the startup hooks

_shutdown

runs the shutdown hooks

__exit

exits the FastStream application

Asyncronous FastStream Application class

stores and run broker, control hooks

PARAMETER DESCRIPTION broker

async broker to run (may be None, then specify by set_broker)

TYPE: Optional[BrokerAsyncUsecase[Any, Any]] DEFAULT: None

logger

logger object to log startup/shutdown messages (None to disable)

TYPE: Optional[Logger] DEFAULT: logger

title

application title - for AsyncAPI docs

TYPE: str DEFAULT: 'FastStream'

version

application version - for AsyncAPI docs

TYPE: str DEFAULT: '0.1.0'

description

application description - for AsyncAPI docs

TYPE: str DEFAULT: ''

Source code in faststream/app.py
def __init__(\n    self,\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    lifespan: Optional[Lifespan] = None,\n    # AsyncAPI args,\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[Union[License, LicenseDict, AnyDict]] = None,\n    contact: Optional[Union[Contact, ContactDict, AnyDict]] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[Sequence[Union[Tag, TagDict, AnyDict]]] = None,\n    external_docs: Optional[Union[ExternalDocs, ExternalDocsDict, AnyDict]] = None,\n) -> None:\n    \"\"\"Asyncronous FastStream Application class\n\n    stores and run broker, control hooks\n\n    Args:\n        broker: async broker to run (may be `None`, then specify by `set_broker`)\n        logger: logger object to log startup/shutdown messages (`None` to disable)\n        title: application title - for AsyncAPI docs\n        version: application version - for AsyncAPI docs\n        description: application description - for AsyncAPI docs\n    \"\"\"\n    super().__init__(\n        broker=broker,\n        logger=logger,\n        title=title,\n        version=version,\n        description=description,\n        terms_of_service=terms_of_service,\n        license=license,\n        contact=contact,\n        identifier=identifier,\n        tags=tags,\n        external_docs=external_docs,\n    )\n\n    self._stop_event = None\n\n    self.lifespan_context = (\n        apply_types(\n            func=lifespan,\n            wrap_model=drop_response_type,\n        )\n        if lifespan is not None\n        else fake_context\n    )\n\n    set_exit(lambda *_: self.__exit())\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = tags\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.contact","title":"contact instance-attribute","text":"
contact = contact\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.context","title":"context instance-attribute","text":"
context = context\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.external_docs","title":"external_docs instance-attribute","text":"
external_docs = external_docs\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.identifier","title":"identifier instance-attribute","text":"
identifier = identifier\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.license","title":"license instance-attribute","text":"
license = license\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context = (\n    apply_types(\n        func=lifespan, wrap_model=drop_response_type\n    )\n    if lifespan is not None\n    else fake_context\n)\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = terms_of_service\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.title","title":"title instance-attribute","text":"
title = title\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.version","title":"version instance-attribute","text":"
version = version\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.after_shutdown","title":"after_shutdown","text":"
after_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker disconnected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def after_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker disconnected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().after_shutdown(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.after_startup","title":"after_startup","text":"
after_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker connected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def after_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker connected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().after_startup(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.on_shutdown","title":"on_shutdown","text":"
on_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker disconnected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def on_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker disconnected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().on_shutdown(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.on_startup","title":"on_startup","text":"
on_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker connected

This hook also takes an extra CLI options as a kwargs

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def on_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker connected\n\n    This hook also takes an extra CLI options as a kwargs\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().on_startup(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.run","title":"run async","text":"
run(\n    log_level: int = logging.INFO,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n) -> None\n

Run FastStream Application

PARAMETER DESCRIPTION log_level

force application log level

TYPE: int DEFAULT: INFO

RETURNS DESCRIPTION None

Block an event loop until stopped

Source code in faststream/app.py
async def run(\n    self,\n    log_level: int = logging.INFO,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Run FastStream Application\n\n    Args:\n        log_level: force application log level\n\n    Returns:\n        Block an event loop until stopped\n    \"\"\"\n    assert self.broker, \"You should setup a broker\"  # nosec B101\n\n    self._init_async_cycle()\n    async with self.lifespan_context(**(run_extra_options or {})):\n        try:\n            async with anyio.create_task_group() as tg:\n                tg.start_soon(self._start, log_level, run_extra_options)\n                await self._stop(log_level)\n                tg.cancel_scope.cancel()\n        except ExceptionGroup as e:\n            for ex in e.exceptions:\n                raise ex from None\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.set_broker","title":"set_broker","text":"
set_broker(broker: BrokerAsyncUsecase[Any, Any]) -> None\n

Set already existed App object broker Usefull then you create/init broker in on_startup hook

Source code in faststream/app.py
def set_broker(self, broker: BrokerAsyncUsecase[Any, Any]) -> None:\n    \"\"\"Set already existed App object broker\n    Usefull then you create/init broker in `on_startup` hook\"\"\"\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/asyncapi/get_asyncapi_html/","title":"get_asyncapi_html","text":"","boost":0.5},{"location":"api/faststream/asyncapi/get_asyncapi_html/#faststream.asyncapi.get_asyncapi_html","title":"faststream.asyncapi.get_asyncapi_html","text":"
get_asyncapi_html(\n    schema: Schema,\n    sidebar: bool = True,\n    info: bool = True,\n    servers: bool = True,\n    operations: bool = True,\n    messages: bool = True,\n    schemas: bool = True,\n    errors: bool = True,\n    expand_message_examples: bool = True,\n    title: str = \"FastStream\",\n) -> str\n

Generate HTML for displaying an AsyncAPI document.

PARAMETER DESCRIPTION schema

The AsyncAPI schema object.

TYPE: Schema

sidebar

Whether to show the sidebar. Defaults to True.

TYPE: bool DEFAULT: True

info

Whether to show the info section. Defaults to True.

TYPE: bool DEFAULT: True

servers

Whether to show the servers section. Defaults to True.

TYPE: bool DEFAULT: True

operations

Whether to show the operations section. Defaults to True.

TYPE: bool DEFAULT: True

messages

Whether to show the messages section. Defaults to True.

TYPE: bool DEFAULT: True

schemas

Whether to show the schemas section. Defaults to True.

TYPE: bool DEFAULT: True

errors

Whether to show the errors section. Defaults to True.

TYPE: bool DEFAULT: True

expand_message_examples

Whether to expand message examples. Defaults to True.

TYPE: bool DEFAULT: True

title

The title of the HTML document. Defaults to \"FastStream\".

TYPE: str DEFAULT: 'FastStream'

RETURNS DESCRIPTION str

The generated HTML document.

TYPE: str

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/asyncapi/site.py
def get_asyncapi_html(\n    schema: \"Schema\",\n    sidebar: bool = True,\n    info: bool = True,\n    servers: bool = True,\n    operations: bool = True,\n    messages: bool = True,\n    schemas: bool = True,\n    errors: bool = True,\n    expand_message_examples: bool = True,\n    title: str = \"FastStream\",\n) -> str:\n    \"\"\"Generate HTML for displaying an AsyncAPI document.\n\n    Args:\n        schema (Schema): The AsyncAPI schema object.\n        sidebar (bool, optional): Whether to show the sidebar. Defaults to True.\n        info (bool, optional): Whether to show the info section. Defaults to True.\n        servers (bool, optional): Whether to show the servers section. Defaults to True.\n        operations (bool, optional): Whether to show the operations section. Defaults to True.\n        messages (bool, optional): Whether to show the messages section. Defaults to True.\n        schemas (bool, optional): Whether to show the schemas section. Defaults to True.\n        errors (bool, optional): Whether to show the errors section. Defaults to True.\n        expand_message_examples (bool, optional): Whether to expand message examples. Defaults to True.\n        title (str, optional): The title of the HTML document. Defaults to \"FastStream\".\n\n    Returns:\n        str: The generated HTML document.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    schema_json = schema.to_json()\n\n    config = {\n        \"schema\": schema_json,\n        \"config\": {\n            \"show\": {\n                \"sidebar\": sidebar,\n                \"info\": info,\n                \"servers\": servers,\n                \"operations\": operations,\n                \"messages\": messages,\n                \"schemas\": schemas,\n                \"errors\": errors,\n            },\n            \"expand\": {\n                \"messageExamples\": expand_message_examples,\n            },\n            \"sidebar\": {\n                \"showServers\": \"byDefault\",\n                \"showOperations\": \"byDefault\",\n            },\n        },\n    }\n\n    return (\n        \"\"\"\n    <!DOCTYPE html>\n    <html>\n        <head>\n    \"\"\"\n        f\"\"\"\n        <title>{title} AsyncAPI</title>\n    \"\"\"\n        \"\"\"\n        <link rel=\"icon\" href=\"https://www.asyncapi.com/favicon.ico\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"https://www.asyncapi.com/favicon-16x16.png\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"https://www.asyncapi.com/favicon-32x32.png\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"194x194\" href=\"https://www.asyncapi.com/favicon-194x194.png\">\n        <link rel=\"stylesheet\" href=\"https://unpkg.com/@asyncapi/react-component@1.0.0-next.46/styles/default.min.css\">\n        </head>\n\n        <style>\n        html {\n            font-family: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;\n            line-height: 1.5;\n        }\n        </style>\n\n        <body>\n        <div id=\"asyncapi\"></div>\n\n        <script src=\"https://unpkg.com/@asyncapi/react-component@1.0.0-next.47/browser/standalone/index.js\"></script>\n        <script>\n    \"\"\"\n        f\"\"\"\n            AsyncApiStandalone.render({json.dumps(config)}, document.getElementById('asyncapi'));\n    \"\"\"\n        \"\"\"\n        </script>\n        </body>\n    </html>\n    \"\"\"\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/base/AsyncAPIOperation/","title":"AsyncAPIOperation","text":"","boost":0.5},{"location":"api/faststream/asyncapi/base/AsyncAPIOperation/#faststream.asyncapi.base.AsyncAPIOperation","title":"faststream.asyncapi.base.AsyncAPIOperation dataclass","text":"

A class representing an asynchronous API operation.

METHOD DESCRIPTION schema

returns the schema of the API operation as a dictionary of channel names and channel objects

","boost":0.5},{"location":"api/faststream/asyncapi/base/AsyncAPIOperation/#faststream.asyncapi.base.AsyncAPIOperation.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/asyncapi/base/AsyncAPIOperation/#faststream.asyncapi.base.AsyncAPIOperation.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/asyncapi/base/AsyncAPIOperation/#faststream.asyncapi.base.AsyncAPIOperation.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_broker_channels/","title":"get_app_broker_channels","text":"","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_broker_channels/#faststream.asyncapi.generate.get_app_broker_channels","title":"faststream.asyncapi.generate.get_app_broker_channels","text":"
get_app_broker_channels(\n    app: Union[FastStream, StreamRouter[Any]]\n) -> Dict[str, Channel]\n

Get the broker channels for an application.

PARAMETER DESCRIPTION app

An instance of FastStream or StreamRouter.

TYPE: Union[FastStream, StreamRouter[Any]]

RETURNS DESCRIPTION Dict[str, Channel]

A dictionary of channel names and their corresponding Channel objects.

RAISES DESCRIPTION AssertionError

If the app does not have a broker.

Source code in faststream/asyncapi/generate.py
def get_app_broker_channels(\n    app: Union[FastStream, \"StreamRouter[Any]\"]\n) -> Dict[str, Channel]:\n    \"\"\"Get the broker channels for an application.\n\n    Args:\n        app: An instance of FastStream or StreamRouter.\n\n    Returns:\n        A dictionary of channel names and their corresponding Channel objects.\n\n    Raises:\n        AssertionError: If the app does not have a broker.\n\n    \"\"\"\n    channels = {}\n    assert app.broker  # nosec B101\n\n    for h in app.broker.handlers.values():\n        channels.update(h.schema())\n\n    for p in app.broker._publishers.values():\n        channels.update(p.schema())\n\n    return channels\n
","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_broker_server/","title":"get_app_broker_server","text":"","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_broker_server/#faststream.asyncapi.generate.get_app_broker_server","title":"faststream.asyncapi.generate.get_app_broker_server","text":"
get_app_broker_server(\n    app: Union[FastStream, StreamRouter[Any]]\n) -> Dict[str, Server]\n

Get the broker server for an application.

PARAMETER DESCRIPTION app

An instance of FastStream or StreamRouter representing the application.

TYPE: Union[FastStream, StreamRouter[Any]]

RETURNS DESCRIPTION Dict[str, Server]

A dictionary containing the broker servers. The keys are the server names and the values are instances of Server class.

RAISES DESCRIPTION AssertionError

If the broker attribute of the app is not present.

Note

This function is currently incomplete and the following fields in the broker_meta dictionary are not populated: \"security\", \"variables\", \"bindings\".

Source code in faststream/asyncapi/generate.py
def get_app_broker_server(\n    app: Union[FastStream, \"StreamRouter[Any]\"]\n) -> Dict[str, Server]:\n    \"\"\"Get the broker server for an application.\n\n    Args:\n        app: An instance of `FastStream` or `StreamRouter` representing the application.\n\n    Returns:\n        A dictionary containing the broker servers. The keys are the server names and the values are instances of `Server` class.\n\n    Raises:\n        AssertionError: If the `broker` attribute of the app is not present.\n\n    Note:\n        This function is currently incomplete and the following fields in the `broker_meta` dictionary are not populated: \"security\", \"variables\", \"bindings\".\n\n    \"\"\"\n    servers = {}\n\n    broker = app.broker\n    assert broker  # nosec B101\n\n    broker_meta: Dict[str, Any] = {\n        \"protocol\": broker.protocol,\n        \"protocolVersion\": broker.protocol_version,\n        \"description\": broker.description,\n        \"tags\": broker.tags,\n        # TODO\n        # \"variables\": \"\",\n        # \"bindings\": \"\",\n    }\n\n    if broker.security is not None:\n        broker_meta[\"security\"] = broker.security.get_requirement()\n\n    if isinstance(broker.url, str):\n        servers[\"development\"] = Server(\n            url=broker.url,\n            **broker_meta,\n        )\n\n    elif len(broker.url) == 1:\n        servers[\"development\"] = Server(\n            url=broker.url[0],\n            **broker_meta,\n        )\n\n    else:\n        for i, url in enumerate(broker.url, 1):\n            servers[f\"Server{i}\"] = Server(\n                url=url,\n                **broker_meta,\n            )\n\n    return servers\n
","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_schema/","title":"get_app_schema","text":"","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_schema/#faststream.asyncapi.generate.get_app_schema","title":"faststream.asyncapi.generate.get_app_schema","text":"
get_app_schema(\n    app: Union[FastStream, StreamRouter[Any]]\n) -> Schema\n

Get the application schema.

PARAMETER DESCRIPTION app

An instance of FastStream or StreamRouter.

TYPE: Union[FastStream, StreamRouter[Any]]

RETURNS DESCRIPTION Schema

The schema object.

Source code in faststream/asyncapi/generate.py
def get_app_schema(app: Union[FastStream, \"StreamRouter[Any]\"]) -> Schema:\n    \"\"\"Get the application schema.\n\n    Args:\n        app: An instance of FastStream or StreamRouter.\n\n    Returns:\n        The schema object.\n\n    \"\"\"\n    servers = get_app_broker_server(app)\n    channels = get_app_broker_channels(app)\n\n    messages: Dict[str, Message] = {}\n    payloads: Dict[str, Dict[str, Any]] = {}\n    for channel_name, ch in channels.items():\n        ch.servers = list(servers.keys())\n\n        if ch.subscribe is not None:\n            m = ch.subscribe.message\n\n            if isinstance(m, Message):  # pragma: no branch\n                ch.subscribe.message = _resolve_msg_payloads(\n                    m,\n                    channel_name,\n                    payloads,\n                    messages,\n                )\n\n        if ch.publish is not None:\n            m = ch.publish.message\n\n            if isinstance(m, Message):  # pragma: no branch\n                ch.publish.message = _resolve_msg_payloads(\n                    m,\n                    channel_name,\n                    payloads,\n                    messages,\n                )\n\n    broker = app.broker\n    if broker is None:  # pragma: no cover\n        raise RuntimeError()\n\n    schema = Schema(\n        info=Info(\n            title=app.title,\n            version=app.version,\n            description=app.description,\n            termsOfService=app.terms_of_service,\n            contact=app.contact,\n            license=app.license,\n        ),\n        defaultContentType=ContentTypes.json.value,\n        id=app.identifier,\n        tags=list(app.asyncapi_tags) if app.asyncapi_tags else None,\n        externalDocs=app.external_docs,\n        servers=servers,\n        channels=channels,\n        components=Components(\n            messages=messages,\n            schemas=payloads,\n            securitySchemes=None\n            if broker.security is None\n            else broker.security.get_schema(),\n        ),\n    )\n    return schema\n
","boost":0.5},{"location":"api/faststream/asyncapi/message/get_model_schema/","title":"get_model_schema","text":"","boost":0.5},{"location":"api/faststream/asyncapi/message/get_model_schema/#faststream.asyncapi.message.get_model_schema","title":"faststream.asyncapi.message.get_model_schema","text":"
get_model_schema(\n    call: Optional[Type[BaseModel]],\n    prefix: str = \"\",\n    exclude: Sequence[str] = (),\n) -> Optional[Dict[str, Any]]\n

Get the schema of a model.

PARAMETER DESCRIPTION call

The model class to get the schema for.

TYPE: Optional[Type[BaseModel]]

prefix

A prefix to add to the schema title.

TYPE: str DEFAULT: ''

exclude

A sequence of field names to exclude from the schema.

TYPE: Sequence[str] DEFAULT: ()

RETURNS DESCRIPTION Optional[Dict[str, Any]]

The schema of the model as a dictionary, or None if the model has no fields.

RAISES DESCRIPTION NotImplementedError

If the model is a silent animal.

Source code in faststream/asyncapi/message.py
def get_model_schema(\n    call: Optional[Type[BaseModel]],\n    prefix: str = \"\",\n    exclude: Sequence[str] = (),\n) -> Optional[Dict[str, Any]]:\n    \"\"\"Get the schema of a model.\n\n    Args:\n        call: The model class to get the schema for.\n        prefix: A prefix to add to the schema title.\n        exclude: A sequence of field names to exclude from the schema.\n\n    Returns:\n        The schema of the model as a dictionary, or None if the model has no fields.\n\n    Raises:\n        NotImplementedError: If the model is a silent animal.\n\n    \"\"\"\n    if call is None:\n        return None\n\n    params = {k: v for k, v in get_model_fields(call).items() if k not in exclude}\n    params_number = len(params)\n\n    if params_number == 0:\n        return None\n\n    model = None\n    use_original_model = False\n    if params_number == 1:\n        name, param = tuple(params.items())[0]\n\n        if (\n            param.annotation\n            and isclass(param.annotation)\n            and issubclass(param.annotation, BaseModel)  # NOTE: 3.7-3.10 compatibility\n        ):\n            model = param.annotation\n            use_original_model = True\n\n    if model is None:\n        model = call\n\n    body: Dict[str, Any] = model_schema(model)\n    body[\"properties\"] = body.get(\"properties\", {})\n    for i in exclude:\n        body[\"properties\"].pop(i, None)\n    if required := body.get(\"required\"):\n        body[\"required\"] = list(filter(lambda x: x not in exclude, required))\n\n    if params_number == 1 and not use_original_model:\n        param_body: Dict[str, Any] = body.get(\"properties\", {})\n        param_body = param_body[name]\n\n        if PYDANTIC_V2:\n            original_title = param.title\n        else:\n            original_title = param.field_info.title  # type: ignore[attr-defined]\n\n        if original_title:\n            use_original_model = True\n            param_body[\"title\"] = original_title\n        else:\n            param_body[\"title\"] = name\n\n        body = param_body\n\n    if not use_original_model:\n        body[\"title\"] = f\"{prefix}:Payload\"\n\n    return body\n
","boost":0.5},{"location":"api/faststream/asyncapi/message/get_response_schema/","title":"get_response_schema","text":"","boost":0.5},{"location":"api/faststream/asyncapi/message/get_response_schema/#faststream.asyncapi.message.get_response_schema","title":"faststream.asyncapi.message.get_response_schema","text":"
get_response_schema(\n    call: Optional[CallModel[Any, Any]], prefix: str = \"\"\n) -> Optional[Dict[str, Any]]\n

Get the response schema for a given call.

PARAMETER DESCRIPTION call

The call model.

TYPE: Optional[CallModel[Any, Any]]

prefix

A prefix to add to the schema keys.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION Optional[Dict[str, Any]]

The response schema as a dictionary.

Source code in faststream/asyncapi/message.py
def get_response_schema(\n    call: Optional[CallModel[Any, Any]],\n    prefix: str = \"\",\n) -> Optional[Dict[str, Any]]:\n    \"\"\"Get the response schema for a given call.\n\n    Args:\n        call: The call model.\n        prefix: A prefix to add to the schema keys.\n\n    Returns:\n        The response schema as a dictionary.\n\n    \"\"\"\n    return get_model_schema(\n        getattr(\n            call, \"response_model\", None\n        ),  # NOTE: FastAPI Dependant object compatibility\n        prefix=prefix,\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/message/parse_handler_params/","title":"parse_handler_params","text":"","boost":0.5},{"location":"api/faststream/asyncapi/message/parse_handler_params/#faststream.asyncapi.message.parse_handler_params","title":"faststream.asyncapi.message.parse_handler_params","text":"
parse_handler_params(\n    call: CallModel[Any, Any], prefix: str = \"\"\n) -> Dict[str, Any]\n

Parses the handler parameters.

PARAMETER DESCRIPTION call

The call model.

TYPE: CallModel[Any, Any]

prefix

The prefix for the model schema.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION Dict[str, Any]

A dictionary containing the parsed parameters.

Source code in faststream/asyncapi/message.py
def parse_handler_params(call: CallModel[Any, Any], prefix: str = \"\") -> Dict[str, Any]:\n    \"\"\"Parses the handler parameters.\n\n    Args:\n        call: The call model.\n        prefix: The prefix for the model schema.\n\n    Returns:\n        A dictionary containing the parsed parameters.\n\n    \"\"\"\n    body = get_model_schema(\n        call.model,\n        prefix=prefix,\n        exclude=tuple(call.custom_fields.keys()),\n    )\n\n    if body is None:\n        return {\"title\": \"EmptyPayload\", \"type\": \"null\"}\n\n    return body\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/","title":"Channel","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel","title":"faststream.asyncapi.schema.Channel","text":"

Bases: BaseModel

A class to represent a channel.

Configurations

model_config : configuration for the model (only applicable for Pydantic version 2) Config : configuration for the class (only applicable for Pydantic version 1)

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.parameters","title":"parameters class-attribute instance-attribute","text":"
parameters: Optional[Parameter] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.publish","title":"publish class-attribute instance-attribute","text":"
publish: Optional[Operation] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.servers","title":"servers class-attribute instance-attribute","text":"
servers: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.subscribe","title":"subscribe class-attribute instance-attribute","text":"
subscribe: Optional[Operation] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding","title":"faststream.asyncapi.schema.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/","title":"Components","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components","title":"faststream.asyncapi.schema.Components","text":"

Bases: BaseModel

A class to represent components in a system.

Note

The following attributes are not implemented yet: - servers - serverVariables - channels - securitySchemes - parameters - correlationIds - operationTraits - messageTraits - serverBindings - channelBindings - operationBindings - messageBindings

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.messages","title":"messages class-attribute instance-attribute","text":"
messages: Optional[Dict[str, Message]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.schemas","title":"schemas class-attribute instance-attribute","text":"
schemas: Optional[Dict[str, Dict[str, Any]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.securitySchemes","title":"securitySchemes class-attribute instance-attribute","text":"
securitySchemes: Optional[Dict[str, Dict[str, Any]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/","title":"Contact","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact","title":"faststream.asyncapi.schema.Contact","text":"

Bases: BaseModel

A class to represent a contact.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.email","title":"email class-attribute instance-attribute","text":"
email: Optional[EmailStr] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.url","title":"url class-attribute instance-attribute","text":"
url: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ContactDict/","title":"ContactDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ContactDict/#faststream.asyncapi.schema.ContactDict","title":"faststream.asyncapi.schema.ContactDict","text":"

Bases: TypedDict

A class to represent a dictionary of contact information.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/ContactDict/#faststream.asyncapi.schema.ContactDict.email","title":"email instance-attribute","text":"
email: EmailStr\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ContactDict/#faststream.asyncapi.schema.ContactDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ContactDict/#faststream.asyncapi.schema.ContactDict.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/","title":"CorrelationId","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId","title":"faststream.asyncapi.schema.CorrelationId","text":"

Bases: BaseModel

A class to represent a correlation ID.

Configurations

extra : allows extra fields in the correlation ID model

","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId.location","title":"location instance-attribute","text":"
location: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/","title":"ExternalDocs","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs","title":"faststream.asyncapi.schema.ExternalDocs","text":"

Bases: BaseModel

A class to represent external documentation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocsDict/","title":"ExternalDocsDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocsDict/#faststream.asyncapi.schema.ExternalDocsDict","title":"faststream.asyncapi.schema.ExternalDocsDict","text":"

Bases: TypedDict

A dictionary type for representing external documentation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocsDict/#faststream.asyncapi.schema.ExternalDocsDict.description","title":"description instance-attribute","text":"
description: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocsDict/#faststream.asyncapi.schema.ExternalDocsDict.url","title":"url instance-attribute","text":"
url: Required[AnyHttpUrl]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/","title":"Info","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info","title":"faststream.asyncapi.schema.Info","text":"

Bases: BaseModel

A class to represent information.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.contact","title":"contact class-attribute instance-attribute","text":"
contact: Optional[\n    Union[Contact, ContactDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.description","title":"description class-attribute instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.license","title":"license class-attribute instance-attribute","text":"
license: Optional[\n    Union[License, LicenseDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.termsOfService","title":"termsOfService class-attribute instance-attribute","text":"
termsOfService: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.title","title":"title instance-attribute","text":"
title: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.version","title":"version class-attribute instance-attribute","text":"
version: str = '1.0.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/","title":"License","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License","title":"faststream.asyncapi.schema.License","text":"

Bases: BaseModel

A class to represent a license.

Config

extra : allow additional attributes in the model (PYDANTIC_V2)

","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License.url","title":"url class-attribute instance-attribute","text":"
url: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/LicenseDict/","title":"LicenseDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/LicenseDict/#faststream.asyncapi.schema.LicenseDict","title":"faststream.asyncapi.schema.LicenseDict","text":"

Bases: TypedDict

A dictionary-like class to represent a license.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/LicenseDict/#faststream.asyncapi.schema.LicenseDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/LicenseDict/#faststream.asyncapi.schema.LicenseDict.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/","title":"Message","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message","title":"faststream.asyncapi.schema.Message","text":"

Bases: BaseModel

A class to represent a message.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.contentType","title":"contentType class-attribute instance-attribute","text":"
contentType: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.correlationId","title":"correlationId class-attribute instance-attribute","text":"
correlationId: Optional[CorrelationId] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.messageId","title":"messageId class-attribute instance-attribute","text":"
messageId: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.payload","title":"payload instance-attribute","text":"
payload: Dict[str, Any]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.summary","title":"summary class-attribute instance-attribute","text":"
summary: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[List[Union[Tag, Dict[str, Any]]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/","title":"Operation","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation","title":"faststream.asyncapi.schema.Operation","text":"

Bases: BaseModel

A class to represent an operation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.message","title":"message instance-attribute","text":"
message: Union[Message, Reference]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.operationId","title":"operationId class-attribute instance-attribute","text":"
operationId: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.security","title":"security class-attribute instance-attribute","text":"
security: Optional[Dict[str, List[str]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.summary","title":"summary class-attribute instance-attribute","text":"
summary: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding","title":"faststream.asyncapi.schema.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Reference/","title":"Reference","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Reference/#faststream.asyncapi.schema.Reference","title":"faststream.asyncapi.schema.Reference","text":"

Bases: BaseModel

A class to represent a reference.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Reference/#faststream.asyncapi.schema.Reference.ref","title":"ref class-attribute instance-attribute","text":"
ref: str = Field(..., alias='$ref')\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/","title":"Schema","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema","title":"faststream.asyncapi.schema.Schema","text":"

Bases: BaseModel

A class to represent a schema.

METHOD DESCRIPTION to_jsonable

Convert the schema to a JSON-serializable object.

to_json

Convert the schema to a JSON string.

to_yaml

Convert the schema to a YAML string.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.asyncapi","title":"asyncapi class-attribute instance-attribute","text":"
asyncapi: str = ASYNC_API_VERSION\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.channels","title":"channels instance-attribute","text":"
channels: Dict[str, Channel]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.components","title":"components class-attribute instance-attribute","text":"
components: Optional[Components] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.defaultContentType","title":"defaultContentType class-attribute instance-attribute","text":"
defaultContentType: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.id","title":"id class-attribute instance-attribute","text":"
id: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.info","title":"info instance-attribute","text":"
info: Info\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.servers","title":"servers class-attribute instance-attribute","text":"
servers: Optional[Dict[str, Server]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.to_json","title":"to_json","text":"
to_json() -> str\n
Source code in faststream/asyncapi/schema/main.py
def to_json(self) -> str:\n    return model_to_json(\n        self,\n        by_alias=True,\n        exclude_none=True,\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.to_jsonable","title":"to_jsonable","text":"
to_jsonable() -> Any\n
Source code in faststream/asyncapi/schema/main.py
def to_jsonable(self) -> Any:\n    return model_to_jsonable(\n        self,\n        by_alias=True,\n        exclude_none=True,\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.to_yaml","title":"to_yaml","text":"
to_yaml() -> str\n
Source code in faststream/asyncapi/schema/main.py
def to_yaml(self) -> str:\n    from io import StringIO\n\n    import yaml\n\n    io = StringIO(initial_value=\"\", newline=\"\\n\")\n    yaml.dump(self.to_jsonable(), io, sort_keys=False)\n    return io.getvalue()\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/","title":"SecuritySchemaComponent","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent","title":"faststream.asyncapi.schema.SecuritySchemaComponent","text":"

Bases: BaseModel

A class to represent a security schema component.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.bearerFormat","title":"bearerFormat class-attribute instance-attribute","text":"
bearerFormat: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.flows","title":"flows class-attribute instance-attribute","text":"
flows: Optional[OauthFlows] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.in_","title":"in_ class-attribute instance-attribute","text":"
in_: Optional[str] = Field(default=None, alias='in')\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.openIdConnectUrl","title":"openIdConnectUrl class-attribute instance-attribute","text":"
openIdConnectUrl: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.schema_","title":"schema_ class-attribute instance-attribute","text":"
schema_: Optional[str] = Field(default=None, alias=\"schema\")\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.type","title":"type instance-attribute","text":"
type: Literal[\n    \"userPassword\",\n    \"apikey\",\n    \"X509\",\n    \"symmetricEncryption\",\n    \"asymmetricEncryption\",\n    \"httpApiKey\",\n    \"http\",\n    \"oauth2\",\n    \"openIdConnect\",\n    \"plain\",\n    \"scramSha256\",\n    \"scramSha512\",\n    \"gssapi\",\n]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/","title":"Server","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server","title":"faststream.asyncapi.schema.Server","text":"

Bases: BaseModel

A class to represent a server.

Note

The attributes description, protocolVersion, tags, security, variables, and bindings are all optional.

Configurations

If PYDANTIC_V2 is True, the model configuration is set to allow extra attributes. Otherwise, the Config class is defined with the extra attribute set to \"allow\".

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[Union[ServerBinding, Reference]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.protocol","title":"protocol instance-attribute","text":"
protocol: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.protocolVersion","title":"protocolVersion class-attribute instance-attribute","text":"
protocolVersion: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.security","title":"security class-attribute instance-attribute","text":"
security: Optional[SecurityRequirement] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.variables","title":"variables class-attribute instance-attribute","text":"
variables: Optional[\n    Dict[str, Union[ServerVariable, Reference]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding","title":"faststream.asyncapi.schema.ServerBinding","text":"

Bases: BaseModel

A class to represent server bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/","title":"Tag","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag","title":"faststream.asyncapi.schema.Tag","text":"

Bases: BaseModel

A class to represent a tag.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/TagDict/","title":"TagDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/TagDict/#faststream.asyncapi.schema.TagDict","title":"faststream.asyncapi.schema.TagDict","text":"

Bases: TypedDict

A dictionary-like class for storing tags.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/TagDict/#faststream.asyncapi.schema.TagDict.description","title":"description instance-attribute","text":"
description: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/TagDict/#faststream.asyncapi.schema.TagDict.externalDocs","title":"externalDocs instance-attribute","text":"
externalDocs: Union[ExternalDocs, ExternalDocsDict]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/TagDict/#faststream.asyncapi.schema.TagDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding","title":"faststream.asyncapi.schema.bindings.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding","title":"faststream.asyncapi.schema.bindings.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding","title":"faststream.asyncapi.schema.bindings.ServerBinding","text":"

Bases: BaseModel

A class to represent server bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/#faststream.asyncapi.schema.bindings.amqp.ChannelBinding","title":"faststream.asyncapi.schema.bindings.amqp.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/#faststream.asyncapi.schema.bindings.amqp.ChannelBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.2.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/#faststream.asyncapi.schema.bindings.amqp.ChannelBinding.exchange","title":"exchange class-attribute instance-attribute","text":"
exchange: Optional[Exchange] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/#faststream.asyncapi.schema.bindings.amqp.ChannelBinding.is_","title":"is_ class-attribute instance-attribute","text":"
is_: Literal[\"queue\", \"routingKey\"] = Field(..., alias=\"is\")\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/#faststream.asyncapi.schema.bindings.amqp.ChannelBinding.queue","title":"queue class-attribute instance-attribute","text":"
queue: Optional[Queue] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/","title":"Exchange","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange","title":"faststream.asyncapi.schema.bindings.amqp.Exchange","text":"

Bases: BaseModel

A class to represent an exchange.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange.autoDelete","title":"autoDelete class-attribute instance-attribute","text":"
autoDelete: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange.durable","title":"durable class-attribute instance-attribute","text":"
durable: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange.type","title":"type instance-attribute","text":"
type: Literal[\n    \"default\", \"direct\", \"topic\", \"fanout\", \"headers\"\n]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange.vhost","title":"vhost class-attribute instance-attribute","text":"
vhost: str = '/'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding","title":"faststream.asyncapi.schema.bindings.amqp.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.ack","title":"ack class-attribute instance-attribute","text":"
ack: bool = True\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.2.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.cc","title":"cc class-attribute instance-attribute","text":"
cc: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.deliveryMode","title":"deliveryMode class-attribute instance-attribute","text":"
deliveryMode: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.priority","title":"priority class-attribute instance-attribute","text":"
priority: Optional[PositiveInt] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.replyTo","title":"replyTo class-attribute instance-attribute","text":"
replyTo: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/","title":"Queue","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue","title":"faststream.asyncapi.schema.bindings.amqp.Queue","text":"

Bases: BaseModel

A class to represent a queue.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue.autoDelete","title":"autoDelete instance-attribute","text":"
autoDelete: bool\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue.durable","title":"durable instance-attribute","text":"
durable: bool\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue.exclusive","title":"exclusive instance-attribute","text":"
exclusive: bool\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue.vhost","title":"vhost class-attribute instance-attribute","text":"
vhost: str = '/'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ServerBinding/#faststream.asyncapi.schema.bindings.amqp.ServerBinding","title":"faststream.asyncapi.schema.bindings.amqp.ServerBinding","text":"

Bases: BaseModel

A class to represent a server binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ServerBinding/#faststream.asyncapi.schema.bindings.amqp.ServerBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.2.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/#faststream.asyncapi.schema.bindings.kafka.ChannelBinding","title":"faststream.asyncapi.schema.bindings.kafka.ChannelBinding","text":"

Bases: BaseModel

A class to represent a channel binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/#faststream.asyncapi.schema.bindings.kafka.ChannelBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.4.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/#faststream.asyncapi.schema.bindings.kafka.ChannelBinding.partitions","title":"partitions class-attribute instance-attribute","text":"
partitions: Optional[PositiveInt] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/#faststream.asyncapi.schema.bindings.kafka.ChannelBinding.replicas","title":"replicas class-attribute instance-attribute","text":"
replicas: Optional[PositiveInt] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/#faststream.asyncapi.schema.bindings.kafka.ChannelBinding.topic","title":"topic class-attribute instance-attribute","text":"
topic: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/#faststream.asyncapi.schema.bindings.kafka.OperationBinding","title":"faststream.asyncapi.schema.bindings.kafka.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/#faststream.asyncapi.schema.bindings.kafka.OperationBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.4.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/#faststream.asyncapi.schema.bindings.kafka.OperationBinding.clientId","title":"clientId class-attribute instance-attribute","text":"
clientId: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/#faststream.asyncapi.schema.bindings.kafka.OperationBinding.groupId","title":"groupId class-attribute instance-attribute","text":"
groupId: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/#faststream.asyncapi.schema.bindings.kafka.OperationBinding.replyTo","title":"replyTo class-attribute instance-attribute","text":"
replyTo: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ServerBinding/#faststream.asyncapi.schema.bindings.kafka.ServerBinding","title":"faststream.asyncapi.schema.bindings.kafka.ServerBinding","text":"

Bases: BaseModel

A class to represent a server binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ServerBinding/#faststream.asyncapi.schema.bindings.kafka.ServerBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.4.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding","title":"faststream.asyncapi.schema.bindings.main.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding","title":"faststream.asyncapi.schema.bindings.main.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding","title":"faststream.asyncapi.schema.bindings.main.ServerBinding","text":"

Bases: BaseModel

A class to represent server bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ChannelBinding/#faststream.asyncapi.schema.bindings.nats.ChannelBinding","title":"faststream.asyncapi.schema.bindings.nats.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ChannelBinding/#faststream.asyncapi.schema.bindings.nats.ChannelBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ChannelBinding/#faststream.asyncapi.schema.bindings.nats.ChannelBinding.queue","title":"queue class-attribute instance-attribute","text":"
queue: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ChannelBinding/#faststream.asyncapi.schema.bindings.nats.ChannelBinding.subject","title":"subject instance-attribute","text":"
subject: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/OperationBinding/#faststream.asyncapi.schema.bindings.nats.OperationBinding","title":"faststream.asyncapi.schema.bindings.nats.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/OperationBinding/#faststream.asyncapi.schema.bindings.nats.OperationBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/OperationBinding/#faststream.asyncapi.schema.bindings.nats.OperationBinding.replyTo","title":"replyTo class-attribute instance-attribute","text":"
replyTo: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ServerBinding/#faststream.asyncapi.schema.bindings.nats.ServerBinding","title":"faststream.asyncapi.schema.bindings.nats.ServerBinding","text":"

Bases: BaseModel

A class to represent a server binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ServerBinding/#faststream.asyncapi.schema.bindings.nats.ServerBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding","title":"faststream.asyncapi.schema.bindings.redis.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding.channel","title":"channel instance-attribute","text":"
channel: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding.consumer_name","title":"consumer_name class-attribute instance-attribute","text":"
consumer_name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding.group_name","title":"group_name class-attribute instance-attribute","text":"
group_name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding.method","title":"method class-attribute instance-attribute","text":"
method: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/OperationBinding/#faststream.asyncapi.schema.bindings.redis.OperationBinding","title":"faststream.asyncapi.schema.bindings.redis.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/OperationBinding/#faststream.asyncapi.schema.bindings.redis.OperationBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/OperationBinding/#faststream.asyncapi.schema.bindings.redis.OperationBinding.replyTo","title":"replyTo class-attribute instance-attribute","text":"
replyTo: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ServerBinding/#faststream.asyncapi.schema.bindings.redis.ServerBinding","title":"faststream.asyncapi.schema.bindings.redis.ServerBinding","text":"

Bases: BaseModel

A class to represent a server binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ServerBinding/#faststream.asyncapi.schema.bindings.redis.ServerBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ChannelBinding/#faststream.asyncapi.schema.bindings.sqs.ChannelBinding","title":"faststream.asyncapi.schema.bindings.sqs.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ChannelBinding/#faststream.asyncapi.schema.bindings.sqs.ChannelBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ChannelBinding/#faststream.asyncapi.schema.bindings.sqs.ChannelBinding.queue","title":"queue instance-attribute","text":"
queue: Dict[str, Any]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/OperationBinding/#faststream.asyncapi.schema.bindings.sqs.OperationBinding","title":"faststream.asyncapi.schema.bindings.sqs.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/OperationBinding/#faststream.asyncapi.schema.bindings.sqs.OperationBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/OperationBinding/#faststream.asyncapi.schema.bindings.sqs.OperationBinding.replyTo","title":"replyTo class-attribute instance-attribute","text":"
replyTo: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ServerBinding/#faststream.asyncapi.schema.bindings.sqs.ServerBinding","title":"faststream.asyncapi.schema.bindings.sqs.ServerBinding","text":"

Bases: BaseModel

A class to represent a server binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ServerBinding/#faststream.asyncapi.schema.bindings.sqs.ServerBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/","title":"Channel","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel","title":"faststream.asyncapi.schema.channels.Channel","text":"

Bases: BaseModel

A class to represent a channel.

Configurations

model_config : configuration for the model (only applicable for Pydantic version 2) Config : configuration for the class (only applicable for Pydantic version 1)

","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.parameters","title":"parameters class-attribute instance-attribute","text":"
parameters: Optional[Parameter] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.publish","title":"publish class-attribute instance-attribute","text":"
publish: Optional[Operation] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.servers","title":"servers class-attribute instance-attribute","text":"
servers: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.subscribe","title":"subscribe class-attribute instance-attribute","text":"
subscribe: Optional[Operation] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/","title":"Contact","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact","title":"faststream.asyncapi.schema.info.Contact","text":"

Bases: BaseModel

A class to represent a contact.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.email","title":"email class-attribute instance-attribute","text":"
email: Optional[EmailStr] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.url","title":"url class-attribute instance-attribute","text":"
url: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/ContactDict/","title":"ContactDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/ContactDict/#faststream.asyncapi.schema.info.ContactDict","title":"faststream.asyncapi.schema.info.ContactDict","text":"

Bases: TypedDict

A class to represent a dictionary of contact information.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/ContactDict/#faststream.asyncapi.schema.info.ContactDict.email","title":"email instance-attribute","text":"
email: EmailStr\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/ContactDict/#faststream.asyncapi.schema.info.ContactDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/ContactDict/#faststream.asyncapi.schema.info.ContactDict.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/EmailStr/","title":"EmailStr","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/EmailStr/#faststream.asyncapi.schema.info.EmailStr","title":"faststream.asyncapi.schema.info.EmailStr","text":"

Bases: str

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/EmailStr/#faststream.asyncapi.schema.info.EmailStr.validate","title":"validate classmethod","text":"
validate(v: Any) -> str\n
Source code in faststream/asyncapi/schema/info.py
@classmethod\ndef validate(cls, v: Any) -> str:\n    logger.warning(\n        \"email-validator bot installed, email fields will be treated as str.\\n\"\n        \"To install, run: pip install email-validator\"\n    )\n    return str(v)\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/","title":"Info","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info","title":"faststream.asyncapi.schema.info.Info","text":"

Bases: BaseModel

A class to represent information.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.contact","title":"contact class-attribute instance-attribute","text":"
contact: Optional[\n    Union[Contact, ContactDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.description","title":"description class-attribute instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.license","title":"license class-attribute instance-attribute","text":"
license: Optional[\n    Union[License, LicenseDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.termsOfService","title":"termsOfService class-attribute instance-attribute","text":"
termsOfService: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.title","title":"title instance-attribute","text":"
title: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.version","title":"version class-attribute instance-attribute","text":"
version: str = '1.0.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/","title":"License","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License","title":"faststream.asyncapi.schema.info.License","text":"

Bases: BaseModel

A class to represent a license.

Config

extra : allow additional attributes in the model (PYDANTIC_V2)

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License.url","title":"url class-attribute instance-attribute","text":"
url: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/LicenseDict/","title":"LicenseDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/LicenseDict/#faststream.asyncapi.schema.info.LicenseDict","title":"faststream.asyncapi.schema.info.LicenseDict","text":"

Bases: TypedDict

A dictionary-like class to represent a license.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/LicenseDict/#faststream.asyncapi.schema.info.LicenseDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/LicenseDict/#faststream.asyncapi.schema.info.LicenseDict.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/","title":"Components","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components","title":"faststream.asyncapi.schema.main.Components","text":"

Bases: BaseModel

A class to represent components in a system.

Note

The following attributes are not implemented yet: - servers - serverVariables - channels - securitySchemes - parameters - correlationIds - operationTraits - messageTraits - serverBindings - channelBindings - operationBindings - messageBindings

","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.messages","title":"messages class-attribute instance-attribute","text":"
messages: Optional[Dict[str, Message]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.schemas","title":"schemas class-attribute instance-attribute","text":"
schemas: Optional[Dict[str, Dict[str, Any]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.securitySchemes","title":"securitySchemes class-attribute instance-attribute","text":"
securitySchemes: Optional[Dict[str, Dict[str, Any]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/","title":"Schema","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema","title":"faststream.asyncapi.schema.main.Schema","text":"

Bases: BaseModel

A class to represent a schema.

METHOD DESCRIPTION to_jsonable

Convert the schema to a JSON-serializable object.

to_json

Convert the schema to a JSON string.

to_yaml

Convert the schema to a YAML string.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.asyncapi","title":"asyncapi class-attribute instance-attribute","text":"
asyncapi: str = ASYNC_API_VERSION\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.channels","title":"channels instance-attribute","text":"
channels: Dict[str, Channel]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.components","title":"components class-attribute instance-attribute","text":"
components: Optional[Components] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.defaultContentType","title":"defaultContentType class-attribute instance-attribute","text":"
defaultContentType: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.id","title":"id class-attribute instance-attribute","text":"
id: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.info","title":"info instance-attribute","text":"
info: Info\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.servers","title":"servers class-attribute instance-attribute","text":"
servers: Optional[Dict[str, Server]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.to_json","title":"to_json","text":"
to_json() -> str\n
Source code in faststream/asyncapi/schema/main.py
def to_json(self) -> str:\n    return model_to_json(\n        self,\n        by_alias=True,\n        exclude_none=True,\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.to_jsonable","title":"to_jsonable","text":"
to_jsonable() -> Any\n
Source code in faststream/asyncapi/schema/main.py
def to_jsonable(self) -> Any:\n    return model_to_jsonable(\n        self,\n        by_alias=True,\n        exclude_none=True,\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.to_yaml","title":"to_yaml","text":"
to_yaml() -> str\n
Source code in faststream/asyncapi/schema/main.py
def to_yaml(self) -> str:\n    from io import StringIO\n\n    import yaml\n\n    io = StringIO(initial_value=\"\", newline=\"\\n\")\n    yaml.dump(self.to_jsonable(), io, sort_keys=False)\n    return io.getvalue()\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/","title":"CorrelationId","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId","title":"faststream.asyncapi.schema.message.CorrelationId","text":"

Bases: BaseModel

A class to represent a correlation ID.

Configurations

extra : allows extra fields in the correlation ID model

","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId.location","title":"location instance-attribute","text":"
location: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/","title":"Message","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message","title":"faststream.asyncapi.schema.message.Message","text":"

Bases: BaseModel

A class to represent a message.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.contentType","title":"contentType class-attribute instance-attribute","text":"
contentType: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.correlationId","title":"correlationId class-attribute instance-attribute","text":"
correlationId: Optional[CorrelationId] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.messageId","title":"messageId class-attribute instance-attribute","text":"
messageId: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.payload","title":"payload instance-attribute","text":"
payload: Dict[str, Any]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.summary","title":"summary class-attribute instance-attribute","text":"
summary: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[List[Union[Tag, Dict[str, Any]]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/","title":"Operation","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation","title":"faststream.asyncapi.schema.operations.Operation","text":"

Bases: BaseModel

A class to represent an operation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.message","title":"message instance-attribute","text":"
message: Union[Message, Reference]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.operationId","title":"operationId class-attribute instance-attribute","text":"
operationId: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.security","title":"security class-attribute instance-attribute","text":"
security: Optional[Dict[str, List[str]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.summary","title":"summary class-attribute instance-attribute","text":"
summary: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/","title":"OauthFlowObj","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj","title":"faststream.asyncapi.schema.security.OauthFlowObj","text":"

Bases: BaseModel

A class to represent an OAuth flow object.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.authorizationUrl","title":"authorizationUrl class-attribute instance-attribute","text":"
authorizationUrl: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.refreshUrl","title":"refreshUrl class-attribute instance-attribute","text":"
refreshUrl: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.scopes","title":"scopes instance-attribute","text":"
scopes: Dict[str, str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.tokenUrl","title":"tokenUrl class-attribute instance-attribute","text":"
tokenUrl: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/","title":"OauthFlows","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows","title":"faststream.asyncapi.schema.security.OauthFlows","text":"

Bases: BaseModel

A class to represent OAuth flows.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.authorizationCode","title":"authorizationCode class-attribute instance-attribute","text":"
authorizationCode: Optional[OauthFlowObj] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.clientCredentials","title":"clientCredentials class-attribute instance-attribute","text":"
clientCredentials: Optional[OauthFlowObj] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.implicit","title":"implicit class-attribute instance-attribute","text":"
implicit: Optional[OauthFlowObj] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.password","title":"password class-attribute instance-attribute","text":"
password: Optional[OauthFlowObj] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/","title":"SecuritySchemaComponent","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent","title":"faststream.asyncapi.schema.security.SecuritySchemaComponent","text":"

Bases: BaseModel

A class to represent a security schema component.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.bearerFormat","title":"bearerFormat class-attribute instance-attribute","text":"
bearerFormat: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.flows","title":"flows class-attribute instance-attribute","text":"
flows: Optional[OauthFlows] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.in_","title":"in_ class-attribute instance-attribute","text":"
in_: Optional[str] = Field(default=None, alias='in')\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.openIdConnectUrl","title":"openIdConnectUrl class-attribute instance-attribute","text":"
openIdConnectUrl: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.schema_","title":"schema_ class-attribute instance-attribute","text":"
schema_: Optional[str] = Field(default=None, alias=\"schema\")\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.type","title":"type instance-attribute","text":"
type: Literal[\n    \"userPassword\",\n    \"apikey\",\n    \"X509\",\n    \"symmetricEncryption\",\n    \"asymmetricEncryption\",\n    \"httpApiKey\",\n    \"http\",\n    \"oauth2\",\n    \"openIdConnect\",\n    \"plain\",\n    \"scramSha256\",\n    \"scramSha512\",\n    \"gssapi\",\n]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/","title":"Server","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server","title":"faststream.asyncapi.schema.servers.Server","text":"

Bases: BaseModel

A class to represent a server.

Note

The attributes description, protocolVersion, tags, security, variables, and bindings are all optional.

Configurations

If PYDANTIC_V2 is True, the model configuration is set to allow extra attributes. Otherwise, the Config class is defined with the extra attribute set to \"allow\".

","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[Union[ServerBinding, Reference]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.protocol","title":"protocol instance-attribute","text":"
protocol: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.protocolVersion","title":"protocolVersion class-attribute instance-attribute","text":"
protocolVersion: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.security","title":"security class-attribute instance-attribute","text":"
security: Optional[SecurityRequirement] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.variables","title":"variables class-attribute instance-attribute","text":"
variables: Optional[\n    Dict[str, Union[ServerVariable, Reference]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/","title":"ServerVariable","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable","title":"faststream.asyncapi.schema.servers.ServerVariable","text":"

Bases: BaseModel

A class to represent a server variable.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.default","title":"default class-attribute instance-attribute","text":"
default: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.enum","title":"enum class-attribute instance-attribute","text":"
enum: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.examples","title":"examples class-attribute instance-attribute","text":"
examples: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/","title":"ExternalDocs","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs","title":"faststream.asyncapi.schema.utils.ExternalDocs","text":"

Bases: BaseModel

A class to represent external documentation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocsDict/","title":"ExternalDocsDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocsDict/#faststream.asyncapi.schema.utils.ExternalDocsDict","title":"faststream.asyncapi.schema.utils.ExternalDocsDict","text":"

Bases: TypedDict

A dictionary type for representing external documentation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocsDict/#faststream.asyncapi.schema.utils.ExternalDocsDict.description","title":"description instance-attribute","text":"
description: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocsDict/#faststream.asyncapi.schema.utils.ExternalDocsDict.url","title":"url instance-attribute","text":"
url: Required[AnyHttpUrl]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Parameter/","title":"Parameter","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Parameter/#faststream.asyncapi.schema.utils.Parameter","title":"faststream.asyncapi.schema.utils.Parameter","text":"

Bases: BaseModel

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Reference/","title":"Reference","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Reference/#faststream.asyncapi.schema.utils.Reference","title":"faststream.asyncapi.schema.utils.Reference","text":"

Bases: BaseModel

A class to represent a reference.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Reference/#faststream.asyncapi.schema.utils.Reference.ref","title":"ref class-attribute instance-attribute","text":"
ref: str = Field(..., alias='$ref')\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/","title":"Tag","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag","title":"faststream.asyncapi.schema.utils.Tag","text":"

Bases: BaseModel

A class to represent a tag.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/TagDict/","title":"TagDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/TagDict/#faststream.asyncapi.schema.utils.TagDict","title":"faststream.asyncapi.schema.utils.TagDict","text":"

Bases: TypedDict

A dictionary-like class for storing tags.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/TagDict/#faststream.asyncapi.schema.utils.TagDict.description","title":"description instance-attribute","text":"
description: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/TagDict/#faststream.asyncapi.schema.utils.TagDict.externalDocs","title":"externalDocs instance-attribute","text":"
externalDocs: Union[ExternalDocs, ExternalDocsDict]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/TagDict/#faststream.asyncapi.schema.utils.TagDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/site/get_asyncapi_html/","title":"get_asyncapi_html","text":"","boost":0.5},{"location":"api/faststream/asyncapi/site/get_asyncapi_html/#faststream.asyncapi.site.get_asyncapi_html","title":"faststream.asyncapi.site.get_asyncapi_html","text":"
get_asyncapi_html(\n    schema: Schema,\n    sidebar: bool = True,\n    info: bool = True,\n    servers: bool = True,\n    operations: bool = True,\n    messages: bool = True,\n    schemas: bool = True,\n    errors: bool = True,\n    expand_message_examples: bool = True,\n    title: str = \"FastStream\",\n) -> str\n

Generate HTML for displaying an AsyncAPI document.

PARAMETER DESCRIPTION schema

The AsyncAPI schema object.

TYPE: Schema

sidebar

Whether to show the sidebar. Defaults to True.

TYPE: bool DEFAULT: True

info

Whether to show the info section. Defaults to True.

TYPE: bool DEFAULT: True

servers

Whether to show the servers section. Defaults to True.

TYPE: bool DEFAULT: True

operations

Whether to show the operations section. Defaults to True.

TYPE: bool DEFAULT: True

messages

Whether to show the messages section. Defaults to True.

TYPE: bool DEFAULT: True

schemas

Whether to show the schemas section. Defaults to True.

TYPE: bool DEFAULT: True

errors

Whether to show the errors section. Defaults to True.

TYPE: bool DEFAULT: True

expand_message_examples

Whether to expand message examples. Defaults to True.

TYPE: bool DEFAULT: True

title

The title of the HTML document. Defaults to \"FastStream\".

TYPE: str DEFAULT: 'FastStream'

RETURNS DESCRIPTION str

The generated HTML document.

TYPE: str

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/asyncapi/site.py
def get_asyncapi_html(\n    schema: \"Schema\",\n    sidebar: bool = True,\n    info: bool = True,\n    servers: bool = True,\n    operations: bool = True,\n    messages: bool = True,\n    schemas: bool = True,\n    errors: bool = True,\n    expand_message_examples: bool = True,\n    title: str = \"FastStream\",\n) -> str:\n    \"\"\"Generate HTML for displaying an AsyncAPI document.\n\n    Args:\n        schema (Schema): The AsyncAPI schema object.\n        sidebar (bool, optional): Whether to show the sidebar. Defaults to True.\n        info (bool, optional): Whether to show the info section. Defaults to True.\n        servers (bool, optional): Whether to show the servers section. Defaults to True.\n        operations (bool, optional): Whether to show the operations section. Defaults to True.\n        messages (bool, optional): Whether to show the messages section. Defaults to True.\n        schemas (bool, optional): Whether to show the schemas section. Defaults to True.\n        errors (bool, optional): Whether to show the errors section. Defaults to True.\n        expand_message_examples (bool, optional): Whether to expand message examples. Defaults to True.\n        title (str, optional): The title of the HTML document. Defaults to \"FastStream\".\n\n    Returns:\n        str: The generated HTML document.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    schema_json = schema.to_json()\n\n    config = {\n        \"schema\": schema_json,\n        \"config\": {\n            \"show\": {\n                \"sidebar\": sidebar,\n                \"info\": info,\n                \"servers\": servers,\n                \"operations\": operations,\n                \"messages\": messages,\n                \"schemas\": schemas,\n                \"errors\": errors,\n            },\n            \"expand\": {\n                \"messageExamples\": expand_message_examples,\n            },\n            \"sidebar\": {\n                \"showServers\": \"byDefault\",\n                \"showOperations\": \"byDefault\",\n            },\n        },\n    }\n\n    return (\n        \"\"\"\n    <!DOCTYPE html>\n    <html>\n        <head>\n    \"\"\"\n        f\"\"\"\n        <title>{title} AsyncAPI</title>\n    \"\"\"\n        \"\"\"\n        <link rel=\"icon\" href=\"https://www.asyncapi.com/favicon.ico\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"https://www.asyncapi.com/favicon-16x16.png\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"https://www.asyncapi.com/favicon-32x32.png\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"194x194\" href=\"https://www.asyncapi.com/favicon-194x194.png\">\n        <link rel=\"stylesheet\" href=\"https://unpkg.com/@asyncapi/react-component@1.0.0-next.46/styles/default.min.css\">\n        </head>\n\n        <style>\n        html {\n            font-family: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;\n            line-height: 1.5;\n        }\n        </style>\n\n        <body>\n        <div id=\"asyncapi\"></div>\n\n        <script src=\"https://unpkg.com/@asyncapi/react-component@1.0.0-next.47/browser/standalone/index.js\"></script>\n        <script>\n    \"\"\"\n        f\"\"\"\n            AsyncApiStandalone.render({json.dumps(config)}, document.getElementById('asyncapi'));\n    \"\"\"\n        \"\"\"\n        </script>\n        </body>\n    </html>\n    \"\"\"\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/site/serve_app/","title":"serve_app","text":"","boost":0.5},{"location":"api/faststream/asyncapi/site/serve_app/#faststream.asyncapi.site.serve_app","title":"faststream.asyncapi.site.serve_app","text":"
serve_app(schema: Schema, host: str, port: int) -> None\n

Serve the FastAPI application.

PARAMETER DESCRIPTION schema

The schema object representing the API specification.

TYPE: Schema

host

The host address to run the application on.

TYPE: str

port

The port number to run the application on.

TYPE: int

RETURNS DESCRIPTION None

None

Source code in faststream/asyncapi/site.py
def serve_app(\n    schema: \"Schema\",\n    host: str,\n    port: int,\n) -> None:\n    \"\"\"Serve the FastAPI application.\n\n    Args:\n        schema: The schema object representing the API specification.\n        host: The host address to run the application on.\n        port: The port number to run the application on.\n\n    Returns:\n        None\n\n    \"\"\"\n    import uvicorn\n    from fastapi import FastAPI\n    from fastapi.responses import HTMLResponse\n\n    app = FastAPI()\n\n    @app.get(\"/\")\n    def asyncapi(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:  # pragma: no cover\n        \"\"\"Generate an AsyncAPI HTML response.\n\n        Args:\n            sidebar (bool): Whether to include the sidebar. Default is True.\n            info (bool): Whether to include the info section. Default is True.\n            servers (bool): Whether to include the servers section. Default is True.\n            operations (bool): Whether to include the operations section. Default is True.\n            messages (bool): Whether to include the messages section. Default is True.\n            schemas (bool): Whether to include the schemas section. Default is True.\n            errors (bool): Whether to include the errors section. Default is True.\n            expandMessageExamples (bool): Whether to expand message examples. Default is True.\n\n        Returns:\n            HTMLResponse: The generated HTML response.\n\n        \"\"\"\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=schema.info.title,\n            )\n        )\n\n    uvicorn.run(app, host=host, port=port)\n
","boost":0.5},{"location":"api/faststream/asyncapi/utils/resolve_payloads/","title":"resolve_payloads","text":"","boost":0.5},{"location":"api/faststream/asyncapi/utils/resolve_payloads/#faststream.asyncapi.utils.resolve_payloads","title":"faststream.asyncapi.utils.resolve_payloads","text":"
resolve_payloads(\n    payloads: List[Tuple[AnyDict, str]],\n    extra: str = \"\",\n    served_words: int = 1,\n) -> AnyDict\n

Resolve payloads.

PARAMETER DESCRIPTION payloads

A list of dictionaries representing payloads.

TYPE: List[Tuple[AnyDict, str]]

RETURNS DESCRIPTION AnyDict

A dictionary representing the resolved payload.

Source code in faststream/asyncapi/utils.py
def resolve_payloads(\n    payloads: List[Tuple[AnyDict, str]],\n    extra: str = \"\",\n    served_words: int = 1,\n) -> AnyDict:\n    \"\"\"Resolve payloads.\n\n    Args:\n        payloads: A list of dictionaries representing payloads.\n\n    Returns:\n        A dictionary representing the resolved payload.\n\n    \"\"\"\n    ln = len(payloads)\n    payload: AnyDict\n    if ln > 1:\n        one_of_payloads = {}\n\n        for body, handler_name in payloads:\n            title = body[\"title\"]\n            words = title.split(\":\")\n\n            if len(words) > 1:  # not pydantic model case\n                body[\"title\"] = title = \":\".join(\n                    filter(\n                        lambda x: bool(x),\n                        (\n                            handler_name,\n                            extra if extra not in words else \"\",\n                            *words[served_words:],\n                        ),\n                    )\n                )\n\n            one_of_payloads[title] = body\n\n        payload = {\"oneOf\": one_of_payloads}\n\n    elif ln == 1:\n        payload = payloads[0][0]\n\n    else:\n        payload = {}\n\n    return payload\n
","boost":0.5},{"location":"api/faststream/asyncapi/utils/to_camelcase/","title":"to_camelcase","text":"","boost":0.5},{"location":"api/faststream/asyncapi/utils/to_camelcase/#faststream.asyncapi.utils.to_camelcase","title":"faststream.asyncapi.utils.to_camelcase","text":"
to_camelcase(*names: str) -> str\n

Converts a list of names to camel case.

PARAMETER DESCRIPTION *names

Variable length list of names to be converted to camel case.

TYPE: str DEFAULT: ()

RETURNS DESCRIPTION str

The camel case representation of the names.

Example

to_camelcase(\"hello_world\") \"HelloWorld\"

Source code in faststream/asyncapi/utils.py
def to_camelcase(*names: str) -> str:\n    \"\"\"Converts a list of names to camel case.\n\n    Args:\n        *names: Variable length list of names to be converted to camel case.\n\n    Returns:\n        The camel case representation of the names.\n\n    Example:\n        >>> to_camelcase(\"hello_world\")\n        \"HelloWorld\"\n\n    \"\"\"\n    return \" \".join(names).replace(\"_\", \" \").title().replace(\" \", \"\")\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/","title":"BrokerUsecase","text":"","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase","title":"faststream.broker.core.abc.BrokerUsecase","text":"
BrokerUsecase(\n    url: Union[str, List[str]],\n    *args: Any,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = None,\n    description: Optional[str] = None,\n    tags: Optional[\n        Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]\n    ] = None,\n    asyncapi_url: Union[str, List[str], None] = None,\n    apply_types: bool = True,\n    validate: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[\n        str\n    ] = \"%(asctime)s %(levelname)s - %(message)s\",\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[Callable[[MsgType], BaseMiddleware]]\n    ] = None,\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: ABC, Generic[MsgType, ConnectionType], LoggingMixin

A class representing a broker use case.

METHOD DESCRIPTION __init__

constructor method

include_router

include a router in the broker

include_routers

include multiple routers in the broker

_resolve_connection_kwargs

resolve connection kwargs

_wrap_handler

wrap a handler function

_abc_start

start the broker

_abc_close

close the broker

_abc__close

close the broker connection

_process_message

process a message

subscriber

decorator to register a subscriber

publisher

register a publisher

_wrap_decode_message

wrap a message decoding function

Initialize a broker.

PARAMETER DESCRIPTION url

The URL or list of URLs to connect to.

TYPE: Union[str, List[str]]

*args

Additional arguments.

TYPE: Any DEFAULT: ()

protocol

The protocol to use for the connection.

TYPE: Optional[str] DEFAULT: None

protocol_version

The version of the protocol.

TYPE: Optional[str] DEFAULT: None

description

A description of the broker.

TYPE: Optional[str] DEFAULT: None

tags

Tags associated with the broker.

TYPE: Optional[Sequence[Union[Tag, TagDict]]] DEFAULT: None

apply_types

Whether to apply types to messages.

TYPE: bool DEFAULT: True

validate

Whether to cast types using Pydantic validation.

TYPE: bool DEFAULT: True

logger

The logger to use.

TYPE: Optional[Logger] DEFAULT: access_logger

log_level

The log level to use.

TYPE: int DEFAULT: INFO

log_fmt

The log format to use.

TYPE: Optional[str] DEFAULT: '%(asctime)s %(levelname)s - %(message)s'

dependencies

Dependencies of the broker.

TYPE: Sequence[Depends] DEFAULT: ()

middlewares

Middlewares to use.

TYPE: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] DEFAULT: None

decoder

Custom decoder for messages.

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

parser

Custom parser for messages.

TYPE: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/core/abc.py
def __init__(\n    self,\n    url: Union[str, List[str]],\n    *args: Any,\n    # AsyncAPI kwargs\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = None,\n    description: Optional[str] = None,\n    tags: Optional[Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]] = None,\n    asyncapi_url: Union[str, List[str], None] = None,\n    # broker kwargs\n    apply_types: bool = True,\n    validate: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = \"%(asctime)s %(levelname)s - %(message)s\",\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] = None,\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a broker.\n\n    Args:\n        url: The URL or list of URLs to connect to.\n        *args: Additional arguments.\n        protocol: The protocol to use for the connection.\n        protocol_version: The version of the protocol.\n        description: A description of the broker.\n        tags: Tags associated with the broker.\n        apply_types: Whether to apply types to messages.\n        validate: Whether to cast types using Pydantic validation.\n        logger: The logger to use.\n        log_level: The log level to use.\n        log_fmt: The log format to use.\n        dependencies: Dependencies of the broker.\n        middlewares: Middlewares to use.\n        decoder: Custom decoder for messages.\n        parser: Custom parser for messages.\n        **kwargs: Additional keyword arguments.\n\n    \"\"\"\n    super().__init__(\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n    )\n\n    self._connection = None\n    self._is_apply_types = apply_types\n    self._is_validate = validate\n    self.handlers = {}\n    self._publishers = {}\n    empty_middleware: Sequence[Callable[[MsgType], BaseMiddleware]] = ()\n    midd_args: Sequence[Callable[[MsgType], BaseMiddleware]] = (\n        middlewares or empty_middleware\n    )\n    self.middlewares = [CriticalLogMiddleware(logger, log_level), *midd_args]\n    self.dependencies = dependencies\n\n    self._connection_args = (url, *args)\n    self._connection_kwargs = kwargs\n\n    self._global_parser = parser\n    self._global_decoder = decoder\n\n    context.set_global(\"logger\", logger)\n    context.set_global(\"broker\", self)\n\n    self.started = False\n\n    # AsyncAPI information\n    self.url = asyncapi_url or url\n    self.protocol = protocol\n    self.protocol_version = protocol_version\n    self.description = description\n    self.tags = tags\n    self.security = security\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.handlers","title":"handlers instance-attribute","text":"
handlers: Mapping[Any, BaseHandler[MsgType]] = {}\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[Any], BaseMiddleware]] = [\n    CriticalLogMiddleware(logger, log_level),\n    *midd_args,\n]\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.url","title":"url instance-attribute","text":"
url = asyncapi_url or url\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.publisher","title":"publisher abstractmethod","text":"
publisher(\n    key: Any, publisher: BasePublisher[MsgType]\n) -> BasePublisher[MsgType]\n

Publishes a publisher.

PARAMETER DESCRIPTION key

The key associated with the publisher.

TYPE: Any

publisher

The publisher to be published.

TYPE: BasePublisher[MsgType]

RETURNS DESCRIPTION BasePublisher[MsgType]

The published publisher.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/abc.py
@abstractmethod\ndef publisher(\n    self,\n    key: Any,\n    publisher: BasePublisher[MsgType],\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a publisher.\n\n    Args:\n        key: The key associated with the publisher.\n        publisher: The publisher to be published.\n\n    Returns:\n        The published publisher.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    self._publishers = {**self._publishers, key: publisher}\n    return publisher\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.subscriber","title":"subscriber abstractmethod","text":"
subscriber(\n    *broker_args: Any,\n    retry: Union[bool, int] = False,\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Filter[\n        StreamMessage[MsgType]\n    ] = lambda: not m.processed,\n    _raw: bool = False,\n    _get_dependant: Optional[Any] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [\n        Union[\n            Callable[P_HandlerParams, T_HandlerReturn],\n            HandlerCallWrapper[\n                MsgType, P_HandlerParams, T_HandlerReturn\n            ],\n        ]\n    ],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

This is a function decorator for subscribing to a message broker.

PARAMETER DESCRIPTION *broker_args

Positional arguments to be passed to the broker.

TYPE: Any DEFAULT: ()

retry

Whether to retry the subscription if it fails. Can be a boolean or an integer specifying the number of retries.

TYPE: Union[bool, int] DEFAULT: False

dependencies

Sequence of dependencies to be injected into the handler function.

TYPE: Sequence[Depends] DEFAULT: ()

decoder

Custom decoder function to decode the message.

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

parser

Custom parser function to parse the decoded message.

TYPE: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] DEFAULT: None

middlewares

Sequence of middleware functions to be applied to the message.

TYPE: Optional[Sequence[Callable[[StreamMessage[MsgType]], BaseMiddleware]]] DEFAULT: None

filter

Filter function to filter the messages to be processed.

TYPE: Filter[StreamMessage[MsgType]] DEFAULT: lambda : not processed

_raw

Whether to return the raw message instead of the processed message.

TYPE: bool DEFAULT: False

_get_dependant

Optional parameter to get the dependant object.

TYPE: Optional[Any] DEFAULT: None

**broker_kwargs

Keyword arguments to be passed to the broker.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Callable[[Union[Callable[P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable object that can be used as a decorator for a handler function.

RAISES DESCRIPTION RuntimeWarning

If the broker is already running.

Source code in faststream/broker/core/abc.py
@abstractmethod\ndef subscriber(  # type: ignore[return]\n    self,\n    *broker_args: Any,\n    retry: Union[bool, int] = False,\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                BaseMiddleware,\n            ]\n        ]\n    ] = None,\n    filter: Filter[StreamMessage[MsgType]] = lambda m: not m.processed,\n    _raw: bool = False,\n    _get_dependant: Optional[Any] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [\n        Union[\n            Callable[P_HandlerParams, T_HandlerReturn],\n            HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n        ]\n    ],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"This is a function decorator for subscribing to a message broker.\n\n    Args:\n        *broker_args: Positional arguments to be passed to the broker.\n        retry: Whether to retry the subscription if it fails. Can be a boolean or an integer specifying the number of retries.\n        dependencies: Sequence of dependencies to be injected into the handler function.\n        decoder: Custom decoder function to decode the message.\n        parser: Custom parser function to parse the decoded message.\n        middlewares: Sequence of middleware functions to be applied to the message.\n        filter: Filter function to filter the messages to be processed.\n        _raw: Whether to return the raw message instead of the processed message.\n        _get_dependant: Optional parameter to get the dependant object.\n        **broker_kwargs: Keyword arguments to be passed to the broker.\n\n    Returns:\n        A callable object that can be used as a decorator for a handler function.\n\n    Raises:\n        RuntimeWarning: If the broker is already running.\n\n    \"\"\"\n    if self.started and not is_test_env():  # pragma: no cover\n        warnings.warn(\n            \"You are trying to register `handler` with already running broker\\n\"  # noqa: E501\n            \"It has no effect until broker restarting.\",  # noqa: E501\n            category=RuntimeWarning,\n            stacklevel=1,\n        )\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/extend_dependencies/","title":"extend_dependencies","text":"","boost":0.5},{"location":"api/faststream/broker/core/abc/extend_dependencies/#faststream.broker.core.abc.extend_dependencies","title":"faststream.broker.core.abc.extend_dependencies","text":"
extend_dependencies(\n    extra: Sequence[CallModel[Any, Any]],\n    dependant: CallModel[Any, Any],\n) -> CallModel[Any, Any]\n

Extends the dependencies of a function or FastAPI dependency.

PARAMETER DESCRIPTION extra

Additional dependencies to be added.

TYPE: Sequence[CallModel[Any, Any]]

dependant

The function or FastAPI dependency whose dependencies will be extended.

TYPE: CallModel[Any, Any]

RETURNS DESCRIPTION CallModel[Any, Any]

The updated function or FastAPI dependency.

Source code in faststream/broker/core/abc.py
def extend_dependencies(\n    extra: Sequence[CallModel[Any, Any]], dependant: CallModel[Any, Any]\n) -> CallModel[Any, Any]:\n    \"\"\"Extends the dependencies of a function or FastAPI dependency.\n\n    Args:\n        extra: Additional dependencies to be added.\n        dependant: The function or FastAPI dependency whose dependencies will be extended.\n\n    Returns:\n        The updated function or FastAPI dependency.\n\n    \"\"\"\n    if isinstance(dependant, CallModel):\n        dependant.extra_dependencies = (*dependant.extra_dependencies, *extra)\n    else:  # FastAPI dependencies\n        dependant.dependencies.extend(extra)\n    return dependant\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/","title":"BrokerAsyncUsecase","text":"","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase","title":"faststream.broker.core.asyncronous.BrokerAsyncUsecase","text":"
BrokerAsyncUsecase(\n    *args: Any,\n    apply_types: bool = True,\n    validate: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[\n        str\n    ] = \"%(asctime)s %(levelname)s - %(message)s\",\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    middlewares: Optional[\n        Sequence[Callable[[MsgType], BaseMiddleware]]\n    ] = None,\n    graceful_timeout: Optional[float] = None,\n    **kwargs: Any\n)\n

Bases: BrokerUsecase[MsgType, ConnectionType]

A class representing a broker async usecase.

METHOD DESCRIPTION start

Abstract method to start the broker async usecase.

_connect

Any) : Abstract method to connect to the broker.

_close

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) : Abstract method to close the connection to the broker.

close

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) : Close the connection to the broker.

_process_message

Callable[[StreamMessage[MsgType]], Awaitable[T_HandlerReturn]], watcher: BaseWatcher) : Abstract method to process a message.

publish

SendableMessage, *args: Any, reply_to: str = \"\", rpc: bool = False, rpc_timeout: Optional[float]

Initialize the class.

PARAMETER DESCRIPTION *args

Variable length arguments

TYPE: Any DEFAULT: ()

apply_types

Whether to apply types or not

TYPE: bool DEFAULT: True

validate

Whether to cast types using Pydantic validation.

TYPE: bool DEFAULT: True

logger

Logger object for logging

TYPE: Optional[Logger] DEFAULT: access_logger

log_level

Log level for logging

TYPE: int DEFAULT: INFO

log_fmt

Log format for logging

TYPE: Optional[str] DEFAULT: '%(asctime)s %(levelname)s - %(message)s'

dependencies

Sequence of dependencies

TYPE: Sequence[Depends] DEFAULT: ()

decoder

Custom decoder object

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

parser

Custom parser object

TYPE: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] DEFAULT: None

middlewares

Sequence of middlewares

TYPE: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] DEFAULT: None

**kwargs

Keyword arguments

TYPE: Any DEFAULT: {}

Source code in faststream/broker/core/asyncronous.py
def __init__(\n    self,\n    *args: Any,\n    apply_types: bool = True,\n    validate: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = \"%(asctime)s %(levelname)s - %(message)s\",\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    middlewares: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] = None,\n    graceful_timeout: Optional[float] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        *args: Variable length arguments\n        apply_types: Whether to apply types or not\n        validate: Whether to cast types using Pydantic validation.\n        logger: Logger object for logging\n        log_level: Log level for logging\n        log_fmt: Log format for logging\n        dependencies: Sequence of dependencies\n        decoder: Custom decoder object\n        parser: Custom parser object\n        middlewares: Sequence of middlewares\n        **kwargs: Keyword arguments\n\n    \"\"\"\n    super().__init__(\n        *args,\n        apply_types=apply_types,\n        validate=validate,\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n        dependencies=dependencies,\n        decoder=cast(\n            Optional[AsyncCustomDecoder[StreamMessage[MsgType]]],\n            to_async(decoder) if decoder else None,\n        ),\n        parser=cast(\n            Optional[AsyncCustomParser[MsgType, StreamMessage[MsgType]]],\n            to_async(parser) if parser else None,\n        ),\n        middlewares=middlewares,\n        **kwargs,\n    )\n    self.graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.handlers","title":"handlers instance-attribute","text":"
handlers: Mapping[Any, AsyncHandler[MsgType]]\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.url","title":"url instance-attribute","text":"
url = asyncapi_url or url\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.connect","title":"connect async","text":"
connect(*args: Any, **kwargs: Any) -> ConnectionType\n

Connect to a remote server.

PARAMETER DESCRIPTION *args

Variable length argument list.

TYPE: Any DEFAULT: ()

**kwargs

Arbitrary keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION ConnectionType

The connection object.

Source code in faststream/broker/core/asyncronous.py
async def connect(self, *args: Any, **kwargs: Any) -> ConnectionType:\n    \"\"\"Connect to a remote server.\n\n    Args:\n        *args: Variable length argument list.\n        **kwargs: Arbitrary keyword arguments.\n\n    Returns:\n        The connection object.\n\n    \"\"\"\n    if self._connection is None:\n        _kwargs = self._resolve_connection_kwargs(*args, **kwargs)\n        self._connection = await self._connect(**_kwargs)\n    return self._connection\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.publish","title":"publish abstractmethod async","text":"
publish(\n    message: SendableMessage,\n    *args: Any,\n    reply_to: str = \"\",\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

*args

Additional arguments.

TYPE: Any DEFAULT: ()

reply_to

The reply-to address for the message.

TYPE: str DEFAULT: ''

rpc

Whether the message is for RPC.

TYPE: bool DEFAULT: False

rpc_timeout

The timeout for RPC.

TYPE: Optional[float] DEFAULT: None

raise_timeout

Whether to raise an exception on timeout.

TYPE: bool DEFAULT: False

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
@abstractmethod\nasync def publish(\n    self,\n    message: SendableMessage,\n    *args: Any,\n    reply_to: str = \"\",\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        *args: Additional arguments.\n        reply_to: The reply-to address for the message.\n        rpc: Whether the message is for RPC.\n        rpc_timeout: The timeout for RPC.\n        raise_timeout: Whether to raise an exception on timeout.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.publisher","title":"publisher abstractmethod","text":"
publisher(\n    key: Any, publisher: BasePublisher[MsgType]\n) -> BasePublisher[MsgType]\n

Publishes a publisher.

PARAMETER DESCRIPTION key

The key associated with the publisher.

TYPE: Any

publisher

The publisher to be published.

TYPE: BasePublisher[MsgType]

RETURNS DESCRIPTION BasePublisher[MsgType]

The published publisher.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/abc.py
@abstractmethod\ndef publisher(\n    self,\n    key: Any,\n    publisher: BasePublisher[MsgType],\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a publisher.\n\n    Args:\n        key: The key associated with the publisher.\n        publisher: The publisher to be published.\n\n    Returns:\n        The published publisher.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    self._publishers = {**self._publishers, key: publisher}\n    return publisher\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.start","title":"start abstractmethod async","text":"
start() -> None\n
Source code in faststream/broker/core/asyncronous.py
@abstractmethod\nasync def start(self) -> None:\n    super()._abc_start()\n    for h in self.handlers.values():\n        for f, _, _, _, _, _ in h.calls:\n            f.refresh(with_mock=False)\n    await self.connect()\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.subscriber","title":"subscriber abstractmethod","text":"
subscriber(\n    *broker_args: Any,\n    retry: Union[bool, int] = False,\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    middlewares: Optional[\n        Sequence[Callable[[MsgType], BaseMiddleware]]\n    ] = None,\n    filter: Filter[StreamMessage[MsgType]] = default_filter,\n    _raw: bool = False,\n    _get_dependant: Optional[Any] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [\n        Union[\n            Callable[P_HandlerParams, T_HandlerReturn],\n            HandlerCallWrapper[\n                MsgType, P_HandlerParams, T_HandlerReturn\n            ],\n        ]\n    ],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function decorator for subscribing to a message broker.

PARAMETER DESCRIPTION *broker_args

Positional arguments to be passed to the message broker.

TYPE: Any DEFAULT: ()

retry

Whether to retry the subscription if it fails. Can be a boolean or an integer specifying the number of retries.

TYPE: Union[bool, int] DEFAULT: False

dependencies

Sequence of dependencies to be injected into the decorated function.

TYPE: Sequence[Depends] DEFAULT: ()

decoder

Custom decoder function for decoding the message.

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

parser

Custom parser function for parsing the decoded message.

TYPE: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] DEFAULT: None

middlewares

Sequence of middleware functions to be applied to the message.

TYPE: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] DEFAULT: None

filter

Filter function for filtering the messages to be processed.

TYPE: Filter[StreamMessage[MsgType]] DEFAULT: default_filter

_raw

Whether to return the raw message instead of the processed result.

TYPE: bool DEFAULT: False

_get_dependant

Optional argument to get the dependant object.

TYPE: Optional[Any] DEFAULT: None

RETURNS DESCRIPTION Callable[[Union[Callable[P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable decorator that wraps the decorated function and handles the subscription.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/core/asyncronous.py
@override\n@abstractmethod\ndef subscriber(  # type: ignore[override,return]\n    self,\n    *broker_args: Any,\n    retry: Union[bool, int] = False,\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    middlewares: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] = None,\n    filter: Filter[StreamMessage[MsgType]] = default_filter,\n    _raw: bool = False,\n    _get_dependant: Optional[Any] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [\n        Union[\n            Callable[P_HandlerParams, T_HandlerReturn],\n            HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n        ]\n    ],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function decorator for subscribing to a message broker.\n\n    Args:\n        *broker_args: Positional arguments to be passed to the message broker.\n        retry: Whether to retry the subscription if it fails. Can be a boolean or an integer specifying the number of retries.\n        dependencies: Sequence of dependencies to be injected into the decorated function.\n        decoder: Custom decoder function for decoding the message.\n        parser: Custom parser function for parsing the decoded message.\n        middlewares: Sequence of middleware functions to be applied to the message.\n        filter: Filter function for filtering the messages to be processed.\n        _raw: Whether to return the raw message instead of the processed result.\n        _get_dependant: Optional argument to get the dependant object.\n\n    Returns:\n        A callable decorator that wraps the decorated function and handles the subscription.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    super().subscriber()\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/default_filter/","title":"default_filter","text":"","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/default_filter/#faststream.broker.core.asyncronous.default_filter","title":"faststream.broker.core.asyncronous.default_filter async","text":"
default_filter(msg: StreamMessage[Any]) -> bool\n

A function to filter stream messages.

PARAMETER DESCRIPTION msg

A stream message object

RETURNS DESCRIPTION bool

True if the message has not been processed, False otherwise

Source code in faststream/broker/core/asyncronous.py
async def default_filter(msg: StreamMessage[Any]) -> bool:\n    \"\"\"A function to filter stream messages.\n\n    Args:\n        msg : A stream message object\n\n    Returns:\n        True if the message has not been processed, False otherwise\n\n    \"\"\"\n    return not msg.processed\n
","boost":0.5},{"location":"api/faststream/broker/core/mixins/LoggingMixin/","title":"LoggingMixin","text":"","boost":0.5},{"location":"api/faststream/broker/core/mixins/LoggingMixin/#faststream.broker.core.mixins.LoggingMixin","title":"faststream.broker.core.mixins.LoggingMixin","text":"
LoggingMixin(\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[\n        str\n    ] = \"%(asctime)s %(levelname)s - %(message)s\",\n    **kwargs: Any\n)\n

A mixin class for logging.

METHOD DESCRIPTION fmt

getter method for _fmt attribute

_get_log_context

returns a dictionary with log context information

_log

logs a message with optional log level, extra data, and exception info

Initialize the class.

PARAMETER DESCRIPTION *args

Variable length argument list

TYPE: Any DEFAULT: ()

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: access_logger

log_level

Log level (default: logging.INFO)

TYPE: int DEFAULT: INFO

log_fmt

Log format (default: \"%(asctime)s %(levelname)s - %(message)s\")

TYPE: Optional[str] DEFAULT: '%(asctime)s %(levelname)s - %(message)s'

**kwargs

Arbitrary keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/mixins.py
def __init__(\n    self,\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = \"%(asctime)s %(levelname)s - %(message)s\",\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        *args: Variable length argument list\n        logger: Optional logger object\n        log_level: Log level (default: logging.INFO)\n        log_fmt: Log format (default: \"%(asctime)s %(levelname)s - %(message)s\")\n        **kwargs: Arbitrary keyword arguments\n\n    Returns:\n        None\n\n    \"\"\"\n    self.logger = logger\n    self.log_level = log_level\n    self._fmt = log_fmt\n    self._message_id_ln = 10\n
","boost":0.5},{"location":"api/faststream/broker/core/mixins/LoggingMixin/#faststream.broker.core.mixins.LoggingMixin.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/broker/core/mixins/LoggingMixin/#faststream.broker.core.mixins.LoggingMixin.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/broker/core/mixins/LoggingMixin/#faststream.broker.core.mixins.LoggingMixin.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/","title":"StreamMessage","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage","title":"faststream.broker.fastapi.StreamMessage","text":"
StreamMessage(\n    *,\n    body: Union[AnyDict, List[Any]],\n    headers: AnyDict,\n    path: AnyDict\n)\n

Bases: Request

A class to represent a stream message.

METHOD DESCRIPTION __init__

initializes the StreamMessage object

get_session

returns a callable function that handles the session of the message

Initialize a class instance.

PARAMETER DESCRIPTION body

The body of the request as a dictionary.

TYPE: Union[AnyDict, List[Any]]

headers

The headers of the request as a dictionary.

TYPE: AnyDict

Source code in faststream/broker/fastapi/route.py
def __init__(\n    self,\n    *,\n    body: Union[AnyDict, List[Any]],\n    headers: AnyDict,\n    path: AnyDict,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        body: The body of the request as a dictionary.\n        headers: The headers of the request as a dictionary.\n\n    Attributes:\n        scope: A dictionary to store the scope of the request.\n        _cookies: A dictionary to store the cookies of the request.\n        _headers: A dictionary to store the headers of the request.\n        _body: A dictionary to store the body of the request.\n        _query_params: A dictionary to store the query parameters of the request.\n\n    \"\"\"\n    self._headers = headers\n    self._body = body\n    self._query_params = path\n\n    self.scope = {\"path_params\": self._query_params}\n    self._cookies = {}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.app","title":"app property","text":"
app: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.auth","title":"auth property","text":"
auth: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.base_url","title":"base_url property","text":"
base_url: URL\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.client","title":"client property","text":"
client: typing.Optional[Address]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.cookies","title":"cookies property","text":"
cookies: typing.Dict[str, str]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.headers","title":"headers property","text":"
headers: Headers\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.method","title":"method property","text":"
method: str\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.path_params","title":"path_params property","text":"
path_params: typing.Dict[str, typing.Any]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.query_params","title":"query_params property","text":"
query_params: QueryParams\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.receive","title":"receive property","text":"
receive: Receive\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.scope","title":"scope instance-attribute","text":"
scope: AnyDict = {'path_params': self._query_params}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.session","title":"session property","text":"
session: typing.Dict[str, typing.Any]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.state","title":"state property","text":"
state: State\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.url","title":"url property","text":"
url: URL\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.user","title":"user property","text":"
user: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.body","title":"body async","text":"
body() -> bytes\n
Source code in starlette/requests.py
async def body(self) -> bytes:\n    if not hasattr(self, \"_body\"):\n        chunks: \"typing.List[bytes]\" = []\n        async for chunk in self.stream():\n            chunks.append(chunk)\n        self._body = b\"\".join(chunks)\n    return self._body\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.close","title":"close async","text":"
close() -> None\n
Source code in starlette/requests.py
async def close(self) -> None:\n    if self._form is not None:\n        await self._form.close()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.form","title":"form","text":"
form(\n    *,\n    max_files: typing.Union[int, float] = 1000,\n    max_fields: typing.Union[int, float] = 1000\n) -> AwaitableOrContextManager[FormData]\n
Source code in starlette/requests.py
def form(\n    self,\n    *,\n    max_files: typing.Union[int, float] = 1000,\n    max_fields: typing.Union[int, float] = 1000,\n) -> AwaitableOrContextManager[FormData]:\n    return AwaitableOrContextManagerWrapper(\n        self._get_form(max_files=max_files, max_fields=max_fields)\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.get_session","title":"get_session classmethod","text":"
get_session(\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[\n    [NativeMessage[Any]], Awaitable[SendableMessage]\n]\n

Creates a session for handling requests.

PARAMETER DESCRIPTION dependant

The dependant object representing the session.

TYPE: Dependant

dependency_overrides_provider

Optional provider for dependency overrides.

TYPE: Optional[Any] DEFAULT: None

RETURNS DESCRIPTION Callable[[StreamMessage[Any]], Awaitable[SendableMessage]]

A callable that takes a native message and returns an awaitable sendable message.

RAISES DESCRIPTION AssertionError

If the dependant call is not defined.

Note

This function is used to create a session for handling requests. It takes a dependant object, which represents the session, and a dependency overrides provider, which allows for overriding dependencies. It returns a callable that takes a native message and returns an awaitable sendable message. The session is created based on the dependant object and the message passed to the callable. The session is then used to call the function obtained from the dependant object, and the result is returned.

Source code in faststream/broker/fastapi/route.py
@classmethod\ndef get_session(\n    cls,\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[[NativeMessage[Any]], Awaitable[SendableMessage]]:\n    \"\"\"Creates a session for handling requests.\n\n    Args:\n        dependant: The dependant object representing the session.\n        dependency_overrides_provider: Optional provider for dependency overrides.\n\n    Returns:\n        A callable that takes a native message and returns an awaitable sendable message.\n\n    Raises:\n        AssertionError: If the dependant call is not defined.\n\n    Note:\n        This function is used to create a session for handling requests. It takes a dependant object, which represents the session, and a dependency overrides provider, which allows for overriding dependencies. It returns a callable that takes a native message and returns an awaitable sendable message. The session is created based on the dependant object and the message passed to the callable. The session is then used to call the function obtained from the dependant object, and the result is returned.\n\n    \"\"\"\n    assert dependant.call  # nosec B101\n\n    func = get_app(dependant, dependency_overrides_provider)\n\n    dependencies_names = tuple(i.name for i in dependant.dependencies)\n\n    first_arg = next(\n        dropwhile(\n            lambda i: i in dependencies_names,\n            inspect.signature(dependant.call).parameters,\n        ),\n        None,\n    )\n\n    async def app(message: NativeMessage[Any]) -> SendableMessage:\n        \"\"\"An asynchronous function that processes an incoming message and returns a sendable message.\n\n        Args:\n            message : The incoming message to be processed\n\n        Returns:\n            The sendable message\n\n        Raises:\n            TypeError: If the body of the message is not a dictionary\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        body = message.decoded_body\n\n        fastapi_body: Union[AnyDict, List[Any]]\n        if first_arg is not None:\n            if isinstance(body, dict):\n                path = fastapi_body = body or {}\n            elif isinstance(body, list):\n                fastapi_body, path = body, {}\n            else:\n                path = fastapi_body = {first_arg: body}\n\n            session = cls(\n                body=fastapi_body,\n                headers=message.headers,\n                path={**path, **message.path},\n            )\n\n        else:\n            session = cls(\n                body={},\n                headers={},\n                path={},\n            )\n\n        return await func(session)\n\n    return app\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.is_disconnected","title":"is_disconnected async","text":"
is_disconnected() -> bool\n
Source code in starlette/requests.py
async def is_disconnected(self) -> bool:\n    if not self._is_disconnected:\n        message: Message = {}\n\n        # If message isn't immediately available, move on\n        with anyio.CancelScope() as cs:\n            cs.cancel()\n            message = await self._receive()\n\n        if message.get(\"type\") == \"http.disconnect\":\n            self._is_disconnected = True\n\n    return self._is_disconnected\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.json","title":"json async","text":"
json() -> typing.Any\n
Source code in starlette/requests.py
async def json(self) -> typing.Any:\n    if not hasattr(self, \"_json\"):\n        body = await self.body()\n        self._json = json.loads(body)\n    return self._json\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.send_push_promise","title":"send_push_promise async","text":"
send_push_promise(path: str) -> None\n
Source code in starlette/requests.py
async def send_push_promise(self, path: str) -> None:\n    if \"http.response.push\" in self.scope.get(\"extensions\", {}):\n        raw_headers: \"typing.List[typing.Tuple[bytes, bytes]]\" = []\n        for name in SERVER_PUSH_HEADERS_TO_COPY:\n            for value in self.headers.getlist(name):\n                raw_headers.append(\n                    (name.encode(\"latin-1\"), value.encode(\"latin-1\"))\n                )\n        await self._send(\n            {\"type\": \"http.response.push\", \"path\": path, \"headers\": raw_headers}\n        )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.stream","title":"stream async","text":"
stream() -> typing.AsyncGenerator[bytes, None]\n
Source code in starlette/requests.py
async def stream(self) -> typing.AsyncGenerator[bytes, None]:\n    if hasattr(self, \"_body\"):\n        yield self._body\n        yield b\"\"\n        return\n    if self._stream_consumed:\n        raise RuntimeError(\"Stream consumed\")\n    self._stream_consumed = True\n    while True:\n        message = await self._receive()\n        if message[\"type\"] == \"http.request\":\n            body = message.get(\"body\", b\"\")\n            if body:\n                yield body\n            if not message.get(\"more_body\", False):\n                break\n        elif message[\"type\"] == \"http.disconnect\":\n            self._is_disconnected = True\n            raise ClientDisconnect()\n    yield b\"\"\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.url_for","title":"url_for","text":"
url_for(__name: str, **path_params: typing.Any) -> URL\n
Source code in starlette/requests.py
def url_for(self, __name: str, **path_params: typing.Any) -> URL:\n    router: Router = self.scope[\"router\"]\n    url_path = router.url_path_for(__name, **path_params)\n    return url_path.make_absolute_url(base_url=self.base_url)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/","title":"StreamRoute","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute","title":"faststream.broker.fastapi.StreamRoute","text":"
StreamRoute(\n    path: Union[NameRequired, str, None],\n    *extra: Union[NameRequired, str],\n    endpoint: Union[\n        Callable[P_HandlerParams, T_HandlerReturn],\n        HandlerCallWrapper[\n            MsgType, P_HandlerParams, T_HandlerReturn\n        ],\n    ],\n    broker: BrokerAsyncUsecase[MsgType, Any],\n    dependencies: Sequence[params.Depends] = (),\n    dependency_overrides_provider: Optional[Any] = None,\n    **handle_kwargs: Any\n)\n

Bases: BaseRoute, Generic[MsgType, P_HandlerParams, T_HandlerReturn]

A class representing a stream route.

Initialize a class instance.

PARAMETER DESCRIPTION path

The path of the instance.

TYPE: Union[NameRequired, str, None]

*extra

Additional arguments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint of the instance.

TYPE: Union[Callable[P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

broker

The broker of the instance.

TYPE: BrokerAsyncUsecase[MsgType, Any]

dependencies

The dependencies of the instance.

TYPE: Sequence[Depends] DEFAULT: ()

dependency_overrides_provider

The provider for dependency overrides.

TYPE: Optional[Any] DEFAULT: None

**handle_kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None.

Source code in faststream/broker/fastapi/route.py
def __init__(\n    self,\n    path: Union[NameRequired, str, None],\n    *extra: Union[NameRequired, str],\n    endpoint: Union[\n        Callable[P_HandlerParams, T_HandlerReturn],\n        HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n    ],\n    broker: BrokerAsyncUsecase[MsgType, Any],\n    dependencies: Sequence[params.Depends] = (),\n    dependency_overrides_provider: Optional[Any] = None,\n    **handle_kwargs: Any,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        path: The path of the instance.\n        *extra: Additional arguments.\n        endpoint: The endpoint of the instance.\n        broker: The broker of the instance.\n        dependencies: The dependencies of the instance.\n        dependency_overrides_provider: The provider for dependency overrides.\n        **handle_kwargs: Additional keyword arguments.\n\n    Returns:\n        None.\n\n    \"\"\"\n    self.path = path or \"\"\n    self.broker = broker\n\n    path_name = self.path if isinstance(self.path, str) else self.path.name\n\n    if isinstance(endpoint, HandlerCallWrapper):\n        orig_call = endpoint._original_call\n    else:\n        orig_call = endpoint\n\n    dependant = get_dependant(\n        path=path_name,\n        call=orig_call,\n    )\n    for depends in dependencies[::-1]:\n        dependant.dependencies.insert(\n            0,\n            get_parameterless_sub_dependant(depends=depends, path=path_name),\n        )\n    self.dependant = dependant\n\n    call = wraps(orig_call)(\n        StreamMessage.get_session(\n            dependant,\n            dependency_overrides_provider,\n        )\n    )\n\n    if isinstance(endpoint, HandlerCallWrapper):\n        endpoint._original_call = call\n        handler = endpoint\n\n    else:\n        handler = call\n\n    self.handler = broker.subscriber(\n        path,\n        *extra,\n        _raw=True,\n        _get_dependant=lambda call: dependant,\n        **handle_kwargs,\n    )(\n        handler  # type: ignore[arg-type]\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.dependant","title":"dependant instance-attribute","text":"
dependant = dependant\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.handler","title":"handler instance-attribute","text":"
handler: HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n] = broker.subscriber(\n    path,\n    *extra,\n    _raw=True,\n    _get_dependant=lambda: dependant,\n    **handle_kwargs\n)(\n    handler\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.path","title":"path instance-attribute","text":"
path = path or ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.handle","title":"handle async","text":"
handle(scope: Scope, receive: Receive, send: Send) -> None\n
Source code in starlette/routing.py
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.matches","title":"matches","text":"
matches(scope: Scope) -> typing.Tuple[Match, Scope]\n
Source code in starlette/routing.py
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/","title":"StreamRouter","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter","title":"faststream.broker.fastapi.StreamRouter","text":"
StreamRouter(\n    *connection_args: Tuple[Any, ...],\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    setup_state: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id),\n    asyncapi_tags: Optional[\n        Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]\n    ] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    **connection_kwars: Any\n)\n

Bases: APIRouter, Generic[MsgType]

A class to route streams.

METHOD DESCRIPTION __init__

initialize the StreamRouter

add_api_mq_route

add a route for API and message queue

subscriber

decorator to define a subscriber

wrap_lifespan

wrap the lifespan of the router

after_startup

decorator to define a function to be executed after startup

publisher

create a publisher for the broker

asyncapi_router

create an APIRouter for AsyncAPI documentation

include_router

include another router in the StreamRouter

_setup_log_context

setup log context for the broker

Initialize an instance of a class.

PARAMETER DESCRIPTION *connection_args

Variable length arguments for the connection

TYPE: Tuple[Any, ...] DEFAULT: ()

prefix

Prefix for the class

TYPE: str DEFAULT: ''

tags

Optional list of tags for the class

TYPE: Optional[List[Union[str, Enum]]] DEFAULT: None

dependencies

Optional sequence of dependencies for the class

TYPE: Optional[Sequence[Depends]] DEFAULT: None

default_response_class

Default response class for the class

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

Optional dictionary of responses for the class

TYPE: Optional[Dict[Union[int, str], AnyDict]] DEFAULT: None

callbacks

Optional list of callbacks for the class

TYPE: Optional[List[BaseRoute]] DEFAULT: None

routes

Optional list of routes for the class

TYPE: Optional[List[BaseRoute]] DEFAULT: None

redirect_slashes

Boolean value indicating whether to redirect slashes

TYPE: bool DEFAULT: True

default

Optional default value for the class

TYPE: Optional[ASGIApp] DEFAULT: None

dependency_overrides_provider

Optional provider for dependency overrides

TYPE: Optional[Any] DEFAULT: None

route_class

Route class for the class

TYPE: Type[APIRoute] DEFAULT: APIRoute

on_startup

Optional sequence of functions to run on startup

TYPE: Optional[Sequence[Callable[[], Any]]] DEFAULT: None

on_shutdown

Optional sequence of functions to run on shutdown

TYPE: Optional[Sequence[Callable[[], Any]]] DEFAULT: None

deprecated

Optional boolean value indicating whether the class is deprecated

TYPE: Optional[bool] DEFAULT: None

include_in_schema

Boolean value indicating whether to include the class in the schema

TYPE: bool DEFAULT: True

setup_state

Boolean value indicating whether to setup state

TYPE: bool DEFAULT: True

lifespan

Optional lifespan for the class

TYPE: Optional[Lifespan[Any]] DEFAULT: None

generate_unique_id_function

Function to generate unique ID for the class

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

asyncapi_tags

Optional sequence of asyncapi tags for the class schema

TYPE: Optional[Sequence[Union[Tag, TagDict]]] DEFAULT: None

Source code in faststream/broker/fastapi/router.py
def __init__(\n    self,\n    *connection_args: Tuple[Any, ...],\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[Sequence[Callable[[], Any]]] = None,\n    on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    setup_state: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n    # AsyncAPI information\n    asyncapi_tags: Optional[Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    **connection_kwars: Any,\n) -> None:\n    \"\"\"Initialize an instance of a class.\n\n    Args:\n        *connection_args: Variable length arguments for the connection\n        prefix: Prefix for the class\n        tags: Optional list of tags for the class\n        dependencies: Optional sequence of dependencies for the class\n        default_response_class: Default response class for the class\n        responses: Optional dictionary of responses for the class\n        callbacks: Optional list of callbacks for the class\n        routes: Optional list of routes for the class\n        redirect_slashes: Boolean value indicating whether to redirect slashes\n        default: Optional default value for the class\n        dependency_overrides_provider: Optional provider for dependency overrides\n        route_class: Route class for the class\n        on_startup: Optional sequence of functions to run on startup\n        on_shutdown: Optional sequence of functions to run on shutdown\n        deprecated: Optional boolean value indicating whether the class is deprecated\n        include_in_schema: Boolean value indicating whether to include the class in the schema\n        setup_state: Boolean value indicating whether to setup state\n        lifespan: Optional lifespan for the class\n        generate_unique_id_function: Function to generate unique ID for the class\n        asyncapi_tags: Optional sequence of asyncapi tags for the class schema\n\n    \"\"\"\n    assert (  # nosec B101\n        self.broker_class\n    ), \"You should specify `broker_class` at your implementation\"\n\n    self.broker = self.broker_class(\n        *connection_args,\n        apply_types=False,\n        tags=asyncapi_tags,\n        **connection_kwars,\n    )\n\n    self.setup_state = setup_state\n\n    # AsyncAPI information\n    # Empty\n    self.terms_of_service = None\n    self.identifier = None\n    self.asyncapi_tags = None\n    self.external_docs = None\n    # parse from FastAPI app on startup\n    self.title = \"\"\n    self.version = \"\"\n    self.description = \"\"\n    self.license = None\n    self.contact = None\n\n    self.schema = None\n\n    super().__init__(\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        routes=routes,\n        redirect_slashes=redirect_slashes,\n        default=default,\n        dependency_overrides_provider=dependency_overrides_provider,\n        route_class=route_class,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n        lifespan=self.wrap_lifespan(lifespan),\n        on_startup=on_startup,\n        on_shutdown=on_shutdown,\n    )\n\n    self.docs_router = self.asyncapi_router(schema_url)\n\n    self._after_startup_hooks = []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.broker","title":"broker instance-attribute","text":"
broker: BrokerAsyncUsecase[\n    MsgType, Any\n] = self.broker_class(\n    *connection_args,\n    apply_types=False,\n    tags=asyncapi_tags,\n    **connection_kwars\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.broker_class","title":"broker_class instance-attribute","text":"
broker_class: Type[BrokerAsyncUsecase[MsgType, Any]]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any\n) -> HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n]\n

Add an API message queue route.

PARAMETER DESCRIPTION path

The path of the route.

TYPE: Union[NameRequired, str]

*extra

Additional path segments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint function to be called for this route.

TYPE: Callable[P_HandlerParams, T_HandlerReturn]

dependencies

The dependencies required by the endpoint function.

TYPE: Sequence[Depends]

**broker_kwargs

Additional keyword arguments to be passed to the broker.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]

The handler call wrapper for the route.

Source code in faststream/broker/fastapi/router.py
def add_api_mq_route(\n    self,\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any,\n) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n    \"\"\"Add an API message queue route.\n\n    Args:\n        path: The path of the route.\n        *extra: Additional path segments.\n        endpoint: The endpoint function to be called for this route.\n        dependencies: The dependencies required by the endpoint function.\n        **broker_kwargs: Additional keyword arguments to be passed to the broker.\n\n    Returns:\n        The handler call wrapper for the route.\n\n    \"\"\"\n    route: StreamRoute[MsgType, P_HandlerParams, T_HandlerReturn] = StreamRoute(\n        path,\n        *extra,\n        endpoint=endpoint,\n        dependencies=dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        broker=self.broker,\n        **broker_kwargs,\n    )\n    self.routes.append(route)\n    return route.handler\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.publisher","title":"publisher","text":"
publisher(\n    queue: Union[NameRequired, str],\n    *publisher_args: Any,\n    **publisher_kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes messages to a queue.

PARAMETER DESCRIPTION queue

The queue to publish the messages to. Can be either a NameRequired object or a string.

TYPE: Union[NameRequired, str]

*publisher_args

Additional arguments to be passed to the publisher.

TYPE: Any DEFAULT: ()

**publisher_kwargs

Additional keyword arguments to be passed to the publisher.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

An instance of BasePublisher that can be used to publish messages to the specified queue.

Source code in faststream/broker/fastapi/router.py
def publisher(\n    self,\n    queue: Union[NameRequired, str],\n    *publisher_args: Any,\n    **publisher_kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes messages to a queue.\n\n    Args:\n        queue: The queue to publish the messages to. Can be either a `NameRequired` object or a string.\n        *publisher_args: Additional arguments to be passed to the publisher.\n        **publisher_kwargs: Additional keyword arguments to be passed to the publisher.\n\n    Returns:\n        An instance of `BasePublisher` that can be used to publish messages to the specified queue.\n\n    \"\"\"\n    return self.broker.publisher(\n        queue,\n        *publisher_args,\n        **publisher_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.subscriber","title":"subscriber","text":"
subscriber(\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function decorator for subscribing to a message queue.

PARAMETER DESCRIPTION path

The path to subscribe to. Can be a string or a NameRequired object.

*extra

Additional path segments. Can be a NameRequired object or a string.

DEFAULT: ()

dependencies

Optional sequence of dependencies.

DEFAULT: None

**broker_kwargs

Additional keyword arguments for the broker.

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable decorator that adds the decorated function as an endpoint for the specified path.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def subscriber(\n    self,\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function decorator for subscribing to a message queue.\n\n    Args:\n        path : The path to subscribe to. Can be a string or a `NameRequired` object.\n        *extra : Additional path segments. Can be a `NameRequired` object or a string.\n        dependencies : Optional sequence of dependencies.\n        **broker_kwargs : Additional keyword arguments for the broker.\n\n    Returns:\n        A callable decorator that adds the decorated function as an endpoint for the specified path.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    def decorator(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n        \"\"\"A decorator function.\n\n        Args:\n            func: The function to be decorated.\n\n        Returns:\n            The decorated function.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        return self.add_api_mq_route(\n            path,\n            *extra,\n            endpoint=func,\n            dependencies=current_dependencies,\n            **broker_kwargs,\n        )\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/context/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/context/Context/#faststream.broker.fastapi.context.Context","title":"faststream.broker.fastapi.context.Context","text":"
Context(name: str) -> Any\n
Source code in faststream/broker/fastapi/context.py
def Context(name: str) -> Any:\n    return params.Depends(\n        lambda: context.resolve(name),\n        use_cache=True,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/","title":"StreamMessage","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage","title":"faststream.broker.fastapi.route.StreamMessage","text":"
StreamMessage(\n    *,\n    body: Union[AnyDict, List[Any]],\n    headers: AnyDict,\n    path: AnyDict\n)\n

Bases: Request

A class to represent a stream message.

METHOD DESCRIPTION __init__

initializes the StreamMessage object

get_session

returns a callable function that handles the session of the message

Initialize a class instance.

PARAMETER DESCRIPTION body

The body of the request as a dictionary.

TYPE: Union[AnyDict, List[Any]]

headers

The headers of the request as a dictionary.

TYPE: AnyDict

Source code in faststream/broker/fastapi/route.py
def __init__(\n    self,\n    *,\n    body: Union[AnyDict, List[Any]],\n    headers: AnyDict,\n    path: AnyDict,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        body: The body of the request as a dictionary.\n        headers: The headers of the request as a dictionary.\n\n    Attributes:\n        scope: A dictionary to store the scope of the request.\n        _cookies: A dictionary to store the cookies of the request.\n        _headers: A dictionary to store the headers of the request.\n        _body: A dictionary to store the body of the request.\n        _query_params: A dictionary to store the query parameters of the request.\n\n    \"\"\"\n    self._headers = headers\n    self._body = body\n    self._query_params = path\n\n    self.scope = {\"path_params\": self._query_params}\n    self._cookies = {}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.app","title":"app property","text":"
app: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.auth","title":"auth property","text":"
auth: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.base_url","title":"base_url property","text":"
base_url: URL\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.client","title":"client property","text":"
client: typing.Optional[Address]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.cookies","title":"cookies property","text":"
cookies: typing.Dict[str, str]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.headers","title":"headers property","text":"
headers: Headers\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.method","title":"method property","text":"
method: str\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.path_params","title":"path_params property","text":"
path_params: typing.Dict[str, typing.Any]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.query_params","title":"query_params property","text":"
query_params: QueryParams\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.receive","title":"receive property","text":"
receive: Receive\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.scope","title":"scope instance-attribute","text":"
scope: AnyDict = {'path_params': self._query_params}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.session","title":"session property","text":"
session: typing.Dict[str, typing.Any]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.state","title":"state property","text":"
state: State\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.url","title":"url property","text":"
url: URL\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.user","title":"user property","text":"
user: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.body","title":"body async","text":"
body() -> bytes\n
Source code in starlette/requests.py
async def body(self) -> bytes:\n    if not hasattr(self, \"_body\"):\n        chunks: \"typing.List[bytes]\" = []\n        async for chunk in self.stream():\n            chunks.append(chunk)\n        self._body = b\"\".join(chunks)\n    return self._body\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.close","title":"close async","text":"
close() -> None\n
Source code in starlette/requests.py
async def close(self) -> None:\n    if self._form is not None:\n        await self._form.close()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.form","title":"form","text":"
form(\n    *,\n    max_files: typing.Union[int, float] = 1000,\n    max_fields: typing.Union[int, float] = 1000\n) -> AwaitableOrContextManager[FormData]\n
Source code in starlette/requests.py
def form(\n    self,\n    *,\n    max_files: typing.Union[int, float] = 1000,\n    max_fields: typing.Union[int, float] = 1000,\n) -> AwaitableOrContextManager[FormData]:\n    return AwaitableOrContextManagerWrapper(\n        self._get_form(max_files=max_files, max_fields=max_fields)\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.get_session","title":"get_session classmethod","text":"
get_session(\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[\n    [NativeMessage[Any]], Awaitable[SendableMessage]\n]\n

Creates a session for handling requests.

PARAMETER DESCRIPTION dependant

The dependant object representing the session.

TYPE: Dependant

dependency_overrides_provider

Optional provider for dependency overrides.

TYPE: Optional[Any] DEFAULT: None

RETURNS DESCRIPTION Callable[[StreamMessage[Any]], Awaitable[SendableMessage]]

A callable that takes a native message and returns an awaitable sendable message.

RAISES DESCRIPTION AssertionError

If the dependant call is not defined.

Note

This function is used to create a session for handling requests. It takes a dependant object, which represents the session, and a dependency overrides provider, which allows for overriding dependencies. It returns a callable that takes a native message and returns an awaitable sendable message. The session is created based on the dependant object and the message passed to the callable. The session is then used to call the function obtained from the dependant object, and the result is returned.

Source code in faststream/broker/fastapi/route.py
@classmethod\ndef get_session(\n    cls,\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[[NativeMessage[Any]], Awaitable[SendableMessage]]:\n    \"\"\"Creates a session for handling requests.\n\n    Args:\n        dependant: The dependant object representing the session.\n        dependency_overrides_provider: Optional provider for dependency overrides.\n\n    Returns:\n        A callable that takes a native message and returns an awaitable sendable message.\n\n    Raises:\n        AssertionError: If the dependant call is not defined.\n\n    Note:\n        This function is used to create a session for handling requests. It takes a dependant object, which represents the session, and a dependency overrides provider, which allows for overriding dependencies. It returns a callable that takes a native message and returns an awaitable sendable message. The session is created based on the dependant object and the message passed to the callable. The session is then used to call the function obtained from the dependant object, and the result is returned.\n\n    \"\"\"\n    assert dependant.call  # nosec B101\n\n    func = get_app(dependant, dependency_overrides_provider)\n\n    dependencies_names = tuple(i.name for i in dependant.dependencies)\n\n    first_arg = next(\n        dropwhile(\n            lambda i: i in dependencies_names,\n            inspect.signature(dependant.call).parameters,\n        ),\n        None,\n    )\n\n    async def app(message: NativeMessage[Any]) -> SendableMessage:\n        \"\"\"An asynchronous function that processes an incoming message and returns a sendable message.\n\n        Args:\n            message : The incoming message to be processed\n\n        Returns:\n            The sendable message\n\n        Raises:\n            TypeError: If the body of the message is not a dictionary\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        body = message.decoded_body\n\n        fastapi_body: Union[AnyDict, List[Any]]\n        if first_arg is not None:\n            if isinstance(body, dict):\n                path = fastapi_body = body or {}\n            elif isinstance(body, list):\n                fastapi_body, path = body, {}\n            else:\n                path = fastapi_body = {first_arg: body}\n\n            session = cls(\n                body=fastapi_body,\n                headers=message.headers,\n                path={**path, **message.path},\n            )\n\n        else:\n            session = cls(\n                body={},\n                headers={},\n                path={},\n            )\n\n        return await func(session)\n\n    return app\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.is_disconnected","title":"is_disconnected async","text":"
is_disconnected() -> bool\n
Source code in starlette/requests.py
async def is_disconnected(self) -> bool:\n    if not self._is_disconnected:\n        message: Message = {}\n\n        # If message isn't immediately available, move on\n        with anyio.CancelScope() as cs:\n            cs.cancel()\n            message = await self._receive()\n\n        if message.get(\"type\") == \"http.disconnect\":\n            self._is_disconnected = True\n\n    return self._is_disconnected\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.json","title":"json async","text":"
json() -> typing.Any\n
Source code in starlette/requests.py
async def json(self) -> typing.Any:\n    if not hasattr(self, \"_json\"):\n        body = await self.body()\n        self._json = json.loads(body)\n    return self._json\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.send_push_promise","title":"send_push_promise async","text":"
send_push_promise(path: str) -> None\n
Source code in starlette/requests.py
async def send_push_promise(self, path: str) -> None:\n    if \"http.response.push\" in self.scope.get(\"extensions\", {}):\n        raw_headers: \"typing.List[typing.Tuple[bytes, bytes]]\" = []\n        for name in SERVER_PUSH_HEADERS_TO_COPY:\n            for value in self.headers.getlist(name):\n                raw_headers.append(\n                    (name.encode(\"latin-1\"), value.encode(\"latin-1\"))\n                )\n        await self._send(\n            {\"type\": \"http.response.push\", \"path\": path, \"headers\": raw_headers}\n        )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.stream","title":"stream async","text":"
stream() -> typing.AsyncGenerator[bytes, None]\n
Source code in starlette/requests.py
async def stream(self) -> typing.AsyncGenerator[bytes, None]:\n    if hasattr(self, \"_body\"):\n        yield self._body\n        yield b\"\"\n        return\n    if self._stream_consumed:\n        raise RuntimeError(\"Stream consumed\")\n    self._stream_consumed = True\n    while True:\n        message = await self._receive()\n        if message[\"type\"] == \"http.request\":\n            body = message.get(\"body\", b\"\")\n            if body:\n                yield body\n            if not message.get(\"more_body\", False):\n                break\n        elif message[\"type\"] == \"http.disconnect\":\n            self._is_disconnected = True\n            raise ClientDisconnect()\n    yield b\"\"\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.url_for","title":"url_for","text":"
url_for(__name: str, **path_params: typing.Any) -> URL\n
Source code in starlette/requests.py
def url_for(self, __name: str, **path_params: typing.Any) -> URL:\n    router: Router = self.scope[\"router\"]\n    url_path = router.url_path_for(__name, **path_params)\n    return url_path.make_absolute_url(base_url=self.base_url)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/","title":"StreamRoute","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute","title":"faststream.broker.fastapi.route.StreamRoute","text":"
StreamRoute(\n    path: Union[NameRequired, str, None],\n    *extra: Union[NameRequired, str],\n    endpoint: Union[\n        Callable[P_HandlerParams, T_HandlerReturn],\n        HandlerCallWrapper[\n            MsgType, P_HandlerParams, T_HandlerReturn\n        ],\n    ],\n    broker: BrokerAsyncUsecase[MsgType, Any],\n    dependencies: Sequence[params.Depends] = (),\n    dependency_overrides_provider: Optional[Any] = None,\n    **handle_kwargs: Any\n)\n

Bases: BaseRoute, Generic[MsgType, P_HandlerParams, T_HandlerReturn]

A class representing a stream route.

Initialize a class instance.

PARAMETER DESCRIPTION path

The path of the instance.

TYPE: Union[NameRequired, str, None]

*extra

Additional arguments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint of the instance.

TYPE: Union[Callable[P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

broker

The broker of the instance.

TYPE: BrokerAsyncUsecase[MsgType, Any]

dependencies

The dependencies of the instance.

TYPE: Sequence[Depends] DEFAULT: ()

dependency_overrides_provider

The provider for dependency overrides.

TYPE: Optional[Any] DEFAULT: None

**handle_kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None.

Source code in faststream/broker/fastapi/route.py
def __init__(\n    self,\n    path: Union[NameRequired, str, None],\n    *extra: Union[NameRequired, str],\n    endpoint: Union[\n        Callable[P_HandlerParams, T_HandlerReturn],\n        HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n    ],\n    broker: BrokerAsyncUsecase[MsgType, Any],\n    dependencies: Sequence[params.Depends] = (),\n    dependency_overrides_provider: Optional[Any] = None,\n    **handle_kwargs: Any,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        path: The path of the instance.\n        *extra: Additional arguments.\n        endpoint: The endpoint of the instance.\n        broker: The broker of the instance.\n        dependencies: The dependencies of the instance.\n        dependency_overrides_provider: The provider for dependency overrides.\n        **handle_kwargs: Additional keyword arguments.\n\n    Returns:\n        None.\n\n    \"\"\"\n    self.path = path or \"\"\n    self.broker = broker\n\n    path_name = self.path if isinstance(self.path, str) else self.path.name\n\n    if isinstance(endpoint, HandlerCallWrapper):\n        orig_call = endpoint._original_call\n    else:\n        orig_call = endpoint\n\n    dependant = get_dependant(\n        path=path_name,\n        call=orig_call,\n    )\n    for depends in dependencies[::-1]:\n        dependant.dependencies.insert(\n            0,\n            get_parameterless_sub_dependant(depends=depends, path=path_name),\n        )\n    self.dependant = dependant\n\n    call = wraps(orig_call)(\n        StreamMessage.get_session(\n            dependant,\n            dependency_overrides_provider,\n        )\n    )\n\n    if isinstance(endpoint, HandlerCallWrapper):\n        endpoint._original_call = call\n        handler = endpoint\n\n    else:\n        handler = call\n\n    self.handler = broker.subscriber(\n        path,\n        *extra,\n        _raw=True,\n        _get_dependant=lambda call: dependant,\n        **handle_kwargs,\n    )(\n        handler  # type: ignore[arg-type]\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.dependant","title":"dependant instance-attribute","text":"
dependant = dependant\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.handler","title":"handler instance-attribute","text":"
handler: HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n] = broker.subscriber(\n    path,\n    *extra,\n    _raw=True,\n    _get_dependant=lambda: dependant,\n    **handle_kwargs\n)(\n    handler\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.path","title":"path instance-attribute","text":"
path = path or ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.handle","title":"handle async","text":"
handle(scope: Scope, receive: Receive, send: Send) -> None\n
Source code in starlette/routing.py
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.matches","title":"matches","text":"
matches(scope: Scope) -> typing.Tuple[Match, Scope]\n
Source code in starlette/routing.py
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/get_app/","title":"get_app","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/route/get_app/#faststream.broker.fastapi.route.get_app","title":"faststream.broker.fastapi.route.get_app","text":"
get_app(\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[\n    [StreamMessage], Coroutine[Any, Any, SendableMessage]\n]\n

Creates a FastAPI application.

PARAMETER DESCRIPTION dependant

The dependant object that defines the endpoint function and its dependencies.

TYPE: Dependant

dependency_overrides_provider

Optional provider for dependency overrides.

TYPE: Optional[Any] DEFAULT: None

RETURNS DESCRIPTION Callable[[StreamMessage], Coroutine[Any, Any, SendableMessage]]

The FastAPI application as a callable that takes a StreamMessage object as input and returns a SendableMessage coroutine.

RAISES DESCRIPTION AssertionError

If the code reaches an unreachable state.

Source code in faststream/broker/fastapi/route.py
def get_app(\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[[StreamMessage], Coroutine[Any, Any, SendableMessage]]:\n    \"\"\"Creates a FastAPI application.\n\n    Args:\n        dependant: The dependant object that defines the endpoint function and its dependencies.\n        dependency_overrides_provider: Optional provider for dependency overrides.\n\n    Returns:\n        The FastAPI application as a callable that takes a StreamMessage object as input and returns a SendableMessage coroutine.\n\n    Raises:\n        AssertionError: If the code reaches an unreachable state.\n\n    \"\"\"\n\n    async def app(request: StreamMessage) -> SendableMessage:\n        \"\"\"Handle an HTTP request and return a response.\n\n        Args:\n            request: The incoming HTTP request.\n\n        Returns:\n            The response to be sent back to the client.\n\n        Raises:\n            AssertionError: If the code reaches an unreachable point.\n\n        \"\"\"\n        async with AsyncExitStack() as stack:\n            request.scope[\"fastapi_astack\"] = stack\n\n            solved_result = await solve_dependencies(\n                request=request,\n                body=request._body,\n                dependant=dependant,\n                dependency_overrides_provider=dependency_overrides_provider,\n            )\n\n            values, errors, _, _2, _3 = solved_result\n            if errors:\n                raise_fastapi_validation_error(errors, request._body)\n\n            return cast(\n                SendableMessage,\n                await run_endpoint_function(\n                    dependant=dependant,\n                    values=values,\n                    is_coroutine=asyncio.iscoroutinefunction(dependant.call),\n                ),\n            )\n\n        raise AssertionError(\"unreachable\")\n\n    return app\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/","title":"StreamRouter","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter","title":"faststream.broker.fastapi.router.StreamRouter","text":"
StreamRouter(\n    *connection_args: Tuple[Any, ...],\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    setup_state: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id),\n    asyncapi_tags: Optional[\n        Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]\n    ] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    **connection_kwars: Any\n)\n

Bases: APIRouter, Generic[MsgType]

A class to route streams.

METHOD DESCRIPTION __init__

initialize the StreamRouter

add_api_mq_route

add a route for API and message queue

subscriber

decorator to define a subscriber

wrap_lifespan

wrap the lifespan of the router

after_startup

decorator to define a function to be executed after startup

publisher

create a publisher for the broker

asyncapi_router

create an APIRouter for AsyncAPI documentation

include_router

include another router in the StreamRouter

_setup_log_context

setup log context for the broker

Initialize an instance of a class.

PARAMETER DESCRIPTION *connection_args

Variable length arguments for the connection

TYPE: Tuple[Any, ...] DEFAULT: ()

prefix

Prefix for the class

TYPE: str DEFAULT: ''

tags

Optional list of tags for the class

TYPE: Optional[List[Union[str, Enum]]] DEFAULT: None

dependencies

Optional sequence of dependencies for the class

TYPE: Optional[Sequence[Depends]] DEFAULT: None

default_response_class

Default response class for the class

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

Optional dictionary of responses for the class

TYPE: Optional[Dict[Union[int, str], AnyDict]] DEFAULT: None

callbacks

Optional list of callbacks for the class

TYPE: Optional[List[BaseRoute]] DEFAULT: None

routes

Optional list of routes for the class

TYPE: Optional[List[BaseRoute]] DEFAULT: None

redirect_slashes

Boolean value indicating whether to redirect slashes

TYPE: bool DEFAULT: True

default

Optional default value for the class

TYPE: Optional[ASGIApp] DEFAULT: None

dependency_overrides_provider

Optional provider for dependency overrides

TYPE: Optional[Any] DEFAULT: None

route_class

Route class for the class

TYPE: Type[APIRoute] DEFAULT: APIRoute

on_startup

Optional sequence of functions to run on startup

TYPE: Optional[Sequence[Callable[[], Any]]] DEFAULT: None

on_shutdown

Optional sequence of functions to run on shutdown

TYPE: Optional[Sequence[Callable[[], Any]]] DEFAULT: None

deprecated

Optional boolean value indicating whether the class is deprecated

TYPE: Optional[bool] DEFAULT: None

include_in_schema

Boolean value indicating whether to include the class in the schema

TYPE: bool DEFAULT: True

setup_state

Boolean value indicating whether to setup state

TYPE: bool DEFAULT: True

lifespan

Optional lifespan for the class

TYPE: Optional[Lifespan[Any]] DEFAULT: None

generate_unique_id_function

Function to generate unique ID for the class

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

asyncapi_tags

Optional sequence of asyncapi tags for the class schema

TYPE: Optional[Sequence[Union[Tag, TagDict]]] DEFAULT: None

Source code in faststream/broker/fastapi/router.py
def __init__(\n    self,\n    *connection_args: Tuple[Any, ...],\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[Sequence[Callable[[], Any]]] = None,\n    on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    setup_state: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n    # AsyncAPI information\n    asyncapi_tags: Optional[Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    **connection_kwars: Any,\n) -> None:\n    \"\"\"Initialize an instance of a class.\n\n    Args:\n        *connection_args: Variable length arguments for the connection\n        prefix: Prefix for the class\n        tags: Optional list of tags for the class\n        dependencies: Optional sequence of dependencies for the class\n        default_response_class: Default response class for the class\n        responses: Optional dictionary of responses for the class\n        callbacks: Optional list of callbacks for the class\n        routes: Optional list of routes for the class\n        redirect_slashes: Boolean value indicating whether to redirect slashes\n        default: Optional default value for the class\n        dependency_overrides_provider: Optional provider for dependency overrides\n        route_class: Route class for the class\n        on_startup: Optional sequence of functions to run on startup\n        on_shutdown: Optional sequence of functions to run on shutdown\n        deprecated: Optional boolean value indicating whether the class is deprecated\n        include_in_schema: Boolean value indicating whether to include the class in the schema\n        setup_state: Boolean value indicating whether to setup state\n        lifespan: Optional lifespan for the class\n        generate_unique_id_function: Function to generate unique ID for the class\n        asyncapi_tags: Optional sequence of asyncapi tags for the class schema\n\n    \"\"\"\n    assert (  # nosec B101\n        self.broker_class\n    ), \"You should specify `broker_class` at your implementation\"\n\n    self.broker = self.broker_class(\n        *connection_args,\n        apply_types=False,\n        tags=asyncapi_tags,\n        **connection_kwars,\n    )\n\n    self.setup_state = setup_state\n\n    # AsyncAPI information\n    # Empty\n    self.terms_of_service = None\n    self.identifier = None\n    self.asyncapi_tags = None\n    self.external_docs = None\n    # parse from FastAPI app on startup\n    self.title = \"\"\n    self.version = \"\"\n    self.description = \"\"\n    self.license = None\n    self.contact = None\n\n    self.schema = None\n\n    super().__init__(\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        routes=routes,\n        redirect_slashes=redirect_slashes,\n        default=default,\n        dependency_overrides_provider=dependency_overrides_provider,\n        route_class=route_class,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n        lifespan=self.wrap_lifespan(lifespan),\n        on_startup=on_startup,\n        on_shutdown=on_shutdown,\n    )\n\n    self.docs_router = self.asyncapi_router(schema_url)\n\n    self._after_startup_hooks = []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.broker","title":"broker instance-attribute","text":"
broker: BrokerAsyncUsecase[\n    MsgType, Any\n] = self.broker_class(\n    *connection_args,\n    apply_types=False,\n    tags=asyncapi_tags,\n    **connection_kwars\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.broker_class","title":"broker_class instance-attribute","text":"
broker_class: Type[BrokerAsyncUsecase[MsgType, Any]]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any\n) -> HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n]\n

Add an API message queue route.

PARAMETER DESCRIPTION path

The path of the route.

TYPE: Union[NameRequired, str]

*extra

Additional path segments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint function to be called for this route.

TYPE: Callable[P_HandlerParams, T_HandlerReturn]

dependencies

The dependencies required by the endpoint function.

TYPE: Sequence[Depends]

**broker_kwargs

Additional keyword arguments to be passed to the broker.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]

The handler call wrapper for the route.

Source code in faststream/broker/fastapi/router.py
def add_api_mq_route(\n    self,\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any,\n) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n    \"\"\"Add an API message queue route.\n\n    Args:\n        path: The path of the route.\n        *extra: Additional path segments.\n        endpoint: The endpoint function to be called for this route.\n        dependencies: The dependencies required by the endpoint function.\n        **broker_kwargs: Additional keyword arguments to be passed to the broker.\n\n    Returns:\n        The handler call wrapper for the route.\n\n    \"\"\"\n    route: StreamRoute[MsgType, P_HandlerParams, T_HandlerReturn] = StreamRoute(\n        path,\n        *extra,\n        endpoint=endpoint,\n        dependencies=dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        broker=self.broker,\n        **broker_kwargs,\n    )\n    self.routes.append(route)\n    return route.handler\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.publisher","title":"publisher","text":"
publisher(\n    queue: Union[NameRequired, str],\n    *publisher_args: Any,\n    **publisher_kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes messages to a queue.

PARAMETER DESCRIPTION queue

The queue to publish the messages to. Can be either a NameRequired object or a string.

TYPE: Union[NameRequired, str]

*publisher_args

Additional arguments to be passed to the publisher.

TYPE: Any DEFAULT: ()

**publisher_kwargs

Additional keyword arguments to be passed to the publisher.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

An instance of BasePublisher that can be used to publish messages to the specified queue.

Source code in faststream/broker/fastapi/router.py
def publisher(\n    self,\n    queue: Union[NameRequired, str],\n    *publisher_args: Any,\n    **publisher_kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes messages to a queue.\n\n    Args:\n        queue: The queue to publish the messages to. Can be either a `NameRequired` object or a string.\n        *publisher_args: Additional arguments to be passed to the publisher.\n        **publisher_kwargs: Additional keyword arguments to be passed to the publisher.\n\n    Returns:\n        An instance of `BasePublisher` that can be used to publish messages to the specified queue.\n\n    \"\"\"\n    return self.broker.publisher(\n        queue,\n        *publisher_args,\n        **publisher_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.subscriber","title":"subscriber","text":"
subscriber(\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function decorator for subscribing to a message queue.

PARAMETER DESCRIPTION path

The path to subscribe to. Can be a string or a NameRequired object.

*extra

Additional path segments. Can be a NameRequired object or a string.

DEFAULT: ()

dependencies

Optional sequence of dependencies.

DEFAULT: None

**broker_kwargs

Additional keyword arguments for the broker.

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable decorator that adds the decorated function as an endpoint for the specified path.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def subscriber(\n    self,\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function decorator for subscribing to a message queue.\n\n    Args:\n        path : The path to subscribe to. Can be a string or a `NameRequired` object.\n        *extra : Additional path segments. Can be a `NameRequired` object or a string.\n        dependencies : Optional sequence of dependencies.\n        **broker_kwargs : Additional keyword arguments for the broker.\n\n    Returns:\n        A callable decorator that adds the decorated function as an endpoint for the specified path.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    def decorator(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n        \"\"\"A decorator function.\n\n        Args:\n            func: The function to be decorated.\n\n        Returns:\n            The decorated function.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        return self.add_api_mq_route(\n            path,\n            *extra,\n            endpoint=func,\n            dependencies=current_dependencies,\n            **broker_kwargs,\n        )\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/","title":"AsyncHandler","text":"","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler","title":"faststream.broker.handler.AsyncHandler","text":"
AsyncHandler(\n    *,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    graceful_timeout: Optional[float] = None\n)\n

Bases: BaseHandler[MsgType]

A class representing an asynchronous handler.

METHOD DESCRIPTION add_call

adds a new call to the list of calls

consume

consumes a message and returns a sendable message

start

starts the handler

close

closes the handler

Source code in faststream/broker/handler.py
def __init__(\n    self,\n    *,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    graceful_timeout: Optional[float] = None,\n) -> None:\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n    )\n    self.lock = MultiLock()\n    self.graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n    parser: CustomParser[MsgType, Any],\n    decoder: CustomDecoder[Any],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    filter: Filter[StreamMessage[MsgType]],\n    middlewares: Optional[\n        Sequence[Callable[[Any], BaseMiddleware]]\n    ]\n) -> None\n

Adds a call to the handler.

PARAMETER DESCRIPTION handler

The handler call wrapper.

TYPE: HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]

parser

The custom parser.

TYPE: CustomParser[MsgType, Any]

decoder

The custom decoder.

TYPE: CustomDecoder[Any]

dependant

The call model.

TYPE: CallModel[P_HandlerParams, T_HandlerReturn]

filter

The filter for stream messages.

TYPE: Filter[StreamMessage[MsgType]]

middlewares

Optional sequence of middlewares.

TYPE: Optional[Sequence[Callable[[Any], BaseMiddleware]]]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n    parser: CustomParser[MsgType, Any],\n    decoder: CustomDecoder[Any],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    filter: Filter[StreamMessage[MsgType]],\n    middlewares: Optional[Sequence[Callable[[Any], BaseMiddleware]]],\n) -> None:\n    \"\"\"Adds a call to the handler.\n\n    Args:\n        handler: The handler call wrapper.\n        parser: The custom parser.\n        decoder: The custom decoder.\n        dependant: The call model.\n        filter: The filter for stream messages.\n        middlewares: Optional sequence of middlewares.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.calls.append(\n        (\n            handler,\n            to_async(filter),\n            to_async(parser) if parser else None,  # type: ignore[arg-type]\n            to_async(decoder) if decoder else None,  # type: ignore[arg-type]\n            middlewares or (),\n            dependant,\n        )\n    )\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.close","title":"close abstractmethod async","text":"
close() -> None\n
Source code in faststream/broker/handler.py
@abstractmethod\nasync def close(self) -> None:\n    self.running = False\n    await self.lock.wait_release(self.graceful_timeout)\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.start","title":"start abstractmethod async","text":"
start() -> None\n
Source code in faststream/broker/handler.py
@abstractmethod\nasync def start(self) -> None:\n    self.running = True\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/","title":"BaseHandler","text":"","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler","title":"faststream.broker.handler.BaseHandler","text":"
BaseHandler(\n    *,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True\n)\n

Bases: AsyncAPIOperation, Generic[MsgType]

A base handler class for asynchronous API operations.

METHOD DESCRIPTION __init__

Initializes the BaseHandler object.

name

Returns the name of the handler.

call_name

Returns the name of the handler call.

description

Returns the description of the handler.

consume

Abstract method to consume a message.

Note: This class inherits from AsyncAPIOperation and is a generic class with type parameter MsgType.

Initialize a new instance of the class.

PARAMETER DESCRIPTION description

Optional description of the instance.

TYPE: Optional[str] DEFAULT: None

title

Optional title of the instance.

TYPE: Optional[str] DEFAULT: None

Source code in faststream/broker/handler.py
def __init__(\n    self,\n    *,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    \"\"\"Initialize a new instance of the class.\n\n    Args:\n        description: Optional description of the instance.\n        title: Optional title of the instance.\n\n    \"\"\"\n    self.calls = []  # type: ignore[assignment]\n    self.global_middlewares = []\n\n    self.log_context_builder = log_context_builder\n    self.running = False\n\n    # AsyncAPI information\n    self._description = description\n    self._title = title\n    self.include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.calls","title":"calls instance-attribute","text":"
calls: Union[\n    List[\n        Tuple[\n            HandlerCallWrapper[\n                MsgType, Any, SendableMessage\n            ],\n            Callable[[StreamMessage[MsgType]], bool],\n            SyncParser[MsgType, StreamMessage[MsgType]],\n            SyncDecoder[StreamMessage[MsgType]],\n            Sequence[Callable[[Any], BaseMiddleware]],\n            CallModel[Any, SendableMessage],\n        ]\n    ],\n    List[\n        Tuple[\n            HandlerCallWrapper[\n                MsgType, Any, SendableMessage\n            ],\n            Callable[\n                [StreamMessage[MsgType]], Awaitable[bool]\n            ],\n            AsyncParser[MsgType, StreamMessage[MsgType]],\n            AsyncDecoder[StreamMessage[MsgType]],\n            Sequence[Callable[[Any], BaseMiddleware]],\n            CallModel[Any, SendableMessage],\n        ]\n    ],\n] = []\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.consume","title":"consume abstractmethod","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/handler.py
@abstractmethod\ndef consume(self, msg: MsgType) -> SendableMessage:\n    \"\"\"Consume a message.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/","title":"MultiLock","text":"","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/#faststream.broker.handler.MultiLock","title":"faststream.broker.handler.MultiLock","text":"
MultiLock()\n
Source code in faststream/broker/handler.py
def __init__(self) -> None:\n    self.queue: \"asyncio.Queue[None]\" = asyncio.Queue()\n
","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/#faststream.broker.handler.MultiLock.empty","title":"empty property","text":"
empty: bool\n
","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/#faststream.broker.handler.MultiLock.qsize","title":"qsize property","text":"
qsize: int\n
","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/#faststream.broker.handler.MultiLock.queue","title":"queue instance-attribute","text":"
queue: asyncio.Queue[None] = asyncio.Queue()\n
","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/#faststream.broker.handler.MultiLock.wait_release","title":"wait_release async","text":"
wait_release(timeout: Optional[float] = None) -> None\n
Source code in faststream/broker/handler.py
async def wait_release(self, timeout: Optional[float] = None) -> None:\n    if timeout:\n        with anyio.move_on_after(timeout):\n            await self.queue.join()\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/","title":"ABCStreamMessage","text":"","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage","title":"faststream.broker.message.ABCStreamMessage dataclass","text":"

Bases: Generic[Msg]

A generic class to represent a stream message.

","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/","title":"StreamMessage","text":"","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage","title":"faststream.broker.message.StreamMessage","text":"

Bases: ABCStreamMessage[Msg]

","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.ack","title":"ack async","text":"
ack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def ack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.nack","title":"nack async","text":"
nack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def nack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.reject","title":"reject async","text":"
reject(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def reject(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/","title":"SyncStreamMessage","text":"","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage","title":"faststream.broker.message.SyncStreamMessage","text":"

Bases: ABCStreamMessage[Msg]

","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.ack","title":"ack","text":"
ack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
def ack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.nack","title":"nack","text":"
nack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
def nack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.reject","title":"reject","text":"
reject(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
def reject(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/","title":"BaseMiddleware","text":"","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware","title":"faststream.broker.middlewares.BaseMiddleware","text":"
BaseMiddleware(msg: Any)\n

A base middleware class.

METHOD DESCRIPTION on_receive

Called when a message is received.

after_processed

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) -> Optional[bool]: Called after processing a message.

__aenter__

Called when entering a context.

__aexit__

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) -> Optional[bool]: Called when exiting a context.

on_consume

DecodedMessage) -> DecodedMessage: Called before consuming a message.

after_consume

Optional[Exception]) -> None: Called after consuming a message.

consume_scope

DecodedMessage) -> AsyncIterator[DecodedMessage]: Context manager for consuming a message.

on_publish

SendableMessage) -> SendableMessage: Called before publishing a message.

after_publish

Optional[Exception]) -> None: Asynchronous function to handle the after publish event.

Initialize the class.

PARAMETER DESCRIPTION msg

Any message to be stored.

TYPE: Any

Source code in faststream/broker/middlewares.py
def __init__(self, msg: Any) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        msg: Any message to be stored.\n    \"\"\"\n    self.msg = msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.msg","title":"msg instance-attribute","text":"
msg = msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.after_consume","title":"after_consume async","text":"
after_consume(err: Optional[Exception]) -> None\n

A function to handle the result of consuming a resource asynchronously.

PARAMETER DESCRIPTION err

Optional exception that occurred during consumption

RAISES DESCRIPTION err

If an exception occurred during consumption

Source code in faststream/broker/middlewares.py
async def after_consume(self, err: Optional[Exception]) -> None:\n    \"\"\"A function to handle the result of consuming a resource asynchronously.\n\n    Args:\n        err : Optional exception that occurred during consumption\n\n    Raises:\n        err : If an exception occurred during consumption\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.after_processed","title":"after_processed async","text":"
after_processed(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> Optional[bool]\n

Asynchronously called after processing.

PARAMETER DESCRIPTION exc_type

Optional exception type

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

Optional exception value

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

Optional traceback

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION Optional[bool]

Optional boolean value indicating whether the processing was successful or not.

Source code in faststream/broker/middlewares.py
async def after_processed(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> Optional[bool]:\n    \"\"\"Asynchronously called after processing.\n\n    Args:\n        exc_type: Optional exception type\n        exc_val: Optional exception value\n        exec_tb: Optional traceback\n\n    Returns:\n        Optional boolean value indicating whether the processing was successful or not.\n    \"\"\"\n    return False\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.after_publish","title":"after_publish async","text":"
after_publish(err: Optional[Exception]) -> None\n

Asynchronous function to handle the after publish event.

PARAMETER DESCRIPTION err

Optional exception that occurred during the publish

TYPE: Optional[Exception]

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION Exception

If an error occurred during the publish

Source code in faststream/broker/middlewares.py
async def after_publish(self, err: Optional[Exception]) -> None:\n    \"\"\"Asynchronous function to handle the after publish event.\n\n    Args:\n        err: Optional exception that occurred during the publish\n\n    Returns:\n        None\n\n    Raises:\n        Exception: If an error occurred during the publish\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.consume_scope","title":"consume_scope async","text":"
consume_scope(\n    msg: DecodedMessage,\n) -> AsyncIterator[DecodedMessage]\n

Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.

PARAMETER DESCRIPTION msg

The decoded message to consume.

TYPE: DecodedMessage

YIELDS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RETURNS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RAISES DESCRIPTION Exception

If an error occurs while consuming the message.

AsyncIterator

An asynchronous iterator that yields decoded messages.

Note

This function is an async function.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def consume_scope(self, msg: DecodedMessage) -> AsyncIterator[DecodedMessage]:\n    \"\"\"Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.\n\n    Args:\n        msg: The decoded message to consume.\n\n    Yields:\n        An asynchronous iterator of decoded messages.\n\n    Returns:\n        An asynchronous iterator of decoded messages.\n\n    Raises:\n        Exception: If an error occurs while consuming the message.\n\n    AsyncIterator:\n        An asynchronous iterator that yields decoded messages.\n\n    Note:\n        This function is an async function.\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_consume(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_consume(err)\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.on_consume","title":"on_consume async","text":"
on_consume(msg: DecodedMessage) -> DecodedMessage\n

Asynchronously consumes a message.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: DecodedMessage

RETURNS DESCRIPTION DecodedMessage

The consumed message.

Source code in faststream/broker/middlewares.py
async def on_consume(self, msg: DecodedMessage) -> DecodedMessage:\n    \"\"\"Asynchronously consumes a message.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The consumed message.\n    \"\"\"\n    return msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.on_publish","title":"on_publish async","text":"
on_publish(msg: SendableMessage) -> SendableMessage\n

Asynchronously handle a publish event.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

RETURNS DESCRIPTION SendableMessage

The published message.

Source code in faststream/broker/middlewares.py
async def on_publish(self, msg: SendableMessage) -> SendableMessage:\n    \"\"\"Asynchronously handle a publish event.\n\n    Args:\n        msg: The message to be published.\n\n    Returns:\n        The published message.\n    \"\"\"\n    return msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.on_receive","title":"on_receive async","text":"
on_receive() -> None\n
Source code in faststream/broker/middlewares.py
async def on_receive(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.publish_scope","title":"publish_scope async","text":"
publish_scope(\n    msg: SendableMessage,\n) -> AsyncIterator[SendableMessage]\n

Publish a message and return an async iterator.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

YIELDS DESCRIPTION AsyncIterator[SendableMessage]

A sendable message.

RETURNS DESCRIPTION AsyncIterator[SendableMessage]

An async iterator of sendable messages.

RAISES DESCRIPTION Exception

If an error occurs during publishing.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def publish_scope(\n    self, msg: SendableMessage\n) -> AsyncIterator[SendableMessage]:\n    \"\"\"Publish a message and return an async iterator.\n\n    Args:\n        msg: The message to be published.\n\n    Yields:\n        A sendable message.\n\n    Returns:\n        An async iterator of sendable messages.\n\n    Raises:\n        Exception: If an error occurs during publishing.\n\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_publish(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_publish(err)\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/","title":"CriticalLogMiddleware","text":"","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware","title":"faststream.broker.middlewares.CriticalLogMiddleware","text":"
CriticalLogMiddleware(\n    logger: Optional[logging.Logger], log_level: int\n)\n

Bases: BaseMiddleware

A middleware class for logging critical errors.

PARAMETER DESCRIPTION logger

The logger object to use for logging

TYPE: Optional[Logger]

METHOD DESCRIPTION __call__

Any) -> Self: Returns the middleware instance

after_processed

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) -> bool: Logs critical errors if they occur and returns True

Initialize the class.

PARAMETER DESCRIPTION logger

an instance of the logging.Logger class

TYPE: Optional[Logger]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/middlewares.py
def __init__(\n    self,\n    logger: Optional[logging.Logger],\n    log_level: int,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        logger: an instance of the logging.Logger class\n\n    Returns:\n        None\n    \"\"\"\n    self.logger = logger\n    self.log_level = log_level\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.msg","title":"msg instance-attribute","text":"
msg = msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.after_consume","title":"after_consume async","text":"
after_consume(err: Optional[Exception]) -> None\n

A function to handle the result of consuming a resource asynchronously.

PARAMETER DESCRIPTION err

Optional exception that occurred during consumption

RAISES DESCRIPTION err

If an exception occurred during consumption

Source code in faststream/broker/middlewares.py
async def after_consume(self, err: Optional[Exception]) -> None:\n    \"\"\"A function to handle the result of consuming a resource asynchronously.\n\n    Args:\n        err : Optional exception that occurred during consumption\n\n    Raises:\n        err : If an exception occurred during consumption\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.after_processed","title":"after_processed async","text":"
after_processed(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> bool\n

Asynchronously called after processing.

PARAMETER DESCRIPTION exc_type

Type of the exception raised during processing.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

Value of the exception raised during processing.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

Traceback of the exception raised during processing.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION bool

True if the method is successfully executed.

TYPE: bool

Source code in faststream/broker/middlewares.py
async def after_processed(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> bool:\n    \"\"\"Asynchronously called after processing.\n\n    Args:\n        exc_type (Optional[Type[BaseException]]): Type of the exception raised during processing.\n        exc_val (Optional[BaseException]): Value of the exception raised during processing.\n        exec_tb (Optional[TracebackType]): Traceback of the exception raised during processing.\n\n    Returns:\n        bool: True if the method is successfully executed.\n    \"\"\"\n    if self.logger is not None:\n        c = context.get_local(\"log_context\")\n\n        if exc_type and exc_val:\n            self.logger.error(\n                f\"{exc_type.__name__}: {exc_val}\",\n                exc_info=exc_val,\n                extra=c,\n            )\n\n        self.logger.log(self.log_level, \"Processed\", extra=c)\n    return True\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.after_publish","title":"after_publish async","text":"
after_publish(err: Optional[Exception]) -> None\n

Asynchronous function to handle the after publish event.

PARAMETER DESCRIPTION err

Optional exception that occurred during the publish

TYPE: Optional[Exception]

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION Exception

If an error occurred during the publish

Source code in faststream/broker/middlewares.py
async def after_publish(self, err: Optional[Exception]) -> None:\n    \"\"\"Asynchronous function to handle the after publish event.\n\n    Args:\n        err: Optional exception that occurred during the publish\n\n    Returns:\n        None\n\n    Raises:\n        Exception: If an error occurred during the publish\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.consume_scope","title":"consume_scope async","text":"
consume_scope(\n    msg: DecodedMessage,\n) -> AsyncIterator[DecodedMessage]\n

Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.

PARAMETER DESCRIPTION msg

The decoded message to consume.

TYPE: DecodedMessage

YIELDS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RETURNS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RAISES DESCRIPTION Exception

If an error occurs while consuming the message.

AsyncIterator

An asynchronous iterator that yields decoded messages.

Note

This function is an async function.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def consume_scope(self, msg: DecodedMessage) -> AsyncIterator[DecodedMessage]:\n    \"\"\"Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.\n\n    Args:\n        msg: The decoded message to consume.\n\n    Yields:\n        An asynchronous iterator of decoded messages.\n\n    Returns:\n        An asynchronous iterator of decoded messages.\n\n    Raises:\n        Exception: If an error occurs while consuming the message.\n\n    AsyncIterator:\n        An asynchronous iterator that yields decoded messages.\n\n    Note:\n        This function is an async function.\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_consume(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_consume(err)\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.on_consume","title":"on_consume async","text":"
on_consume(msg: DecodedMessage) -> DecodedMessage\n
Source code in faststream/broker/middlewares.py
async def on_consume(self, msg: DecodedMessage) -> DecodedMessage:\n    if self.logger is not None:\n        c = context.get_local(\"log_context\")\n        self.logger.log(self.log_level, \"Received\", extra=c)\n\n    return await super().on_consume(msg)\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.on_publish","title":"on_publish async","text":"
on_publish(msg: SendableMessage) -> SendableMessage\n

Asynchronously handle a publish event.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

RETURNS DESCRIPTION SendableMessage

The published message.

Source code in faststream/broker/middlewares.py
async def on_publish(self, msg: SendableMessage) -> SendableMessage:\n    \"\"\"Asynchronously handle a publish event.\n\n    Args:\n        msg: The message to be published.\n\n    Returns:\n        The published message.\n    \"\"\"\n    return msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.on_receive","title":"on_receive async","text":"
on_receive() -> None\n
Source code in faststream/broker/middlewares.py
async def on_receive(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.publish_scope","title":"publish_scope async","text":"
publish_scope(\n    msg: SendableMessage,\n) -> AsyncIterator[SendableMessage]\n

Publish a message and return an async iterator.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

YIELDS DESCRIPTION AsyncIterator[SendableMessage]

A sendable message.

RETURNS DESCRIPTION AsyncIterator[SendableMessage]

An async iterator of sendable messages.

RAISES DESCRIPTION Exception

If an error occurs during publishing.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def publish_scope(\n    self, msg: SendableMessage\n) -> AsyncIterator[SendableMessage]:\n    \"\"\"Publish a message and return an async iterator.\n\n    Args:\n        msg: The message to be published.\n\n    Yields:\n        A sendable message.\n\n    Returns:\n        An async iterator of sendable messages.\n\n    Raises:\n        Exception: If an error occurs during publishing.\n\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_publish(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_publish(err)\n
","boost":0.5},{"location":"api/faststream/broker/parsers/decode_message/","title":"decode_message","text":"","boost":0.5},{"location":"api/faststream/broker/parsers/decode_message/#faststream.broker.parsers.decode_message","title":"faststream.broker.parsers.decode_message","text":"
decode_message(\n    message: StreamMessage[Any],\n) -> DecodedMessage\n

Decodes a message.

PARAMETER DESCRIPTION message

The message to decode.

TYPE: StreamMessage[Any]

RETURNS DESCRIPTION DecodedMessage

The decoded message.

RAISES DESCRIPTION JSONDecodeError

If the message body cannot be decoded as JSON.

Source code in faststream/broker/parsers.py
def decode_message(message: StreamMessage[Any]) -> DecodedMessage:\n    \"\"\"Decodes a message.\n\n    Args:\n        message: The message to decode.\n\n    Returns:\n        The decoded message.\n\n    Raises:\n        JSONDecodeError: If the message body cannot be decoded as JSON.\n\n    \"\"\"\n    body: Any = getattr(message, \"body\", message)\n    m: DecodedMessage = body\n\n    if content_type := getattr(message, \"content_type\", None):\n        if ContentTypes.text.value in content_type:\n            m = body.decode()\n        elif ContentTypes.json.value in content_type:  # pragma: no branch\n            m = json.loads(body)\n\n    else:\n        with suppress(json.JSONDecodeError):\n            m = json.loads(body)\n\n    return m\n
","boost":0.5},{"location":"api/faststream/broker/parsers/encode_message/","title":"encode_message","text":"","boost":0.5},{"location":"api/faststream/broker/parsers/encode_message/#faststream.broker.parsers.encode_message","title":"faststream.broker.parsers.encode_message","text":"
encode_message(\n    msg: SendableMessage,\n) -> Tuple[bytes, Optional[ContentType]]\n

Encodes a message.

PARAMETER DESCRIPTION msg

The message to be encoded.

TYPE: SendableMessage

RETURNS DESCRIPTION Tuple[bytes, Optional[ContentType]]

A tuple containing the encoded message as bytes and the content type of the message.

Source code in faststream/broker/parsers.py
def encode_message(msg: SendableMessage) -> Tuple[bytes, Optional[ContentType]]:\n    \"\"\"Encodes a message.\n\n    Args:\n        msg: The message to be encoded.\n\n    Returns:\n        A tuple containing the encoded message as bytes and the content type of the message.\n\n    \"\"\"\n    if msg is None:\n        return b\"\", None\n\n    if isinstance(msg, bytes):\n        return msg, None\n\n    if isinstance(msg, str):\n        return msg.encode(), ContentTypes.text.value\n\n    return (\n        dump_json(msg).encode(),\n        ContentTypes.json.value,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/parsers/resolve_custom_func/","title":"resolve_custom_func","text":"","boost":0.5},{"location":"api/faststream/broker/parsers/resolve_custom_func/#faststream.broker.parsers.resolve_custom_func","title":"faststream.broker.parsers.resolve_custom_func","text":"
resolve_custom_func(\n    custom_func: Optional[\n        Union[\n            CustomDecoder[StreamMsg],\n            CustomParser[MsgType, StreamMsg],\n        ]\n    ],\n    default_func: Union[\n        Decoder[StreamMsg], Parser[MsgType, StreamMsg]\n    ],\n) -> Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]]\n

Resolve a custom function.

PARAMETER DESCRIPTION custom_func

Optional custom function of type CustomDecoder or CustomParser.

TYPE: Optional[Union[CustomDecoder[StreamMsg], CustomParser[MsgType, StreamMsg]]]

default_func

Default function of type Decoder or Parser.

TYPE: Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]]

RETURNS DESCRIPTION Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]]

The resolved function of type Decoder or Parser.

Source code in faststream/broker/parsers.py
def resolve_custom_func(  # type: ignore[misc]\n    custom_func: Optional[\n        Union[CustomDecoder[StreamMsg], CustomParser[MsgType, StreamMsg]]\n    ],\n    default_func: Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]],\n) -> Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]]:\n    \"\"\"Resolve a custom function.\n\n    Args:\n        custom_func: Optional custom function of type CustomDecoder or CustomParser.\n        default_func: Default function of type Decoder or Parser.\n\n    Returns:\n        The resolved function of type Decoder or Parser.\n\n    \"\"\"\n    if custom_func is None:\n        return default_func\n\n    original_params = inspect.signature(custom_func).parameters\n    if len(original_params) == 1:\n        return cast(Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]], custom_func)\n\n    else:\n        name = tuple(original_params.items())[1][0]\n        return partial(custom_func, **{name: default_func})  # type: ignore\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/","title":"BasePublisher","text":"","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher","title":"faststream.broker.publisher.BasePublisher dataclass","text":"

Bases: AsyncAPIOperation, Generic[MsgType]

A base class for publishers in an asynchronous API.

METHOD DESCRIPTION description

returns the description of the publisher

__call__

decorator to register a function as a handler for the publisher

publish

publishes a message with optional correlation ID

RAISES DESCRIPTION NotImplementedError

if the publish method is not implemented.

","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.publish","title":"publish abstractmethod async","text":"
publish(\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

correlation_id

Optional correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/publisher.py
@abstractmethod\nasync def publish(\n    self,\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        correlation_id: Optional correlation ID for the message.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/","title":"BaseWatcher","text":"","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher","title":"faststream.broker.push_back_watcher.BaseWatcher","text":"
BaseWatcher(\n    max_tries: int = 0, logger: Optional[Logger] = None\n)\n

Bases: ABC

A base class for a watcher.

PARAMETER DESCRIPTION max_tries

maximum number of tries allowed (default=0)

DEFAULT: 0

logger

logger object (optional)

DEFAULT: None

METHOD DESCRIPTION add

add a message to the watcher

is_max

check if the maximum number of tries has been reached for a message

remove

remove a message from the watcher

Initialize the class.

PARAMETER DESCRIPTION max_tries

Maximum number of tries allowed

TYPE: int DEFAULT: 0

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented in the subclass.

Source code in faststream/broker/push_back_watcher.py
def __init__(\n    self,\n    max_tries: int = 0,\n    logger: Optional[Logger] = None,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        max_tries: Maximum number of tries allowed\n        logger: Optional logger object\n\n    Raises:\n        NotImplementedError: If the method is not implemented in the subclass.\n\n    \"\"\"\n    self.logger = logger\n    self.max_tries = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher.max_tries","title":"max_tries instance-attribute","text":"
max_tries: int = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher.add","title":"add abstractmethod","text":"
add(message_id: str) -> None\n

Add a message.

PARAMETER DESCRIPTION message_id

ID of the message to be added

TYPE: str

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/push_back_watcher.py
@abstractmethod\ndef add(self, message_id: str) -> None:\n    \"\"\"Add a message.\n\n    Args:\n        message_id: ID of the message to be added\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher.is_max","title":"is_max abstractmethod","text":"
is_max(message_id: str) -> bool\n

Check if the given message ID is the maximum.

PARAMETER DESCRIPTION message_id

The ID of the message to check.

TYPE: str

RETURNS DESCRIPTION bool

True if the given message ID is the maximum, False otherwise.

RAISES DESCRIPTION NotImplementedError

This method is meant to be overridden by subclasses.

Source code in faststream/broker/push_back_watcher.py
@abstractmethod\ndef is_max(self, message_id: str) -> bool:\n    \"\"\"Check if the given message ID is the maximum.\n\n    Args:\n        message_id: The ID of the message to check.\n\n    Returns:\n        True if the given message ID is the maximum, False otherwise.\n\n    Raises:\n        NotImplementedError: This method is meant to be overridden by subclasses.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher.remove","title":"remove abstractmethod","text":"
remove(message_id: str) -> None\n

Remove a message.

PARAMETER DESCRIPTION message_id

ID of the message to be removed

TYPE: str

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/push_back_watcher.py
@abstractmethod\ndef remove(self, message_id: str) -> None:\n    \"\"\"Remove a message.\n\n    Args:\n        message_id: ID of the message to be removed\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/","title":"CounterWatcher","text":"","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher","title":"faststream.broker.push_back_watcher.CounterWatcher","text":"
CounterWatcher(\n    max_tries: int = 3, logger: Optional[Logger] = None\n)\n

Bases: BaseWatcher

A class to watch and track the count of messages.

PARAMETER DESCRIPTION max_tries

int - maximum number of tries allowed

DEFAULT: 3

logger

Optional[Logger] - logger object for logging messages

DEFAULT: None

METHOD DESCRIPTION add

str) -> None - adds a message to the counter

is_max

str) -> bool - checks if the count of a message has reached the maximum tries

remove

str) -> None - removes a message from the counter

Initialize the class.

PARAMETER DESCRIPTION max_tries

maximum number of tries

TYPE: int DEFAULT: 3

logger

logger object (default: None)

TYPE: Optional[Logger] DEFAULT: None

Source code in faststream/broker/push_back_watcher.py
def __init__(\n    self,\n    max_tries: int = 3,\n    logger: Optional[Logger] = None,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        max_tries (int): maximum number of tries\n        logger (Optional[Logger]): logger object (default: None)\n\n    \"\"\"\n    super().__init__(logger=logger, max_tries=max_tries)\n    self.memory = Counter()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.max_tries","title":"max_tries instance-attribute","text":"
max_tries: int = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.memory","title":"memory instance-attribute","text":"
memory: CounterType[str] = Counter()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.add","title":"add","text":"
add(message_id: str) -> None\n

Increments the count of a message in the memory.

PARAMETER DESCRIPTION message_id

The ID of the message to be incremented.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def add(self, message_id: str) -> None:\n    \"\"\"Increments the count of a message in the memory.\n\n    Args:\n        message_id: The ID of the message to be incremented.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.memory[message_id] += 1\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.is_max","title":"is_max","text":"
is_max(message_id: str) -> bool\n

Check if the number of tries for a message has exceeded the maximum allowed tries.

PARAMETER DESCRIPTION message_id

The ID of the message

TYPE: str

RETURNS DESCRIPTION bool

True if the number of tries has exceeded the maximum allowed tries, False otherwise

Source code in faststream/broker/push_back_watcher.py
def is_max(self, message_id: str) -> bool:\n    \"\"\"Check if the number of tries for a message has exceeded the maximum allowed tries.\n\n    Args:\n        message_id: The ID of the message\n\n    Returns:\n        True if the number of tries has exceeded the maximum allowed tries, False otherwise\n\n    \"\"\"\n    is_max = self.memory[message_id] > self.max_tries\n    if self.logger is not None:\n        if is_max:\n            self.logger.error(f\"Already retried {self.max_tries} times. Skipped.\")\n        else:\n            self.logger.error(\"Error is occured. Pushing back to queue.\")\n    return is_max\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.remove","title":"remove","text":"
remove(message: str) -> None\n

Remove a message from memory.

PARAMETER DESCRIPTION message

The message to be removed.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def remove(self, message: str) -> None:\n    \"\"\"Remove a message from memory.\n\n    Args:\n        message: The message to be removed.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.memory[message] = 0\n    self.memory += Counter()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/","title":"EndlessWatcher","text":"","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher","title":"faststream.broker.push_back_watcher.EndlessWatcher","text":"
EndlessWatcher(\n    max_tries: int = 0, logger: Optional[Logger] = None\n)\n

Bases: BaseWatcher

Initialize the class.

PARAMETER DESCRIPTION max_tries

Maximum number of tries allowed

TYPE: int DEFAULT: 0

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented in the subclass.

Source code in faststream/broker/push_back_watcher.py
def __init__(\n    self,\n    max_tries: int = 0,\n    logger: Optional[Logger] = None,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        max_tries: Maximum number of tries allowed\n        logger: Optional logger object\n\n    Raises:\n        NotImplementedError: If the method is not implemented in the subclass.\n\n    \"\"\"\n    self.logger = logger\n    self.max_tries = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher.max_tries","title":"max_tries instance-attribute","text":"
max_tries: int = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher.add","title":"add","text":"
add(message_id: str) -> None\n

Add a message to the list.

PARAMETER DESCRIPTION message_id

ID of the message to be added

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def add(self, message_id: str) -> None:\n    \"\"\"Add a message to the list.\n\n    Args:\n        message_id: ID of the message to be added\n\n    Returns:\n        None\n\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher.is_max","title":"is_max","text":"
is_max(message_id: str) -> bool\n

Check if a message is the maximum.

PARAMETER DESCRIPTION message_id

ID of the message to check

TYPE: str

RETURNS DESCRIPTION bool

True if the message is the maximum, False otherwise

Source code in faststream/broker/push_back_watcher.py
def is_max(self, message_id: str) -> bool:\n    \"\"\"Check if a message is the maximum.\n\n    Args:\n        message_id: ID of the message to check\n\n    Returns:\n        True if the message is the maximum, False otherwise\n\n    \"\"\"\n    return False\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher.remove","title":"remove","text":"
remove(message_id: str) -> None\n

Remove a message.

PARAMETER DESCRIPTION message_id

The ID of the message to be removed.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def remove(self, message_id: str) -> None:\n    \"\"\"Remove a message.\n\n    Args:\n        message_id: The ID of the message to be removed.\n\n    Returns:\n        None\n\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/","title":"OneTryWatcher","text":"","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher","title":"faststream.broker.push_back_watcher.OneTryWatcher","text":"
OneTryWatcher(\n    max_tries: int = 0, logger: Optional[Logger] = None\n)\n

Bases: BaseWatcher

Initialize the class.

PARAMETER DESCRIPTION max_tries

Maximum number of tries allowed

TYPE: int DEFAULT: 0

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented in the subclass.

Source code in faststream/broker/push_back_watcher.py
def __init__(\n    self,\n    max_tries: int = 0,\n    logger: Optional[Logger] = None,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        max_tries: Maximum number of tries allowed\n        logger: Optional logger object\n\n    Raises:\n        NotImplementedError: If the method is not implemented in the subclass.\n\n    \"\"\"\n    self.logger = logger\n    self.max_tries = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher.max_tries","title":"max_tries instance-attribute","text":"
max_tries: int = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher.add","title":"add","text":"
add(message_id: str) -> None\n

Add a message.

PARAMETER DESCRIPTION message_id

ID of the message to be added

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def add(self, message_id: str) -> None:\n    \"\"\"Add a message.\n\n    Args:\n        message_id: ID of the message to be added\n\n    Returns:\n        None\n\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher.is_max","title":"is_max","text":"
is_max(message_id: str) -> bool\n

Check if the given message ID is the maximum.

PARAMETER DESCRIPTION message_id

The ID of the message to check.

TYPE: str

RETURNS DESCRIPTION bool

True if the given message ID is the maximum, False otherwise.

Source code in faststream/broker/push_back_watcher.py
def is_max(self, message_id: str) -> bool:\n    \"\"\"Check if the given message ID is the maximum.\n\n    Args:\n        message_id: The ID of the message to check.\n\n    Returns:\n        True if the given message ID is the maximum, False otherwise.\n\n    \"\"\"\n    return True\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher.remove","title":"remove","text":"
remove(message_id: str) -> None\n

Remove a message.

PARAMETER DESCRIPTION message_id

ID of the message to be removed

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def remove(self, message_id: str) -> None:\n    \"\"\"Remove a message.\n\n    Args:\n        message_id: ID of the message to be removed\n\n    Returns:\n        None\n\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/WatcherContext/","title":"WatcherContext","text":"","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/WatcherContext/#faststream.broker.push_back_watcher.WatcherContext","title":"faststream.broker.push_back_watcher.WatcherContext","text":"
WatcherContext(\n    message: Union[\n        SyncStreamMessage[MsgType], StreamMessage[MsgType]\n    ],\n    watcher: BaseWatcher,\n    **extra_ack_args: Any\n)\n

A class representing a context for a watcher.

METHOD DESCRIPTION __aenter__

called when entering the context

__aexit__

called when exiting the context

__ack

acknowledges the message

__nack

negatively acknowledges the message

__reject

rejects the message

Initialize a new instance of the class.

PARAMETER DESCRIPTION watcher

An instance of BaseWatcher.

TYPE: BaseWatcher

message

An instance of SyncStreamMessage or StreamMessage.

TYPE: Union[SyncStreamMessage[MsgType], StreamMessage[MsgType]]

**extra_ack_args

Additional arguments for acknowledgement.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/push_back_watcher.py
def __init__(\n    self,\n    message: Union[SyncStreamMessage[MsgType], StreamMessage[MsgType]],\n    watcher: BaseWatcher,\n    **extra_ack_args: Any,\n) -> None:\n    \"\"\"Initialize a new instance of the class.\n\n    Args:\n        watcher: An instance of BaseWatcher.\n        message: An instance of SyncStreamMessage or StreamMessage.\n        **extra_ack_args: Additional arguments for acknowledgement.\n\n    Attributes:\n        watcher: An instance of BaseWatcher.\n        message: An instance of SyncStreamMessage or StreamMessage.\n        extra_ack_args: Additional arguments for acknowledgement.\n\n    \"\"\"\n    self.watcher = watcher\n    self.message = message\n    self.extra_ack_args = extra_ack_args or {}\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/WatcherContext/#faststream.broker.push_back_watcher.WatcherContext.extra_ack_args","title":"extra_ack_args instance-attribute","text":"
extra_ack_args = extra_ack_args or {}\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/WatcherContext/#faststream.broker.push_back_watcher.WatcherContext.message","title":"message instance-attribute","text":"
message = message\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/WatcherContext/#faststream.broker.push_back_watcher.WatcherContext.watcher","title":"watcher instance-attribute","text":"
watcher = watcher\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRoute/","title":"BrokerRoute","text":"","boost":0.5},{"location":"api/faststream/broker/router/BrokerRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/","title":"BrokerRouter","text":"","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter","title":"faststream.broker.router.BrokerRouter","text":"
BrokerRouter(\n    prefix: str = \"\",\n    handlers: Sequence[\n        BrokerRoute[MsgType, SendableMessage]\n    ] = (),\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    include_in_schema: Optional[bool] = None,\n)\n

Bases: Generic[PublisherKeyType, MsgType]

A generic class representing a broker router.

METHOD DESCRIPTION _get_publisher_key

abstract method to get the publisher key

_update_publisher_prefix

abstract method to update the publisher prefix

__init__

constructor method

subscriber

abstract method to define a subscriber

_wrap_subscriber

method to wrap a subscriber function

publisher

abstract method to define a publisher

include_router

method to include a router

include_routers

method to include multiple routers

Initialize a class object.

PARAMETER DESCRIPTION prefix

Prefix for the object.

TYPE: str DEFAULT: ''

handlers

Handlers for the object.

TYPE: Sequence[BrokerRoute[MsgType, SendableMessage]] DEFAULT: ()

dependencies

Dependencies for the object.

TYPE: Sequence[Depends] DEFAULT: ()

middlewares

Middlewares for the object.

TYPE: Optional[Sequence[Callable[[StreamMessage[MsgType]], AsyncContextManager[None]]]] DEFAULT: None

parser

Parser for the object.

TYPE: Optional[CustomParser[MsgType]] DEFAULT: None

decoder

Decoder for the object.

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

Source code in faststream/broker/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[BrokerRoute[MsgType, SendableMessage]] = (),\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    include_in_schema: Optional[bool] = None,\n) -> None:\n    \"\"\"Initialize a class object.\n\n    Args:\n        prefix (str): Prefix for the object.\n        handlers (Sequence[BrokerRoute[MsgType, SendableMessage]]): Handlers for the object.\n        dependencies (Sequence[Depends]): Dependencies for the object.\n        middlewares (Optional[Sequence[Callable[[StreamMessage[MsgType]], AsyncContextManager[None]]]]): Middlewares for the object.\n        parser (Optional[CustomParser[MsgType]]): Parser for the object.\n        decoder (Optional[CustomDecoder[StreamMessage[MsgType]]]): Decoder for the object.\n\n    \"\"\"\n    self.prefix = prefix\n    self.include_in_schema = include_in_schema\n    self._handlers = list(handlers)\n    self._publishers = {}\n    self._dependencies = dependencies\n    self._middlewares = middlewares\n    self._parser = parser\n    self._decoder = decoder\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.subscriber","title":"subscriber abstractmethod","text":"
subscriber(\n    subj: str,\n    *args: Any,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    include_in_schema: Optional[bool] = None,\n    **kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function to subscribe to a subject.

PARAMETER DESCRIPTION subj

subject to subscribe to

*args

additional arguments

DEFAULT: ()

dependencies

sequence of dependencies

DEFAULT: ()

middlewares

optional sequence of middlewares

DEFAULT: None

parser

optional custom parser

DEFAULT: None

decoder

optional custom decoder

DEFAULT: None

**kwargs

additional keyword arguments

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable handler function

RAISES DESCRIPTION NotImplementedError

If the function is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef subscriber(\n    self,\n    subj: str,\n    *args: Any,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    include_in_schema: Optional[bool] = None,\n    **kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function to subscribe to a subject.\n\n    Args:\n        subj : subject to subscribe to\n        *args : additional arguments\n        dependencies : sequence of dependencies\n        middlewares : optional sequence of middlewares\n        parser : optional custom parser\n        decoder : optional custom decoder\n        **kwargs : additional keyword arguments\n\n    Returns:\n        A callable handler function\n\n    Raises:\n        NotImplementedError: If the function is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/schemas/NameRequired/","title":"NameRequired","text":"","boost":0.5},{"location":"api/faststream/broker/schemas/NameRequired/#faststream.broker.schemas.NameRequired","title":"faststream.broker.schemas.NameRequired","text":"
NameRequired(name: str, **kwargs: Any)\n

Bases: BaseModel

A class to represent a required name.

METHOD DESCRIPTION __eq__

object) -> bool: Check if the given value is equal to the current instance.

validate

Type[NameRequiredCls], value: Union[str, NameRequiredCls]) -> NameRequiredCls: Validate the given value and return a NameRequiredCls instance.

validate

Type[NameRequiredCls], value: None) -> None: Validate the given value and return None.

validate

Type[NameRequiredCls], value: Union[str, NameRequiredCls, None]) -> Optional[NameRequiredCls]: Validate the given value and return an optional NameRequiredCls instance.

This is a Python function.

PARAMETER DESCRIPTION name

The name of the object.

TYPE: str

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None.

Source code in faststream/broker/schemas.py
def __init__(self, name: str, **kwargs: Any) -> None:\n    \"\"\"This is a Python function.\n\n    Args:\n        name (str): The name of the object.\n        **kwargs (Any): Additional keyword arguments.\n\n    Returns:\n        None.\n\n    \"\"\"\n    super().__init__(name=name, **kwargs)\n
","boost":0.5},{"location":"api/faststream/broker/schemas/NameRequired/#faststream.broker.schemas.NameRequired.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/broker/schemas/NameRequired/#faststream.broker.schemas.NameRequired.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/broker/schemas/RawDecoced/","title":"RawDecoced","text":"","boost":0.5},{"location":"api/faststream/broker/schemas/RawDecoced/#faststream.broker.schemas.RawDecoced","title":"faststream.broker.schemas.RawDecoced","text":"

Bases: BaseModel

A class to represent a raw decoded message.

","boost":0.5},{"location":"api/faststream/broker/schemas/RawDecoced/#faststream.broker.schemas.RawDecoced.message","title":"message instance-attribute","text":"
message: Union[Json[Any], str]\n
","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/","title":"BaseSecurity","text":"","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/#faststream.security.BaseSecurity","title":"faststream.security.BaseSecurity","text":"
BaseSecurity(\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Base class for defining security configurations.

This class provides a base for defining security configurations for communication with a broker. It allows setting SSL encryption and provides methods to retrieve security requirements and schemas.

PARAMETER DESCRIPTION ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements in the form of a list of dictionaries.

get_schema

Get the security schema as a dictionary.

Source code in faststream/security.py
def __init__(\n    self,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    if ssl_context is not None:\n        use_ssl = True\n\n    self.use_ssl = use_ssl\n    self.ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/#faststream.security.BaseSecurity.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/#faststream.security.BaseSecurity.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/#faststream.security.BaseSecurity.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return []\n
","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/#faststream.security.BaseSecurity.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {}\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/","title":"SASLPlaintext","text":"","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext","title":"faststream.security.SASLPlaintext","text":"
SASLPlaintext(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/PLAINTEXT authentication.

This class defines security configuration for SASL/PLAINTEXT authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/PLAINTEXT authentication.

get_schema

Get the security schema for SASL/PLAINTEXT authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/PLAINTEXT authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/PLAINTEXT authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"user-password\": []}]\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/PLAINTEXT authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/PLAINTEXT authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"user-password\": {\"type\": \"userPassword\"}}\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/","title":"SASLScram256","text":"","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256","title":"faststream.security.SASLScram256","text":"
SASLScram256(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/SCRAM-SHA-256 authentication.

This class defines security configuration for SASL/SCRAM-SHA-256 authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/SCRAM-SHA-256 authentication.

get_schema

Get the security schema for SASL/SCRAM-SHA-256 authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/SCRAM-SHA-256 authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/SCRAM-SHA-256 authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"scram256\": []}]\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/SCRAM-SHA-256 authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/SCRAM-SHA-256 authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"scram256\": {\"type\": \"scramSha256\"}}\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/","title":"SASLScram512","text":"","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512","title":"faststream.security.SASLScram512","text":"
SASLScram512(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/SCRAM-SHA-512 authentication.

This class defines security configuration for SASL/SCRAM-SHA-512 authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/SCRAM-SHA-512 authentication.

get_schema

Get the security schema for SASL/SCRAM-SHA-512 authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/SCRAM-SHA-512 authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/SCRAM-SHA-512 authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"scram512\": []}]\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/SCRAM-SHA-512 authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/SCRAM-SHA-512 authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"scram512\": {\"type\": \"scramSha512\"}}\n
","boost":0.5},{"location":"api/faststream/broker/test/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/broker/test/TestApp/#faststream.broker.test.TestApp","title":"faststream.broker.test.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/broker/test/TestApp/#faststream.broker.test.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/","title":"TestBroker","text":"","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker","title":"faststream.broker.test.TestBroker","text":"
TestBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: Generic[Broker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber abstractmethod staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: Broker, publisher: Any\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/broker/test.py
@staticmethod\n@abstractmethod\ndef create_publisher_fake_subscriber(\n    broker: Broker, publisher: Any\n) -> HandlerCallWrapper[Any, Any, Any]:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.patch_publisher","title":"patch_publisher abstractmethod staticmethod","text":"
patch_publisher(broker: Broker, publisher: Any) -> None\n
Source code in faststream/broker/test.py
@staticmethod\n@abstractmethod\ndef patch_publisher(broker: Broker, publisher: Any) -> None:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber abstractmethod staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: Broker, publisher: Any\n) -> None\n
Source code in faststream/broker/test.py
@staticmethod\n@abstractmethod\ndef remove_publisher_fake_subscriber(broker: Broker, publisher: Any) -> None:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/test/call_handler/","title":"call_handler","text":"","boost":0.5},{"location":"api/faststream/broker/test/call_handler/#faststream.broker.test.call_handler","title":"faststream.broker.test.call_handler async","text":"
call_handler(\n    handler: AsyncHandler[Any],\n    message: Any,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[SendableMessage]\n

Asynchronously call a handler function.

PARAMETER DESCRIPTION handler

The handler function to be called.

TYPE: AsyncHandler[Any]

message

The message to be passed to the handler function.

TYPE: Any

rpc

Whether the call is a remote procedure call (RPC).

TYPE: bool DEFAULT: False

rpc_timeout

The timeout for the RPC, in seconds.

TYPE: Optional[float] DEFAULT: 30.0

raise_timeout

Whether to raise a timeout error if the RPC times out.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION Optional[SendableMessage]

The result of the handler function if rpc is True, otherwise None.

RAISES DESCRIPTION TimeoutError

If the RPC times out and raise_timeout is True.

Source code in faststream/broker/test.py
async def call_handler(\n    handler: AsyncHandler[Any],\n    message: Any,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[SendableMessage]:\n    \"\"\"Asynchronously call a handler function.\n\n    Args:\n        handler: The handler function to be called.\n        message: The message to be passed to the handler function.\n        rpc: Whether the call is a remote procedure call (RPC).\n        rpc_timeout: The timeout for the RPC, in seconds.\n        raise_timeout: Whether to raise a timeout error if the RPC times out.\n\n    Returns:\n        The result of the handler function if `rpc` is True, otherwise None.\n\n    Raises:\n        TimeoutError: If the RPC times out and `raise_timeout` is True.\n\n    \"\"\"\n    with timeout_scope(rpc_timeout, raise_timeout):\n        result = await handler.consume(message)\n\n        if rpc is True:\n            return result\n\n    return None\n
","boost":0.5},{"location":"api/faststream/broker/test/patch_broker_calls/","title":"patch_broker_calls","text":"","boost":0.5},{"location":"api/faststream/broker/test/patch_broker_calls/#faststream.broker.test.patch_broker_calls","title":"faststream.broker.test.patch_broker_calls","text":"
patch_broker_calls(broker: BrokerUsecase[Any, Any]) -> None\n

Patch broker calls.

PARAMETER DESCRIPTION broker

The broker to patch.

TYPE: BrokerUsecase[Any, Any]

RETURNS DESCRIPTION None

None.

Source code in faststream/broker/test.py
def patch_broker_calls(broker: BrokerUsecase[Any, Any]) -> None:\n    \"\"\"Patch broker calls.\n\n    Args:\n        broker: The broker to patch.\n\n    Returns:\n        None.\n\n    \"\"\"\n    broker.middlewares = tuple(\n        filter(  # type: ignore[assignment]\n            lambda x: not isinstance(x, CriticalLogMiddleware),\n            broker.middlewares,\n        )\n    )\n    broker._abc_start()\n\n    for handler in broker.handlers.values():\n        for f, _, _, _, _, _ in handler.calls:\n            f.set_test()\n
","boost":0.5},{"location":"api/faststream/broker/types/AsyncPublisherProtocol/","title":"AsyncPublisherProtocol","text":"","boost":0.5},{"location":"api/faststream/broker/types/AsyncPublisherProtocol/#faststream.broker.types.AsyncPublisherProtocol","title":"faststream.broker.types.AsyncPublisherProtocol","text":"

Bases: Protocol

A protocol for an asynchronous publisher.

METHOD DESCRIPTION publish

SendableMessage, correlation_id: Optional[str] = None, **kwargs: Any) -> Optional[SendableMessage]: Publishes a message asynchronously.

Args: message: The message to be published. correlation_id: The correlation ID for the message (optional). **kwargs: Additional keyword arguments.

Returns: The published message (optional).

","boost":0.5},{"location":"api/faststream/broker/types/AsyncPublisherProtocol/#faststream.broker.types.AsyncPublisherProtocol.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publishes a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

correlation_id

Optional correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message, or None if the message was not published.

Source code in faststream/broker/types.py
async def publish(\n    self,\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publishes a message.\n\n    Args:\n        message: The message to be published.\n        correlation_id: Optional correlation ID for the message.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message, or None if the message was not published.\n\n    \"\"\"\n    ...\n
","boost":0.5},{"location":"api/faststream/broker/utils/change_logger_handlers/","title":"change_logger_handlers","text":"","boost":0.5},{"location":"api/faststream/broker/utils/change_logger_handlers/#faststream.broker.utils.change_logger_handlers","title":"faststream.broker.utils.change_logger_handlers","text":"
change_logger_handlers(\n    logger: logging.Logger, fmt: str\n) -> None\n

Change the formatter of the logger handlers.

PARAMETER DESCRIPTION logger

The logger object.

TYPE: Logger

fmt

The format string for the formatter.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/utils.py
def change_logger_handlers(logger: logging.Logger, fmt: str) -> None:\n    \"\"\"Change the formatter of the logger handlers.\n\n    Args:\n        logger (logging.Logger): The logger object.\n        fmt (str): The format string for the formatter.\n\n    Returns:\n        None\n\n    \"\"\"\n    for handler in getattr(logger, \"handlers\", ()):\n        formatter = handler.formatter\n        if formatter is not None:  # pragma: no branch\n            use_colors = getattr(formatter, \"use_colors\", None)\n            if use_colors is not None:  # pragma: no branch\n                kwargs = {\"use_colors\": use_colors}\n            else:  # pragma: no cover\n                kwargs = {}\n            handler.setFormatter(type(formatter)(fmt, **kwargs))\n
","boost":0.5},{"location":"api/faststream/broker/utils/get_watcher/","title":"get_watcher","text":"","boost":0.5},{"location":"api/faststream/broker/utils/get_watcher/#faststream.broker.utils.get_watcher","title":"faststream.broker.utils.get_watcher","text":"
get_watcher(\n    logger: Optional[logging.Logger],\n    try_number: Union[bool, int] = True,\n) -> BaseWatcher\n

Get a watcher object based on the provided parameters.

PARAMETER DESCRIPTION logger

Optional logger object for logging messages.

TYPE: Optional[Logger]

try_number

Optional parameter to specify the type of watcher. - If set to True, an EndlessWatcher object will be returned. - If set to False, a OneTryWatcher object will be returned. - If set to an integer, a CounterWatcher object with the specified maximum number of tries will be returned.

TYPE: Union[bool, int] DEFAULT: True

RETURNS DESCRIPTION BaseWatcher

A watcher object based on the provided parameters.

Source code in faststream/broker/utils.py
def get_watcher(\n    logger: Optional[logging.Logger],\n    try_number: Union[bool, int] = True,\n) -> BaseWatcher:\n    \"\"\"Get a watcher object based on the provided parameters.\n\n    Args:\n        logger: Optional logger object for logging messages.\n        try_number: Optional parameter to specify the type of watcher.\n            - If set to True, an EndlessWatcher object will be returned.\n            - If set to False, a OneTryWatcher object will be returned.\n            - If set to an integer, a CounterWatcher object with the specified maximum number of tries will be returned.\n\n    Returns:\n        A watcher object based on the provided parameters.\n\n    \"\"\"\n    watcher: Optional[BaseWatcher]\n    if try_number is True:\n        watcher = EndlessWatcher()\n    elif try_number is False:\n        watcher = OneTryWatcher()\n    else:\n        watcher = CounterWatcher(logger=logger, max_tries=try_number)\n    return watcher\n
","boost":0.5},{"location":"api/faststream/broker/utils/set_message_context/","title":"set_message_context","text":"","boost":0.5},{"location":"api/faststream/broker/utils/set_message_context/#faststream.broker.utils.set_message_context","title":"faststream.broker.utils.set_message_context","text":"
set_message_context(\n    func: Callable[\n        [StreamMessage[MsgType]],\n        Awaitable[WrappedReturn[T_HandlerReturn]],\n    ]\n) -> Callable[\n    [StreamMessage[MsgType]],\n    Awaitable[WrappedReturn[T_HandlerReturn]],\n]\n

Sets the message context for a function.

PARAMETER DESCRIPTION func

The function to set the message context for.

TYPE: Callable[[StreamMessage[MsgType]], Awaitable[WrappedReturn[T_HandlerReturn]]]

RETURNS DESCRIPTION Callable[[StreamMessage[MsgType]], Awaitable[WrappedReturn[T_HandlerReturn]]]

The function with the message context set.

Source code in faststream/broker/utils.py
def set_message_context(\n    func: Callable[\n        [StreamMessage[MsgType]],\n        Awaitable[WrappedReturn[T_HandlerReturn]],\n    ],\n) -> Callable[[StreamMessage[MsgType]], Awaitable[WrappedReturn[T_HandlerReturn]]]:\n    \"\"\"Sets the message context for a function.\n\n    Args:\n        func: The function to set the message context for.\n\n    Returns:\n        The function with the message context set.\n\n    \"\"\"\n\n    @wraps(func)\n    async def set_message_wrapper(\n        message: StreamMessage[MsgType],\n    ) -> WrappedReturn[T_HandlerReturn]:\n        \"\"\"Wraps a function that handles a stream message.\n\n        Args:\n            message: The stream message to be handled.\n\n        Returns:\n            The wrapped return value of the handler function.\n\n        \"\"\"\n        with context.scope(\"message\", message):\n            return await func(message)\n\n    return set_message_wrapper\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/FakePublisher/","title":"FakePublisher","text":"","boost":0.5},{"location":"api/faststream/broker/wrapper/FakePublisher/#faststream.broker.wrapper.FakePublisher","title":"faststream.broker.wrapper.FakePublisher","text":"
FakePublisher(\n    method: Callable[..., Awaitable[SendableMessage]]\n)\n

A class to represent a fake publisher.

METHOD DESCRIPTION publish

asynchronously publishes a message with optional correlation ID and additional keyword arguments

Initialize an object.

PARAMETER DESCRIPTION method

A callable that takes any number of arguments and returns an awaitable sendable message.

TYPE: Callable[..., Awaitable[SendableMessage]]

Source code in faststream/broker/wrapper.py
def __init__(self, method: Callable[..., Awaitable[SendableMessage]]) -> None:\n    \"\"\"Initialize an object.\n\n    Args:\n        method: A callable that takes any number of arguments and returns an awaitable sendable message.\n\n    \"\"\"\n    self.method = method\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/FakePublisher/#faststream.broker.wrapper.FakePublisher.method","title":"method instance-attribute","text":"
method = method\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/FakePublisher/#faststream.broker.wrapper.FakePublisher.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

correlation_id

Optional correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message.

Source code in faststream/broker/wrapper.py
async def publish(\n    self,\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        correlation_id: Optional correlation ID for the message.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message.\n\n    \"\"\"\n    return await self.method(message, correlation_id=correlation_id, **kwargs)\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/","title":"HandlerCallWrapper","text":"","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper","title":"faststream.broker.wrapper.HandlerCallWrapper","text":"
HandlerCallWrapper(\n    call: Callable[P_HandlerParams, T_HandlerReturn]\n)\n

Bases: Generic[MsgType, P_HandlerParams, T_HandlerReturn]

A generic class to wrap handler calls.

METHOD DESCRIPTION __new__

Create a new instance of the class

__init__

Initialize the instance

__call__

Call the wrapped handler

set_wrapped

Set the wrapped handler call

call_wrapped

Call the wrapped handler

wait_call

Wait for the handler call to complete

Initialize a handler.

PARAMETER DESCRIPTION call

A callable object that represents the handler function.

TYPE: Callable[P_HandlerParams, T_HandlerReturn]

Source code in faststream/broker/wrapper.py
def __init__(\n    self,\n    call: Callable[P_HandlerParams, T_HandlerReturn],\n) -> None:\n    \"\"\"Initialize a handler.\n\n    Args:\n        call: A callable object that represents the handler function.\n\n    Attributes:\n        _original_call: The original handler function.\n        _wrapped_call: The wrapped handler function.\n        _publishers: A list of publishers.\n        mock: A MagicMock object.\n        __name__: The name of the handler function.\n\n    \"\"\"\n    if not isinstance(call, HandlerCallWrapper):\n        self._original_call = call\n        self._wrapped_call = None\n        self._publishers = []\n\n        self.mock = None\n        self.future = None\n        self.is_test = False\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.future","title":"future instance-attribute","text":"
future: Optional[asyncio.Future[Any]]\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.is_test","title":"is_test instance-attribute","text":"
is_test: bool\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.mock","title":"mock instance-attribute","text":"
mock: Optional[MagicMock]\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.call_wrapped","title":"call_wrapped","text":"
call_wrapped(\n    message: StreamMessage[MsgType],\n) -> Union[\n    Optional[WrappedReturn[T_HandlerReturn]],\n    Awaitable[Optional[WrappedReturn[T_HandlerReturn]]],\n]\n

Calls the wrapped function with the given message.

PARAMETER DESCRIPTION message

The message to be passed to the wrapped function.

TYPE: StreamMessage[MsgType]

RETURNS DESCRIPTION Union[Optional[WrappedReturn[T_HandlerReturn]], Awaitable[Optional[WrappedReturn[T_HandlerReturn]]]]

The result of the wrapped function call.

RAISES DESCRIPTION AssertionError

If set_wrapped has not been called before calling this function.

AssertionError

If the broker has not been started before calling this function.

Source code in faststream/broker/wrapper.py
def call_wrapped(\n    self,\n    message: StreamMessage[MsgType],\n) -> Union[\n    Optional[WrappedReturn[T_HandlerReturn]],\n    Awaitable[Optional[WrappedReturn[T_HandlerReturn]]],\n]:\n    \"\"\"Calls the wrapped function with the given message.\n\n    Args:\n        message: The message to be passed to the wrapped function.\n\n    Returns:\n        The result of the wrapped function call.\n\n    Raises:\n        AssertionError: If `set_wrapped` has not been called before calling this function.\n        AssertionError: If the broker has not been started before calling this function.\n\n    \"\"\"\n    assert self._wrapped_call, \"You should use `set_wrapped` first\"  # nosec B101\n    if self.is_test:\n        assert self.mock  # nosec B101\n        self.mock(message.decoded_body)\n    return self._wrapped_call(message)\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.refresh","title":"refresh","text":"
refresh(with_mock: bool = False) -> None\n
Source code in faststream/broker/wrapper.py
def refresh(self, with_mock: bool = False) -> None:\n    self.future = asyncio.Future()\n    if with_mock and self.mock is not None:\n        self.mock.reset_mock()\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/wrapper.py
def reset_test(self) -> None:\n    self.is_test = False\n    self.mock = None\n    self.future = None\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.set_test","title":"set_test","text":"
set_test() -> None\n
Source code in faststream/broker/wrapper.py
def set_test(self) -> None:\n    self.is_test = True\n    if self.mock is None:\n        self.mock = MagicMock()\n    self.refresh(with_mock=True)\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.set_wrapped","title":"set_wrapped","text":"
set_wrapped(\n    wrapped: WrappedHandlerCall[MsgType, T_HandlerReturn]\n) -> None\n

Set the wrapped handler call.

PARAMETER DESCRIPTION wrapped

The wrapped handler call to set

TYPE: WrappedHandlerCall[MsgType, T_HandlerReturn]

Source code in faststream/broker/wrapper.py
def set_wrapped(\n    self, wrapped: WrappedHandlerCall[MsgType, T_HandlerReturn]\n) -> None:\n    \"\"\"Set the wrapped handler call.\n\n    Args:\n        wrapped: The wrapped handler call to set\n\n    \"\"\"\n    self._wrapped_call = wrapped\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.trigger","title":"trigger","text":"
trigger(\n    result: Any = None,\n    error: Optional[BaseException] = None,\n) -> None\n
Source code in faststream/broker/wrapper.py
def trigger(\n    self,\n    result: Any = None,\n    error: Optional[BaseException] = None,\n) -> None:\n    if not self.is_test:\n        return\n\n    assert (  # nosec B101\n        self.future is not None\n    ), \"You can use this method only with TestClient\"\n\n    if self.future.done():\n        self.future = asyncio.Future()\n\n    if error:\n        self.future.set_exception(error)\n    else:\n        self.future.set_result(result)\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.wait_call","title":"wait_call async","text":"
wait_call(timeout: Optional[float] = None) -> None\n

Waits for a call with an optional timeout.

PARAMETER DESCRIPTION timeout

Optional timeout in seconds

TYPE: Optional[float] DEFAULT: None

RAISES DESCRIPTION AssertionError

If the broker is not started

RETURNS DESCRIPTION None

None

Source code in faststream/broker/wrapper.py
async def wait_call(self, timeout: Optional[float] = None) -> None:\n    \"\"\"Waits for a call with an optional timeout.\n\n    Args:\n        timeout: Optional timeout in seconds\n\n    Raises:\n        AssertionError: If the broker is not started\n\n    Returns:\n        None\n\n    \"\"\"\n    assert (  # nosec B101\n        self.future is not None\n    ), \"You can use this method only with TestClient\"\n    with anyio.fail_after(timeout):\n        await self.future\n
","boost":0.5},{"location":"api/faststream/cli/docs/app/gen/","title":"gen","text":"","boost":0.5},{"location":"api/faststream/cli/docs/app/gen/#faststream.cli.docs.app.gen","title":"faststream.cli.docs.app.gen","text":"
gen(\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] - path to your application\",\n    ),\n    yaml: bool = typer.Option(\n        False,\n        \"--yaml\",\n        is_flag=True,\n        help=\"generate `asyncapi.yaml` schema\",\n    ),\n    out: Optional[str] = typer.Option(\n        None, help=\"output filename\"\n    ),\n) -> None\n

Generate project AsyncAPI schema

Source code in faststream/cli/docs/app.py
@docs_app.command(name=\"gen\")\ndef gen(\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] - path to your application\",\n    ),\n    yaml: bool = typer.Option(\n        False,\n        \"--yaml\",\n        is_flag=True,\n        help=\"generate `asyncapi.yaml` schema\",\n    ),\n    out: Optional[str] = typer.Option(\n        None,\n        help=\"output filename\",\n    ),\n) -> None:\n    \"\"\"Generate project AsyncAPI schema\"\"\"\n    _, app_obj = import_from_string(app)\n    raw_schema = get_app_schema(app_obj)\n\n    if yaml:\n        try:\n            schema = raw_schema.to_yaml()\n        except ImportError as e:  # pragma: no cover\n            typer.echo(INSTALL_YAML, err=True)\n            raise typer.Exit(1) from e\n\n        name = out or \"asyncapi.yaml\"\n\n        with open(name, \"w\") as f:\n            f.write(schema)\n\n    else:\n        schema = raw_schema.to_jsonable()\n        name = out or \"asyncapi.json\"\n\n        with open(name, \"w\") as f:\n            json.dump(schema, f, indent=2)\n\n    typer.echo(f\"Your project AsyncAPI scheme was placed to `{name}`\")\n
","boost":0.5},{"location":"api/faststream/cli/docs/app/serve/","title":"serve","text":"","boost":0.5},{"location":"api/faststream/cli/docs/app/serve/#faststream.cli.docs.app.serve","title":"faststream.cli.docs.app.serve","text":"
serve(\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] or [asyncapi.yaml/.json] - path to your application or documentation\",\n    ),\n    host: str = typer.Option(\n        \"localhost\", help=\"documentation hosting address\"\n    ),\n    port: int = typer.Option(\n        8000, help=\"documentation hosting port\"\n    ),\n    reload: bool = typer.Option(\n        False,\n        \"--reload\",\n        is_flag=True,\n        help=\"Restart documentation at directory files changes\",\n    ),\n) -> None\n

Serve project AsyncAPI schema

Source code in faststream/cli/docs/app.py
@docs_app.command(name=\"serve\")\ndef serve(\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] or [asyncapi.yaml/.json] - path to your application or documentation\",\n    ),\n    host: str = typer.Option(\n        \"localhost\",\n        help=\"documentation hosting address\",\n    ),\n    port: int = typer.Option(\n        8000,\n        help=\"documentation hosting port\",\n    ),\n    reload: bool = typer.Option(\n        False,\n        \"--reload\",\n        is_flag=True,\n        help=\"Restart documentation at directory files changes\",\n    ),\n) -> None:\n    \"\"\"Serve project AsyncAPI schema\"\"\"\n\n    if \":\" in app:\n        module, _ = import_from_string(app)\n\n        module_parent = module.parent\n        extra_extensions: Sequence[str] = ()\n\n    else:\n        module_parent = Path.cwd()\n        schema_filepath = module_parent / app\n        extra_extensions = (schema_filepath.suffix,)\n\n    if reload is True:\n        try:\n            from faststream.cli.supervisors.watchfiles import WatchReloader\n\n        except ImportError:\n            warnings.warn(INSTALL_WATCHFILES, category=ImportWarning, stacklevel=1)\n            _parse_and_serve(app, host, port)\n\n        else:\n            WatchReloader(\n                target=_parse_and_serve,\n                args=(app, host, port),\n                reload_dirs=(str(module_parent),),\n                extra_extensions=extra_extensions,\n            ).run()\n\n    else:\n        _parse_and_serve(app, host, port)\n
","boost":0.5},{"location":"api/faststream/cli/main/main/","title":"main","text":"","boost":0.5},{"location":"api/faststream/cli/main/main/#faststream.cli.main.main","title":"faststream.cli.main.main","text":"
main(\n    version: Optional[bool] = typer.Option(\n        False,\n        \"-v\",\n        \"--version\",\n        callback=version_callback,\n        is_eager=True,\n        help=\"Show current platform, python and FastStream version\",\n    )\n) -> None\n

Generate, run and manage FastStream apps to greater development experience

Source code in faststream/cli/main.py
@cli.callback()\ndef main(\n    version: Optional[bool] = typer.Option(\n        False,\n        \"-v\",\n        \"--version\",\n        callback=version_callback,\n        is_eager=True,\n        help=\"Show current platform, python and FastStream version\",\n    ),\n) -> None:\n    \"\"\"\n    Generate, run and manage FastStream apps to greater development experience\n    \"\"\"\n
","boost":0.5},{"location":"api/faststream/cli/main/run/","title":"run","text":"","boost":0.5},{"location":"api/faststream/cli/main/run/#faststream.cli.main.run","title":"faststream.cli.main.run","text":"
run(\n    ctx: typer.Context,\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] - path to your application\",\n    ),\n    workers: int = typer.Option(\n        1,\n        show_default=False,\n        help=\"Run [workers] applications with process spawning\",\n    ),\n    log_level: LogLevels = typer.Option(\n        LogLevels.info,\n        case_sensitive=False,\n        show_default=False,\n        help=\"[INFO] default\",\n    ),\n    reload: bool = typer.Option(\n        False,\n        \"--reload\",\n        is_flag=True,\n        help=\"Restart app at directory files changes\",\n    ),\n    watch_extensions: List[str] = typer.Option(\n        (),\n        \"--extension\",\n        \"--reload-extension\",\n        \"--reload-ext\",\n        \"--ext\",\n        help=\"List of file extensions to watch by\",\n    ),\n    app_dir: str = typer.Option(\n        \".\",\n        \"--app-dir\",\n        help=\"Look for APP in the specified directory, by adding this to the PYTHONPATH. Defaults to the current working directory.\",\n    ),\n) -> None\n

Run [MODULE:APP] FastStream application

Source code in faststream/cli/main.py
@cli.command(\n    context_settings={\"allow_extra_args\": True, \"ignore_unknown_options\": True}\n)\ndef run(\n    ctx: typer.Context,\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] - path to your application\",\n    ),\n    workers: int = typer.Option(\n        1,\n        show_default=False,\n        help=\"Run [workers] applications with process spawning\",\n    ),\n    log_level: LogLevels = typer.Option(\n        LogLevels.info,\n        case_sensitive=False,\n        show_default=False,\n        help=\"[INFO] default\",\n    ),\n    reload: bool = typer.Option(\n        False,\n        \"--reload\",\n        is_flag=True,\n        help=\"Restart app at directory files changes\",\n    ),\n    watch_extensions: List[str] = typer.Option(\n        (),\n        \"--extension\",\n        \"--reload-extension\",\n        \"--reload-ext\",\n        \"--ext\",\n        help=\"List of file extensions to watch by\",\n    ),\n    app_dir: str = typer.Option(\n        \".\",\n        \"--app-dir\",\n        help=(\n            \"Look for APP in the specified directory, by adding this to the PYTHONPATH.\"\n            \" Defaults to the current working directory.\"\n        ),\n    ),\n) -> None:\n    \"\"\"Run [MODULE:APP] FastStream application\"\"\"\n    if watch_extensions and not reload:\n        typer.echo(\n            \"Extra reload extensions has no effect without `--reload` flag.\"\n            \"\\nProbably, you forgot it?\"\n        )\n\n    app, extra = parse_cli_args(app, *ctx.args)\n    casted_log_level = get_log_level(log_level)\n\n    if app_dir:  # pragma: no branch\n        sys.path.insert(0, app_dir)\n\n    args = (app, extra, casted_log_level)\n\n    if reload and workers > 1:\n        raise ValueError(\"You can't use reload option with multiprocessing\")\n\n    if reload is True:\n        try:\n            from faststream.cli.supervisors.watchfiles import WatchReloader\n        except ImportError:\n            warnings.warn(INSTALL_WATCHFILES, category=ImportWarning, stacklevel=1)\n            _run(*args)\n\n        else:\n            module_path, _ = import_from_string(app)\n\n            WatchReloader(\n                target=_run,\n                args=args,\n                reload_dirs=[str(module_path)] + ([app_dir] if app_dir else []),\n            ).run()\n\n    elif workers > 1:\n        from faststream.cli.supervisors.multiprocess import Multiprocess\n\n        Multiprocess(\n            target=_run,\n            args=(*args, logging.DEBUG),\n            workers=workers,\n        ).run()\n\n    else:\n        _run(*args)\n
","boost":0.5},{"location":"api/faststream/cli/main/version_callback/","title":"version_callback","text":"","boost":0.5},{"location":"api/faststream/cli/main/version_callback/#faststream.cli.main.version_callback","title":"faststream.cli.main.version_callback","text":"
version_callback(version: bool) -> None\n

Callback function for displaying version information.

PARAMETER DESCRIPTION version

If True, display version information

TYPE: bool

RETURNS DESCRIPTION None

None

Source code in faststream/cli/main.py
def version_callback(version: bool) -> None:\n    \"\"\"Callback function for displaying version information.\n\n    Args:\n        version: If True, display version information\n\n    Returns:\n        None\n\n    \"\"\"\n    if version is True:\n        import platform\n\n        typer.echo(\n            \"Running FastStream %s with %s %s on %s\"\n            % (\n                __version__,\n                platform.python_implementation(),\n                platform.python_version(),\n                platform.system(),\n            )\n        )\n\n        raise typer.Exit()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/","title":"BaseReload","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload","title":"faststream.cli.supervisors.basereload.BaseReload","text":"
BaseReload(\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    reload_delay: Optional[float] = 0.5,\n)\n

A base class for implementing a reloader process.

METHOD DESCRIPTION run

Runs the reloader process.

startup

Performs startup operations for the reloader process.

restart

Restarts the process.

shutdown

Shuts down the reloader process.

_stop_process

Stops the spawned process.

_start_process

Starts the spawned process.

should_restart

Determines whether the process should be restarted.

Initialize a class instance.

PARAMETER DESCRIPTION target

The target callable object

TYPE: DecoratedCallable

args

Tuple of arguments to be passed to the target callable

TYPE: Tuple[Any, ...]

reload_delay

Optional delay in seconds before reloading the target callable (default is 0.5 seconds)

TYPE: Optional[float] DEFAULT: 0.5

RETURNS DESCRIPTION None

None

Source code in faststream/cli/supervisors/basereload.py
def __init__(\n    self,\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    reload_delay: Optional[float] = 0.5,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        target: The target callable object\n        args: Tuple of arguments to be passed to the target callable\n        reload_delay: Optional delay in seconds before reloading the target callable (default is 0.5 seconds)\n\n    Returns:\n        None\n\n    \"\"\"\n    self._target = target\n    self._args = args\n\n    self.should_exit = threading.Event()\n    self.pid = os.getpid()\n    self.reload_delay = reload_delay\n\n    set_exit(lambda *_: self.should_exit.set())\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.pid","title":"pid instance-attribute","text":"
pid: int = os.getpid()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.reload_delay","title":"reload_delay instance-attribute","text":"
reload_delay: Optional[float] = reload_delay\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.reloader_name","title":"reloader_name class-attribute instance-attribute","text":"
reloader_name: str = ''\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.should_exit","title":"should_exit instance-attribute","text":"
should_exit: threading.Event = threading.Event()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.restart","title":"restart","text":"
restart() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def restart(self) -> None:\n    self._stop_process()\n    logger.info(\"Process successfully reloaded\")\n    self._process = self._start_process()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.run","title":"run","text":"
run() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def run(self) -> None:\n    self.startup()\n    while not self.should_exit.wait(self.reload_delay):\n        if self.should_restart():  # pragma: no branch\n            self.restart()\n    self.shutdown()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.should_restart","title":"should_restart","text":"
should_restart() -> bool\n
Source code in faststream/cli/supervisors/basereload.py
def should_restart(self) -> bool:\n    raise NotImplementedError(\"Reload strategies should override should_restart()\")\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.shutdown","title":"shutdown","text":"
shutdown() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def shutdown(self) -> None:\n    self._stop_process()\n    logger.info(f\"Stopping reloader process [{self.pid}]\")\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.startup","title":"startup","text":"
startup() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def startup(self) -> None:\n    logger.info(f\"Started reloader process [{self.pid}] using {self.reloader_name}\")\n    self._process = self._start_process()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/","title":"Multiprocess","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess","title":"faststream.cli.supervisors.multiprocess.Multiprocess","text":"
Multiprocess(\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    workers: int,\n)\n

Bases: BaseReload

A class to represent a multiprocess.

METHOD DESCRIPTION startup

starts the parent process and creates worker processes

shutdown

terminates and joins all worker processes, and stops the parent process

Initialize a new instance of the class.

PARAMETER DESCRIPTION target

The target callable object to be executed.

TYPE: DecoratedCallable

args

The arguments to be passed to the target callable.

TYPE: Tuple[Any, ...]

workers

The number of workers to be used.

TYPE: int

RETURNS DESCRIPTION None

None.

Source code in faststream/cli/supervisors/multiprocess.py
def __init__(\n    self,\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    workers: int,\n) -> None:\n    \"\"\"Initialize a new instance of the class.\n\n    Args:\n        target: The target callable object to be executed.\n        args: The arguments to be passed to the target callable.\n        workers: The number of workers to be used.\n\n    Returns:\n        None.\n\n    \"\"\"\n    super().__init__(target, args, None)\n\n    self.workers = workers\n    self.processes: List[SpawnProcess] = []\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.pid","title":"pid instance-attribute","text":"
pid: int = os.getpid()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.processes","title":"processes instance-attribute","text":"
processes: List[SpawnProcess] = []\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.reload_delay","title":"reload_delay instance-attribute","text":"
reload_delay: Optional[float] = reload_delay\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.reloader_name","title":"reloader_name class-attribute instance-attribute","text":"
reloader_name: str = ''\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.should_exit","title":"should_exit instance-attribute","text":"
should_exit: threading.Event = threading.Event()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.workers","title":"workers instance-attribute","text":"
workers = workers\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.restart","title":"restart","text":"
restart() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def restart(self) -> None:\n    self._stop_process()\n    logger.info(\"Process successfully reloaded\")\n    self._process = self._start_process()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.run","title":"run","text":"
run() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def run(self) -> None:\n    self.startup()\n    while not self.should_exit.wait(self.reload_delay):\n        if self.should_restart():  # pragma: no branch\n            self.restart()\n    self.shutdown()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.should_restart","title":"should_restart","text":"
should_restart() -> bool\n
Source code in faststream/cli/supervisors/basereload.py
def should_restart(self) -> bool:\n    raise NotImplementedError(\"Reload strategies should override should_restart()\")\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.shutdown","title":"shutdown","text":"
shutdown() -> None\n
Source code in faststream/cli/supervisors/multiprocess.py
def shutdown(self) -> None:\n    for process in self.processes:\n        process.terminate()\n        logger.info(f\"Stopping child process [{process.pid}]\")\n        process.join()\n\n    logger.info(f\"Stopping parent process [{self.pid}]\")\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.startup","title":"startup","text":"
startup() -> None\n
Source code in faststream/cli/supervisors/multiprocess.py
def startup(self) -> None:\n    logger.info(f\"Started parent process [{self.pid}]\")\n\n    for _ in range(self.workers):\n        process = self._start_process()\n        logger.info(f\"Started child process [{process.pid}]\")\n        self.processes.append(process)\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/get_subprocess/","title":"get_subprocess","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/get_subprocess/#faststream.cli.supervisors.utils.get_subprocess","title":"faststream.cli.supervisors.utils.get_subprocess","text":"
get_subprocess(\n    target: DecoratedCallableNone, args: Any\n) -> SpawnProcess\n

Spawn a subprocess.

PARAMETER DESCRIPTION target

The target function to be executed in the subprocess.

TYPE: DecoratedCallableNone

args

The arguments to be passed to the target function.

TYPE: Any

RETURNS DESCRIPTION SpawnProcess

The spawned subprocess.

RAISES DESCRIPTION OSError

If there is an error getting the file descriptor of sys.stdin.

Source code in faststream/cli/supervisors/utils.py
def get_subprocess(target: DecoratedCallableNone, args: Any) -> SpawnProcess:\n    \"\"\"Spawn a subprocess.\n\n    Args:\n        target: The target function to be executed in the subprocess.\n        args: The arguments to be passed to the target function.\n\n    Returns:\n        The spawned subprocess.\n\n    Raises:\n        OSError: If there is an error getting the file descriptor of sys.stdin.\n\n    \"\"\"\n    stdin_fileno: Optional[int]\n    try:\n        stdin_fileno = sys.stdin.fileno()\n    except OSError:\n        stdin_fileno = None\n\n    return spawn.Process(\n        target=subprocess_started,\n        args=args,\n        kwargs={\"t\": target, \"stdin_fileno\": stdin_fileno},\n    )\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/set_exit/","title":"set_exit","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/set_exit/#faststream.cli.supervisors.utils.set_exit","title":"faststream.cli.supervisors.utils.set_exit","text":"
set_exit(\n    func: Callable[[int, Optional[FrameType]], Any]\n) -> None\n

Set exit handler for signals.

PARAMETER DESCRIPTION func

A callable object that takes an integer and an optional frame type as arguments and returns any value.

TYPE: Callable[[int, Optional[FrameType]], Any]

RETURNS DESCRIPTION None

None

Source code in faststream/cli/supervisors/utils.py
def set_exit(func: Callable[[int, Optional[FrameType]], Any]) -> None:\n    \"\"\"Set exit handler for signals.\n\n    Args:\n        func: A callable object that takes an integer and an optional frame type as arguments and returns any value.\n\n    Returns:\n        None\n\n    \"\"\"\n    for sig in HANDLED_SIGNALS:\n        signal.signal(sig, func)\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/subprocess_started/","title":"subprocess_started","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/subprocess_started/#faststream.cli.supervisors.utils.subprocess_started","title":"faststream.cli.supervisors.utils.subprocess_started","text":"
subprocess_started(\n    *args: Any,\n    t: DecoratedCallableNone,\n    stdin_fileno: Optional[int]\n) -> None\n

Start a subprocess.

PARAMETER DESCRIPTION *args

Arguments to be passed to the subprocess.

TYPE: Any DEFAULT: ()

t

The decorated callable function.

TYPE: DecoratedCallableNone

stdin_fileno

File descriptor for the standard input of the subprocess.

TYPE: Optional[int]

RETURNS DESCRIPTION None

None

Source code in faststream/cli/supervisors/utils.py
def subprocess_started(\n    *args: Any,\n    t: DecoratedCallableNone,\n    stdin_fileno: Optional[int],\n) -> None:\n    \"\"\"Start a subprocess.\n\n    Args:\n        *args: Arguments to be passed to the subprocess.\n        t: The decorated callable function.\n        stdin_fileno: File descriptor for the standard input of the subprocess.\n\n    Returns:\n        None\n\n    \"\"\"\n    if stdin_fileno is not None:  # pragma: no cover\n        sys.stdin = os.fdopen(stdin_fileno)\n    t(*args)\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/ExtendedFilter/","title":"ExtendedFilter","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/ExtendedFilter/#faststream.cli.supervisors.watchfiles.ExtendedFilter","title":"faststream.cli.supervisors.watchfiles.ExtendedFilter","text":"
ExtendedFilter(\n    *,\n    ignore_paths: Optional[\n        Sequence[Union[str, Path]]\n    ] = None,\n    extra_extensions: Sequence[str] = ()\n)\n

Bases: PythonFilter

A class that extends the watchfiles.PythonFilter class.

METHOD DESCRIPTION __init__

Initializes the ExtendedFilter object Args: ignore_paths : Optional sequence of paths to ignore extra_extensions : Sequence of extra extensions to include

Returns: None

Initialize the class.

PARAMETER DESCRIPTION ignore_paths

Optional sequence of paths to ignore.

TYPE: Optional[Sequence[Union[str, Path]]] DEFAULT: None

extra_extensions

Sequence of extra extensions.

TYPE: Sequence[str] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/cli/supervisors/watchfiles.py
def __init__(\n    self,\n    *,\n    ignore_paths: Optional[Sequence[Union[str, Path]]] = None,\n    extra_extensions: Sequence[str] = (),\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        ignore_paths: Optional sequence of paths to ignore.\n        extra_extensions: Sequence of extra extensions.\n\n    Returns:\n        None\n\n    \"\"\"\n    super().__init__(ignore_paths=ignore_paths, extra_extensions=extra_extensions)\n    self.ignore_dirs = self.ignore_dirs + (\n        \"venv\",\n        \"env\",\n        \".github\",\n        \".mypy_cache\",\n        \".pytest_cache\",\n        \".ruff_cache\",\n        \"__pycache__\",\n    )\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/ExtendedFilter/#faststream.cli.supervisors.watchfiles.ExtendedFilter.ignore_dirs","title":"ignore_dirs instance-attribute","text":"
ignore_dirs: Tuple[str, ...] = self.ignore_dirs + (\n    \"venv\",\n    \"env\",\n    \".github\",\n    \".mypy_cache\",\n    \".pytest_cache\",\n    \".ruff_cache\",\n    \"__pycache__\",\n)\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/","title":"WatchReloader","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader","title":"faststream.cli.supervisors.watchfiles.WatchReloader","text":"
WatchReloader(\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    reload_dirs: Sequence[Union[Path, str]],\n    reload_delay: float = 0.3,\n    extra_extensions: Sequence[str] = (),\n)\n

Bases: BaseReload

A class to reload a target function when files in specified directories change.

METHOD DESCRIPTION should_restart

Checks if any files in the watched directories have changed and returns True if a change is detected, False otherwise.

Initialize a WatchFilesReloader object.

PARAMETER DESCRIPTION target

The target callable to be executed.

TYPE: DecoratedCallable

args

The arguments to be passed to the target callable.

TYPE: Tuple[Any, ...]

reload_dirs

A sequence of directories to watch for changes.

TYPE: Sequence[Union[Path, str]]

reload_delay

The delay in seconds between checking for changes. Default is 0.3.

TYPE: float DEFAULT: 0.3

RETURNS DESCRIPTION None

None.

Source code in faststream/cli/supervisors/watchfiles.py
def __init__(\n    self,\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    reload_dirs: Sequence[Union[Path, str]],\n    reload_delay: float = 0.3,\n    extra_extensions: Sequence[str] = (),\n) -> None:\n    \"\"\"Initialize a WatchFilesReloader object.\n\n    Args:\n        target: The target callable to be executed.\n        args: The arguments to be passed to the target callable.\n        reload_dirs: A sequence of directories to watch for changes.\n        reload_delay: The delay in seconds between checking for changes. Default is 0.3.\n\n    Returns:\n        None.\n\n    \"\"\"\n    super().__init__(target, args, reload_delay)\n    self.reloader_name = \"WatchFiles\"\n    self.reload_dirs = reload_dirs\n    self.watcher = watchfiles.watch(\n        *reload_dirs,\n        step=int(reload_delay * 1000),\n        watch_filter=ExtendedFilter(extra_extensions=extra_extensions),\n        stop_event=self.should_exit,\n        yield_on_timeout=True,\n    )\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.pid","title":"pid instance-attribute","text":"
pid: int = os.getpid()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.reload_delay","title":"reload_delay instance-attribute","text":"
reload_delay: Optional[float] = reload_delay\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.reload_dirs","title":"reload_dirs instance-attribute","text":"
reload_dirs = reload_dirs\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.reloader_name","title":"reloader_name instance-attribute","text":"
reloader_name = 'WatchFiles'\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.should_exit","title":"should_exit instance-attribute","text":"
should_exit: threading.Event = threading.Event()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.watcher","title":"watcher instance-attribute","text":"
watcher = watchfiles.watch(\n    *reload_dirs,\n    step=int(reload_delay * 1000),\n    watch_filter=ExtendedFilter(\n        extra_extensions=extra_extensions\n    ),\n    stop_event=self.should_exit,\n    yield_on_timeout=True\n)\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.restart","title":"restart","text":"
restart() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def restart(self) -> None:\n    self._stop_process()\n    logger.info(\"Process successfully reloaded\")\n    self._process = self._start_process()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.run","title":"run","text":"
run() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def run(self) -> None:\n    self.startup()\n    while not self.should_exit.wait(self.reload_delay):\n        if self.should_restart():  # pragma: no branch\n            self.restart()\n    self.shutdown()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.should_restart","title":"should_restart","text":"
should_restart() -> bool\n
Source code in faststream/cli/supervisors/watchfiles.py
def should_restart(self) -> bool:\n    for changes in self.watcher:  # pragma: no branch\n        if changes:  # pragma: no branch\n            unique_paths = {Path(c[1]).name for c in changes}\n            message = \"WatchReloader detected file change in '%s'. Reloading...\"\n            logger.info(message % tuple(unique_paths))\n            return True\n    return False  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.shutdown","title":"shutdown","text":"
shutdown() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def shutdown(self) -> None:\n    self._stop_process()\n    logger.info(f\"Stopping reloader process [{self.pid}]\")\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.startup","title":"startup","text":"
startup() -> None\n
Source code in faststream/cli/supervisors/watchfiles.py
def startup(self) -> None:\n    logger.info(f\"Will watch for changes in these directories: {self.reload_dirs}\")\n    super().startup()\n
","boost":0.5},{"location":"api/faststream/cli/utils/imports/get_app_path/","title":"get_app_path","text":"","boost":0.5},{"location":"api/faststream/cli/utils/imports/get_app_path/#faststream.cli.utils.imports.get_app_path","title":"faststream.cli.utils.imports.get_app_path","text":"
get_app_path(app: str) -> Tuple[Path, str]\n

Get the application path.

PARAMETER DESCRIPTION app

The name of the application in the format \"module:app_name\".

TYPE: str

RETURNS DESCRIPTION Tuple[Path, str]

Tuple[Path, str]: A tuple containing the path to the module and the name of the application.

RAISES DESCRIPTION ValueError

If the given app is not in the format \"module:app_name\".

Source code in faststream/cli/utils/imports.py
def get_app_path(app: str) -> Tuple[Path, str]:\n    \"\"\"Get the application path.\n\n    Args:\n        app (str): The name of the application in the format \"module:app_name\".\n\n    Returns:\n        Tuple[Path, str]: A tuple containing the path to the module and the name of the application.\n\n    Raises:\n        ValueError: If the given app is not in the format \"module:app_name\".\n\n    \"\"\"\n    if \":\" not in app:\n        raise ValueError(f\"{app} is not a FastStream\")\n\n    module, app_name = app.split(\":\", 2)\n\n    mod_path = Path.cwd()\n    for i in module.split(\".\"):\n        mod_path = mod_path / i\n\n    return mod_path, app_name\n
","boost":0.5},{"location":"api/faststream/cli/utils/imports/import_from_string/","title":"import_from_string","text":"","boost":0.5},{"location":"api/faststream/cli/utils/imports/import_from_string/#faststream.cli.utils.imports.import_from_string","title":"faststream.cli.utils.imports.import_from_string","text":"
import_from_string(\n    import_str: str,\n) -> Tuple[Path, FastStream]\n

Import FastStream application from module specified by a string.

PARAMETER DESCRIPTION import_str

A string in the format \":\" specifying the module and faststream application to import.

TYPE: str

RETURNS DESCRIPTION Tuple[Path, FastStream]

Tuple[ModuleType, FastStream]: A tuple containing the imported module and the faststream application.

RAISES DESCRIPTION BadParameter

Raised if the given value is not of type string, if the import string is not in the format \":\", if the module is not found, or if the faststream appliation is not found in the module. Source code in faststream/cli/utils/imports.py

def import_from_string(import_str: str) -> Tuple[Path, FastStream]:\n    \"\"\"\n    Import FastStream application from module specified by a string.\n\n    Parameters:\n        import_str (str): A string in the format \"<module>:<attribute>\" specifying the module and faststream application to import.\n\n    Returns:\n        Tuple[ModuleType, FastStream]: A tuple containing the imported module and the faststream application.\n\n    Raises:\n        typer.BadParameter: Raised if the given value is not of type string, if the import string is not in the format\n            \"<module>:<attribute>\", if the module is not found, or if the faststream appliation is not found in the module.\n    \"\"\"\n    if not isinstance(import_str, str):\n        raise typer.BadParameter(\"Given value is not of type string\")\n\n    module_str, _, attrs_str = import_str.partition(\":\")\n    if not module_str or not attrs_str:\n        raise typer.BadParameter(\n            f'Import string \"{import_str}\" must be in format \"<module>:<attribute>\"'\n        )\n\n    try:\n        module = importlib.import_module(  # nosemgrep: python.lang.security.audit.non-literal-import.non-literal-import\n            module_str\n        )\n\n    except ModuleNotFoundError:\n        module_path, app_name = get_app_path(import_str)\n        instance = try_import_app(module_path, app_name)\n\n    else:\n        attr = module\n        try:\n            for attr_str in attrs_str.split(\".\"):\n                attr = getattr(attr, attr_str)\n            instance = attr  # type: ignore[assignment]\n\n        except AttributeError as e:\n            typer.echo(e, err=True)\n            raise typer.BadParameter(\n                f'Attribute \"{attrs_str}\" not found in module \"{module_str}\".'\n            ) from e\n\n        if module.__file__:\n            module_path = Path(module.__file__).resolve().parent\n        else:\n            module_path = Path.cwd()\n\n    return module_path, instance\n
","boost":0.5},{"location":"api/faststream/cli/utils/imports/import_object/","title":"import_object","text":"","boost":0.5},{"location":"api/faststream/cli/utils/imports/import_object/#faststream.cli.utils.imports.import_object","title":"faststream.cli.utils.imports.import_object","text":"
import_object(module: Path, app: str) -> object\n

Import an object from a module.

PARAMETER DESCRIPTION module

The path to the module file.

TYPE: Path

app

The name of the object to import.

TYPE: str

RETURNS DESCRIPTION object

The imported object.

RAISES DESCRIPTION FileNotFoundError

If the module file is not found.

ValueError

If the module has no loader.

AttributeError

If the object is not found in the module.

Source code in faststream/cli/utils/imports.py
def import_object(module: Path, app: str) -> object:\n    \"\"\"Import an object from a module.\n\n    Args:\n        module: The path to the module file.\n        app: The name of the object to import.\n\n    Returns:\n        The imported object.\n\n    Raises:\n        FileNotFoundError: If the module file is not found.\n        ValueError: If the module has no loader.\n        AttributeError: If the object is not found in the module.\n\n    \"\"\"\n    spec = spec_from_file_location(\n        \"mode\",\n        f\"{module}.py\",\n        submodule_search_locations=[str(module.parent.absolute())],\n    )\n\n    if spec is None:  # pragma: no cover\n        raise FileNotFoundError(module)\n\n    mod = module_from_spec(spec)\n    loader = spec.loader\n\n    if loader is None:  # pragma: no cover\n        raise ValueError(f\"{spec} has no loader\")\n\n    loader.exec_module(mod)\n\n    try:\n        obj = getattr(mod, app)\n    except AttributeError as e:\n        raise FileNotFoundError(module) from e\n\n    return obj\n
","boost":0.5},{"location":"api/faststream/cli/utils/imports/try_import_app/","title":"try_import_app","text":"","boost":0.5},{"location":"api/faststream/cli/utils/imports/try_import_app/#faststream.cli.utils.imports.try_import_app","title":"faststream.cli.utils.imports.try_import_app","text":"
try_import_app(module: Path, app: str) -> FastStream\n

Tries to import a FastStream app from a module.

PARAMETER DESCRIPTION module

Path to the module containing the app.

TYPE: Path

app

Name of the FastStream app.

TYPE: str

RETURNS DESCRIPTION FastStream

The imported FastStream app object.

RAISES DESCRIPTION FileNotFoundError

If the module file is not found.

BadParameter

If the module or app name is not provided correctly.

Source code in faststream/cli/utils/imports.py
def try_import_app(module: Path, app: str) -> FastStream:\n    \"\"\"Tries to import a FastStream app from a module.\n\n    Args:\n        module: Path to the module containing the app.\n        app: Name of the FastStream app.\n\n    Returns:\n        The imported FastStream app object.\n\n    Raises:\n        FileNotFoundError: If the module file is not found.\n        typer.BadParameter: If the module or app name is not provided correctly.\n\n    \"\"\"\n    try:\n        app_object = import_object(module, app)\n\n    except FileNotFoundError as e:\n        typer.echo(e, err=True)\n        raise typer.BadParameter(\n            \"Please, input module like [python_file:faststream_app_name] or [module:attribute]\"\n        ) from e\n\n    else:\n        return app_object  # type: ignore\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/","title":"LogLevels","text":"","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels","title":"faststream.cli.utils.logs.LogLevels","text":"

Bases: str, Enum

A class to represent log levels.

","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels.critical","title":"critical class-attribute instance-attribute","text":"
critical = 'critical'\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels.debug","title":"debug class-attribute instance-attribute","text":"
debug = 'debug'\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels.error","title":"error class-attribute instance-attribute","text":"
error = 'error'\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels.info","title":"info class-attribute instance-attribute","text":"
info = 'info'\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels.warning","title":"warning class-attribute instance-attribute","text":"
warning = 'warning'\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/get_log_level/","title":"get_log_level","text":"","boost":0.5},{"location":"api/faststream/cli/utils/logs/get_log_level/#faststream.cli.utils.logs.get_log_level","title":"faststream.cli.utils.logs.get_log_level","text":"
get_log_level(level: Union[LogLevels, str, int]) -> int\n

Get the log level.

PARAMETER DESCRIPTION level

The log level to get. Can be an integer, a LogLevels enum value, or a string.

TYPE: Union[LogLevels, str, int]

RETURNS DESCRIPTION int

The log level as an integer.

Source code in faststream/cli/utils/logs.py
def get_log_level(level: Union[LogLevels, str, int]) -> int:\n    \"\"\"Get the log level.\n\n    Args:\n        level: The log level to get. Can be an integer, a LogLevels enum value, or a string.\n\n    Returns:\n        The log level as an integer.\n\n    \"\"\"\n    if isinstance(level, int):\n        return level\n\n    if isinstance(level, LogLevels):\n        return LOG_LEVELS[level.value]\n\n    if isinstance(level, str):  # pragma: no branch\n        return LOG_LEVELS[level.lower()]\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/set_log_level/","title":"set_log_level","text":"","boost":0.5},{"location":"api/faststream/cli/utils/logs/set_log_level/#faststream.cli.utils.logs.set_log_level","title":"faststream.cli.utils.logs.set_log_level","text":"
set_log_level(level: int, app: FastStream) -> None\n

Sets the log level for an application.

PARAMETER DESCRIPTION level

The log level to set.

TYPE: int

app

The application object.

TYPE: FastStream

RETURNS DESCRIPTION None

None

Source code in faststream/cli/utils/logs.py
def set_log_level(level: int, app: FastStream) -> None:\n    \"\"\"Sets the log level for an application.\n\n    Args:\n        level (int): The log level to set.\n        app (FastStream): The application object.\n\n    Returns:\n        None\n\n    \"\"\"\n    if app.logger and isinstance(app.logger, logging.Logger):\n        app.logger.setLevel(level)\n\n    broker_logger: Optional[logging.Logger] = getattr(app.broker, \"logger\", None)\n    if broker_logger is not None and isinstance(broker_logger, logging.Logger):\n        broker_logger.setLevel(level)\n
","boost":0.5},{"location":"api/faststream/cli/utils/parser/parse_cli_args/","title":"parse_cli_args","text":"","boost":0.5},{"location":"api/faststream/cli/utils/parser/parse_cli_args/#faststream.cli.utils.parser.parse_cli_args","title":"faststream.cli.utils.parser.parse_cli_args","text":"
parse_cli_args(\n    *args: str,\n) -> Tuple[str, Dict[str, SettingField]]\n

Parses command line arguments.

PARAMETER DESCRIPTION *args

Command line arguments as strings.

TYPE: str DEFAULT: ()

RETURNS DESCRIPTION Tuple[str, Dict[str, SettingField]]

A tuple containing the application name and a dictionary of additional keyword arguments.

Source code in faststream/cli/utils/parser.py
def parse_cli_args(*args: str) -> Tuple[str, Dict[str, SettingField]]:\n    \"\"\"Parses command line arguments.\n\n    Args:\n        *args: Command line arguments as strings.\n\n    Returns:\n        A tuple containing the application name and a dictionary of additional keyword arguments.\n    \"\"\"\n    extra_kwargs: Dict[str, SettingField] = {}\n\n    k: str = \"\"\n    v: SettingField\n\n    field_args: List[str] = []\n    app = \"\"\n    for item in reduce(\n        lambda acc, x: acc + x.split(\"=\"),  # type: ignore\n        args,\n        [],\n    ) + [\"-\"]:\n        if \":\" in item:\n            app = item\n\n        else:\n            if \"-\" in item:\n                if k:\n                    k = k.strip().lstrip(\"-\").replace(\"-\", \"_\")\n\n                    if len(field_args) == 0:\n                        v = not k.startswith(\"no_\")\n                    elif len(field_args) == 1:\n                        v = field_args[0]\n                    else:\n                        v = field_args\n\n                    key = remove_prefix(k, \"no_\")\n                    if (exists := extra_kwargs.get(key)) is not None:\n                        if not isinstance(exists, list):\n                            v = [exists, v]\n                        else:\n                            v = exists + [v]\n\n                    extra_kwargs[key] = v\n                    field_args = []\n\n                k = item\n\n            else:\n                field_args.append(item)\n\n    return app, extra_kwargs\n
","boost":0.5},{"location":"api/faststream/cli/utils/parser/remove_prefix/","title":"remove_prefix","text":"","boost":0.5},{"location":"api/faststream/cli/utils/parser/remove_prefix/#faststream.cli.utils.parser.remove_prefix","title":"faststream.cli.utils.parser.remove_prefix","text":"
remove_prefix(text: str, prefix: str) -> str\n

Removes a prefix from a given text.

Python 3.8 compatibility function

PARAMETER DESCRIPTION text

The text from which the prefix will be removed.

TYPE: str

prefix

The prefix to be removed from the text.

TYPE: str

RETURNS DESCRIPTION str

The text with the prefix removed. If the text does not start with the prefix, the original text is returned.

TYPE: str

Source code in faststream/cli/utils/parser.py
def remove_prefix(text: str, prefix: str) -> str:\n    \"\"\"Removes a prefix from a given text.\n\n    Python 3.8 compatibility function\n\n    Args:\n        text (str): The text from which the prefix will be removed.\n        prefix (str): The prefix to be removed from the text.\n\n    Returns:\n        str: The text with the prefix removed. If the text does not start with the prefix, the original text is returned.\n    \"\"\"\n    if text.startswith(prefix):\n        return text[len(prefix) :]\n    return text\n
","boost":0.5},{"location":"api/faststream/constants/ContentTypes/","title":"ContentTypes","text":"","boost":0.5},{"location":"api/faststream/constants/ContentTypes/#faststream.constants.ContentTypes","title":"faststream.constants.ContentTypes","text":"

Bases: str, Enum

A class to represent content types.

","boost":0.5},{"location":"api/faststream/constants/ContentTypes/#faststream.constants.ContentTypes.json","title":"json class-attribute instance-attribute","text":"
json = 'application/json'\n
","boost":0.5},{"location":"api/faststream/constants/ContentTypes/#faststream.constants.ContentTypes.text","title":"text class-attribute instance-attribute","text":"
text = 'text/plain'\n
","boost":0.5},{"location":"api/faststream/exceptions/AckMessage/","title":"AckMessage","text":"","boost":0.5},{"location":"api/faststream/exceptions/AckMessage/#faststream.exceptions.AckMessage","title":"faststream.exceptions.AckMessage","text":"

Bases: HandlerException

Raise it to ack a message immediately

","boost":0.5},{"location":"api/faststream/exceptions/HandlerException/","title":"HandlerException","text":"","boost":0.5},{"location":"api/faststream/exceptions/HandlerException/#faststream.exceptions.HandlerException","title":"faststream.exceptions.HandlerException","text":"

Bases: Exception

Base Handler Exception

","boost":0.5},{"location":"api/faststream/exceptions/NackMessage/","title":"NackMessage","text":"","boost":0.5},{"location":"api/faststream/exceptions/NackMessage/#faststream.exceptions.NackMessage","title":"faststream.exceptions.NackMessage","text":"

Bases: HandlerException

Raise it to nack a message immediately

","boost":0.5},{"location":"api/faststream/exceptions/RejectMessage/","title":"RejectMessage","text":"","boost":0.5},{"location":"api/faststream/exceptions/RejectMessage/#faststream.exceptions.RejectMessage","title":"faststream.exceptions.RejectMessage","text":"

Bases: HandlerException

Raise it to reject a message immediately

","boost":0.5},{"location":"api/faststream/exceptions/SkipMessage/","title":"SkipMessage","text":"","boost":0.5},{"location":"api/faststream/exceptions/SkipMessage/#faststream.exceptions.SkipMessage","title":"faststream.exceptions.SkipMessage","text":"

Bases: Exception

Watcher Instruction to skip message

","boost":0.5},{"location":"api/faststream/exceptions/StopConsume/","title":"StopConsume","text":"","boost":0.5},{"location":"api/faststream/exceptions/StopConsume/#faststream.exceptions.StopConsume","title":"faststream.exceptions.StopConsume","text":"

Bases: Exception

Raise it to stop Handler consuming

","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/","title":"KafkaBroker","text":"","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker","title":"faststream.kafka.KafkaBroker","text":"
KafkaBroker(\n    bootstrap_servers: Union[\n        str, Iterable[str]\n    ] = \"localhost\",\n    *,\n    protocol: str = None,\n    protocol_version: str = \"auto\",\n    client_id: str = \"faststream-\" + __version__,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: KafkaLoggingMixin, BrokerAsyncUsecase[ConsumerRecord, ConsumerConnectionParams]

KafkaBroker is a class for managing Kafka message consumption and publishing. It extends BrokerAsyncUsecase to handle asynchronous operations.

PARAMETER DESCRIPTION bootstrap_servers

Kafka bootstrap server(s).

TYPE: Union[str, Iterable[str]] DEFAULT: 'localhost'

protocol

The protocol used (default is \"kafka\").

TYPE: str DEFAULT: None

protocol_version

The Kafka protocol version (default is \"auto\").

TYPE: str DEFAULT: 'auto'

client_id

The client ID for the Kafka client.

TYPE: str DEFAULT: 'faststream-' + __version__

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

METHOD DESCRIPTION connect

Establishes a connection to Kafka.

start

Starts the KafkaBroker and message handlers.

publish

Publishes a message to Kafka.

Initialize a KafkaBroker instance.

PARAMETER DESCRIPTION bootstrap_servers

Kafka bootstrap server(s).

TYPE: Union[str, Iterable[str]] DEFAULT: 'localhost'

protocol

The protocol used (default is \"kafka\").

TYPE: str DEFAULT: None

protocol_version

The Kafka protocol version (default is \"auto\").

TYPE: str DEFAULT: 'auto'

client_id

The client ID for the Kafka client.

TYPE: str DEFAULT: 'faststream-' + __version__

security

Security protocol to use in communication with the broker (default is None).

TYPE: Optional[BaseSecurity] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/kafka/broker.py
def __init__(\n    self,\n    bootstrap_servers: Union[str, Iterable[str]] = \"localhost\",\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: str = \"auto\",\n    client_id: str = \"faststream-\" + __version__,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Initialize a KafkaBroker instance.\n\n    Args:\n        bootstrap_servers (Union[str, Iterable[str]]): Kafka bootstrap server(s).\n        protocol (str): The protocol used (default is \"kafka\").\n        protocol_version (str): The Kafka protocol version (default is \"auto\").\n        client_id (str): The client ID for the Kafka client.\n        security (Optional[BaseSecurity]): Security protocol to use in communication with the broker (default is None).\n        **kwargs: Additional keyword arguments.\n    \"\"\"\n    if protocol is None:\n        if security is not None and security.use_ssl:\n            protocol = \"kafka-secure\"\n        else:\n            protocol = \"kafka\"\n\n    super().__init__(\n        url=[bootstrap_servers]\n        if isinstance(bootstrap_servers, str)\n        else list(bootstrap_servers),\n        protocol=protocol,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n        client_id=client_id,\n        bootstrap_servers=bootstrap_servers,\n    )\n    self.client_id = client_id\n    self._producer = None\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.client_id","title":"client_id instance-attribute","text":"
client_id = client_id\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[str, Handler]\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.url","title":"url instance-attribute","text":"
url: List[str]\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.connect","title":"connect async","text":"
connect(\n    *args: Any, **kwargs: Any\n) -> ConsumerConnectionParams\n

Establishes a connection to Kafka and returns connection parameters.

PARAMETER DESCRIPTION *args

Additional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION ConsumerConnectionParams

The connection parameters.

TYPE: ConsumerConnectionParams

Source code in faststream/kafka/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> ConsumerConnectionParams:\n    \"\"\"\n    Establishes a connection to Kafka and returns connection parameters.\n\n    Args:\n        *args: Additional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        ConsumerConnectionParams: The connection parameters.\n    \"\"\"\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.publish","title":"publish async","text":"
publish(*args: Any, **kwargs: Any) -> None\n

Publish a message to Kafka.

PARAMETER DESCRIPTION *args

Positional arguments for message publishing.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments for message publishing.

TYPE: Any DEFAULT: {}

RAISES DESCRIPTION RuntimeError

If KafkaBroker is not started yet.

Source code in faststream/kafka/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Publish a message to Kafka.\n\n    Args:\n        *args: Positional arguments for message publishing.\n        **kwargs: Keyword arguments for message publishing.\n\n    Raises:\n        RuntimeError: If KafkaBroker is not started yet.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.publish_batch","title":"publish_batch async","text":"
publish_batch(*args: Any, **kwargs: Any) -> None\n

Publish a batch of messages to Kafka.

PARAMETER DESCRIPTION *args

Positional arguments for message publishing.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments for message publishing.

TYPE: Any DEFAULT: {}

RAISES DESCRIPTION RuntimeError

If KafkaBroker is not started yet.

Source code in faststream/kafka/broker.py
async def publish_batch(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Publish a batch of messages to Kafka.\n\n    Args:\n        *args: Positional arguments for message publishing.\n        **kwargs: Keyword arguments for message publishing.\n\n    Raises:\n        RuntimeError: If KafkaBroker is not started yet.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    await self._producer.publish_batch(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.publisher","title":"publisher","text":"
publisher(\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n

Create a message publisher for the specified topic.

PARAMETER DESCRIPTION topic

The topic to publish messages to.

TYPE: str

key

Message key.

TYPE: Optional[bytes] DEFAULT: None

partition

Partition to send the message to.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

Message timestamp in milliseconds.

TYPE: Optional[int] DEFAULT: None

headers

Message headers.

TYPE: Optional[Dict[str, str]] DEFAULT: None

reply_to

The topic to which responses should be sent.

TYPE: str DEFAULT: ''

batch

Whether to publish messages in batches.

TYPE: bool DEFAULT: False

title

AsyncAPI title.

TYPE: Optional[str] DEFAULT: None

description

AsyncAPI description.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION Publisher

A message publisher.

TYPE: Publisher

Source code in faststream/kafka/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"\n    Create a message publisher for the specified topic.\n\n    Args:\n        topic (str): The topic to publish messages to.\n        key (Optional[bytes]): Message key.\n        partition (Optional[int]): Partition to send the message to.\n        timestamp_ms (Optional[int]): Message timestamp in milliseconds.\n        headers (Optional[Dict[str, str]]): Message headers.\n        reply_to (str): The topic to which responses should be sent.\n        batch (bool): Whether to publish messages in batches.\n        title (Optional[str]): AsyncAPI title.\n        description (Optional[str]): AsyncAPI description.\n\n    Returns:\n        Publisher: A message publisher.\n    \"\"\"\n    publisher = self._publishers.get(\n        topic,\n        Publisher(\n            topic=topic,\n            client_id=self.client_id,\n            key=key,\n            batch=batch,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(topic, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.start","title":"start async","text":"
start() -> None\n

Start the KafkaBroker and message handlers.

Source code in faststream/kafka/broker.py
async def start(self) -> None:\n    \"\"\"\n    Start the KafkaBroker and message handlers.\n    \"\"\"\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n\n    for handler in self.handlers.values():\n        c = self._get_log_context(None, handler.topics, handler.group_id)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(**(self._connection or {}))\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.subscriber","title":"subscriber","text":"
subscriber(\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    value_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\", \"earliest\", \"none\"\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[\n        AbstractPartitionAssignor\n    ] = (RoundRobinPartitionAssignor),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\", \"read_committed\"\n    ] = \"read_uncommitted\",\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        Union[\n            CustomParser[\n                aiokafka.ConsumerRecord, KafkaMessage\n            ],\n            CustomParser[\n                Tuple[aiokafka.ConsumerRecord, ...],\n                KafkaMessage,\n            ],\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[\n            StreamMessage[\n                Tuple[aiokafka.ConsumerRecord, ...]\n            ]\n        ],\n    ] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    Union[\n        HandlerCallWrapper[\n            aiokafka.ConsumerRecord,\n            P_HandlerParams,\n            T_HandlerReturn,\n        ],\n        HandlerCallWrapper[\n            Tuple[aiokafka.ConsumerRecord, ...],\n            P_HandlerParams,\n            T_HandlerReturn,\n        ],\n    ],\n]\n

Create a message subscriber for the specified topics.

PARAMETER DESCRIPTION *topics

The topics to subscribe to.

TYPE: str DEFAULT: ()

group_id

The Kafka consumer group ID.

TYPE: Optional[str] DEFAULT: None

key_deserializer

Key deserializer function.

TYPE: Optional[Callable[[bytes], Any]] DEFAULT: None

value_deserializer

Value deserializer function.

TYPE: Optional[Callable[[bytes], Any]] DEFAULT: None

fetch_max_wait_ms

The maximum time to wait for data.

TYPE: int DEFAULT: 500

fetch_max_bytes

The maximum number of bytes to fetch.

TYPE: int DEFAULT: 52428800

fetch_min_bytes

The minimum number of bytes to fetch.

TYPE: int DEFAULT: 1

max_partition_fetch_bytes

The maximum bytes to fetch for a partition.

TYPE: int DEFAULT: 1 * 1024 * 1024

auto_offset_reset

Auto offset reset policy.

TYPE: Literal['latest', 'earliest', 'none'] DEFAULT: 'latest'

auto_commit

Whether to enable auto-commit.

TYPE: bool DEFAULT: True

auto_commit_interval_ms

Auto-commit interval in milliseconds.

TYPE: int DEFAULT: 5000

check_crcs

Whether to check CRCs.

TYPE: bool DEFAULT: True

partition_assignment_strategy

Partition assignment strategy.

TYPE: Sequence[AbstractPartitionAssignor] DEFAULT: (RoundRobinPartitionAssignor)

max_poll_interval_ms

Maximum poll interval in milliseconds.

TYPE: int DEFAULT: 300000

rebalance_timeout_ms

Rebalance timeout in milliseconds.

TYPE: Optional[int] DEFAULT: None

session_timeout_ms

Session timeout in milliseconds.

TYPE: int DEFAULT: 10000

heartbeat_interval_ms

Heartbeat interval in milliseconds.

TYPE: int DEFAULT: 3000

consumer_timeout_ms

Consumer timeout in milliseconds.

TYPE: int DEFAULT: 200

max_poll_records

Maximum number of records to poll.

TYPE: Optional[int] DEFAULT: None

exclude_internal_topics

Whether to exclude internal topics.

TYPE: bool DEFAULT: True

isolation_level

Isolation level.

TYPE: Literal['read_uncommitted', 'read_committed'] DEFAULT: 'read_uncommitted'

dependencies

Additional dependencies for message handling.

TYPE: Sequence[Depends] DEFAULT: ()

parser

Message parser.

TYPE: Optional[Union[CustomParser[ConsumerRecord], CustomParser[Tuple[ConsumerRecord, ...]]]] DEFAULT: None

decoder

Message decoder.

TYPE: Optional[CustomDecoder] DEFAULT: None

middlewares

Message middlewares.

TYPE: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]] DEFAULT: None

filter

Message filter.

TYPE: Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[ConsumerRecord, ...]]]] DEFAULT: default_filter

batch

Whether to process messages in batches.

TYPE: bool DEFAULT: False

max_records

Maximum number of records to process in each batch.

TYPE: Optional[int] DEFAULT: None

batch_timeout_ms

Batch timeout in milliseconds.

TYPE: int DEFAULT: 200

no_ack

Whether not to ack/nack/reject messages.

TYPE: bool DEFAULT: False

title

AsyncAPI title.

TYPE: Optional[str] DEFAULT: None

description

AsyncAPI description.

TYPE: Optional[str] DEFAULT: None

**original_kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Callable

A decorator that wraps a message handler function.

TYPE: Callable[[Callable[P_HandlerParams, T_HandlerReturn]], Union[HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[Tuple[ConsumerRecord, ...], P_HandlerParams, T_HandlerReturn]]]

Source code in faststream/kafka/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[Callable[[bytes], Any]] = None,\n    value_deserializer: Optional[Callable[[bytes], Any]] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\",\n        \"earliest\",\n        \"none\",\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[AbstractPartitionAssignor] = (\n        RoundRobinPartitionAssignor,\n    ),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\",\n        \"read_committed\",\n    ] = \"read_uncommitted\",\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        Union[\n            CustomParser[aiokafka.ConsumerRecord, KafkaMessage],\n            CustomParser[Tuple[aiokafka.ConsumerRecord, ...], KafkaMessage],\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord],\n                BaseMiddleware,\n            ]\n        ]\n    ] = None,\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[aiokafka.ConsumerRecord, ...]]],\n    ] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    Union[\n        HandlerCallWrapper[\n            aiokafka.ConsumerRecord, P_HandlerParams, T_HandlerReturn\n        ],\n        HandlerCallWrapper[\n            Tuple[aiokafka.ConsumerRecord, ...], P_HandlerParams, T_HandlerReturn\n        ],\n    ],\n]:\n    \"\"\"\n    Create a message subscriber for the specified topics.\n\n    Args:\n        *topics (str): The topics to subscribe to.\n        group_id (Optional[str]): The Kafka consumer group ID.\n        key_deserializer (Optional[Callable[[bytes], Any]]): Key deserializer function.\n        value_deserializer (Optional[Callable[[bytes], Any]]): Value deserializer function.\n        fetch_max_wait_ms (int): The maximum time to wait for data.\n        fetch_max_bytes (int): The maximum number of bytes to fetch.\n        fetch_min_bytes (int): The minimum number of bytes to fetch.\n        max_partition_fetch_bytes (int): The maximum bytes to fetch for a partition.\n        auto_offset_reset (Literal[\"latest\", \"earliest\", \"none\"]): Auto offset reset policy.\n        auto_commit (bool): Whether to enable auto-commit.\n        auto_commit_interval_ms (int): Auto-commit interval in milliseconds.\n        check_crcs (bool): Whether to check CRCs.\n        partition_assignment_strategy (Sequence[AbstractPartitionAssignor]): Partition assignment strategy.\n        max_poll_interval_ms (int): Maximum poll interval in milliseconds.\n        rebalance_timeout_ms (Optional[int]): Rebalance timeout in milliseconds.\n        session_timeout_ms (int): Session timeout in milliseconds.\n        heartbeat_interval_ms (int): Heartbeat interval in milliseconds.\n        consumer_timeout_ms (int): Consumer timeout in milliseconds.\n        max_poll_records (Optional[int]): Maximum number of records to poll.\n        exclude_internal_topics (bool): Whether to exclude internal topics.\n        isolation_level (Literal[\"read_uncommitted\", \"read_committed\"]): Isolation level.\n        dependencies (Sequence[Depends]): Additional dependencies for message handling.\n        parser (Optional[Union[CustomParser[aiokafka.ConsumerRecord], CustomParser[Tuple[aiokafka.ConsumerRecord, ...]]]]): Message parser.\n        decoder (Optional[CustomDecoder]): Message decoder.\n        middlewares (Optional[Sequence[Callable[[aiokafka.ConsumerRecord], BaseMiddleware]]]): Message middlewares.\n        filter (Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[aiokafka.ConsumerRecord, ...]]]]): Message filter.\n        batch (bool): Whether to process messages in batches.\n        max_records (Optional[int]): Maximum number of records to process in each batch.\n        batch_timeout_ms (int): Batch timeout in milliseconds.\n        no_ack (bool): Whether not to ack/nack/reject messages.\n        title (Optional[str]): AsyncAPI title.\n        description (Optional[str]): AsyncAPI description.\n        **original_kwargs: Additional keyword arguments.\n\n    Returns:\n        Callable: A decorator that wraps a message handler function.\n    \"\"\"\n    super().subscriber()\n\n    self._setup_log_context(topics, group_id)\n\n    if not auto_commit and not group_id:\n        raise ValueError(\"You should install `group_id` with manual commit mode\")\n\n    key = Handler.get_routing_hash(topics, group_id)\n    builder = partial(\n        aiokafka.AIOKafkaConsumer,\n        key_deserializer=key_deserializer,\n        value_deserializer=value_deserializer,\n        fetch_max_wait_ms=fetch_max_wait_ms,\n        fetch_max_bytes=fetch_max_bytes,\n        fetch_min_bytes=fetch_min_bytes,\n        max_partition_fetch_bytes=max_partition_fetch_bytes,\n        auto_offset_reset=auto_offset_reset,\n        enable_auto_commit=auto_commit,\n        auto_commit_interval_ms=auto_commit_interval_ms,\n        check_crcs=check_crcs,\n        partition_assignment_strategy=partition_assignment_strategy,\n        max_poll_interval_ms=max_poll_interval_ms,\n        rebalance_timeout_ms=rebalance_timeout_ms,\n        session_timeout_ms=session_timeout_ms,\n        heartbeat_interval_ms=heartbeat_interval_ms,\n        consumer_timeout_ms=consumer_timeout_ms,\n        max_poll_records=max_poll_records,\n        exclude_internal_topics=exclude_internal_topics,\n        isolation_level=isolation_level,\n    )\n    handler = self.handlers.get(\n        key,\n        Handler(\n            *topics,\n            log_context_builder=partial(\n                self._get_log_context,\n                topics=topics,\n                group_id=group_id,\n            ),\n            is_manual=not auto_commit,\n            group_id=group_id,\n            client_id=self.client_id,\n            builder=builder,\n            description=description,\n            title=title,\n            batch=batch,\n            batch_timeout_ms=batch_timeout_ms,\n            max_records=max_records,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n        ),\n    )\n\n    self.handlers[key] = handler\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[\n        aiokafka.ConsumerRecord, P_HandlerParams, T_HandlerReturn\n    ]:\n        \"\"\"A wrapper function for a consumer handler.\n\n        Args:\n            func : The consumer handler function to be wrapped.\n\n        Returns:\n            The wrapped handler call.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        handler_call, dependant = self._wrap_handler(\n            func=func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRoute/","title":"KafkaRoute","text":"","boost":0.5},{"location":"api/faststream/kafka/KafkaRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/","title":"KafkaRouter","text":"","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter","title":"faststream.kafka.KafkaRouter","text":"
KafkaRouter(\n    prefix: str = \"\",\n    handlers: Sequence[KafkaRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[aiokafka.ConsumerRecord, KafkaMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[KafkaMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: KafkaRouter

A class to represent a Kafka router.

METHOD DESCRIPTION _get_publisher_key

Get the key for a publisher

_update_publisher_prefix

Update the prefix of a publisher

publisher

Create a new publisher

Source code in faststream/kafka/router.py
        publisher: The publisher object.\n\n    Returns:\n        The publisher key.\n\n    \"\"\"\n    return publisher.topic\n\n@override\n@staticmethod\ndef _update_publisher_prefix(  # type: ignore[override]\n    prefix: str,\n    publisher: Publisher,\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.publisher","title":"publisher","text":"
publisher(\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n

Publishes a message to a topic.

PARAMETER DESCRIPTION topic

The topic to publish the message to.

TYPE: str

key

The key associated with the message.

TYPE: bytes DEFAULT: None

partition

The partition to publish the message to.

TYPE: int DEFAULT: None

timestamp_ms

The timestamp of the message in milliseconds.

TYPE: int DEFAULT: None

headers

Additional headers for the message.

TYPE: Dict[str, str] DEFAULT: None

reply_to

The topic to reply to.

TYPE: str DEFAULT: ''

batch

Whether to publish the message as part of a batch.

TYPE: bool DEFAULT: False

title

The title of the message.

TYPE: str DEFAULT: None

description

The description of the message.

TYPE: str DEFAULT: None

RETURNS DESCRIPTION Publisher

The publisher object used to publish the message.

TYPE: Publisher

Source code in faststream/kafka/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"Publishes a message to a topic.\n\n    Args:\n        topic (str): The topic to publish the message to.\n        key (bytes, optional): The key associated with the message.\n        partition (int, optional): The partition to publish the message to.\n        timestamp_ms (int, optional): The timestamp of the message in milliseconds.\n        headers (Dict[str, str], optional): Additional headers for the message.\n        reply_to (str, optional): The topic to reply to.\n        batch (bool, optional): Whether to publish the message as part of a batch.\n        title (str, optional): The title of the message.\n        description (str, optional): The description of the message.\n\n    Returns:\n        Publisher: The publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            topic=topic,\n            key=key,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            batch=batch,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.subscriber","title":"subscriber","text":"
subscriber(\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    value_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\", \"earliest\", \"none\"\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[\n        AbstractPartitionAssignor\n    ] = (RoundRobinPartitionAssignor),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\", \"read_committed\"\n    ] = \"read_uncommitted\",\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[aiokafka.ConsumerRecord, KafkaMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[KafkaMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Filter[KafkaMessage] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    retry: Union[bool, int] = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aiokafka.ConsumerRecord,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n
Source code in faststream/kafka/router.py
    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"Publishes a message to a topic.\n\n    Args:\n        topic (str): The topic to publish the message to.\n        key (bytes, optional): The key associated with the message.\n        partition (int, optional): The partition to publish the message to.\n        timestamp_ms (int, optional): The timestamp of the message in milliseconds.\n        headers (Dict[str, str], optional): Additional headers for the message.\n        reply_to (str, optional): The topic to reply to.\n        batch (bool, optional): Whether to publish the message as part of a batch.\n        title (str, optional): The title of the message.\n        description (str, optional): The description of the message.\n\n    Returns:\n        Publisher: The publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            topic=topic,\n            key=key,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            batch=batch,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/kafka/TestApp/#faststream.broker.test.TestApp","title":"faststream.broker.test.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/kafka/TestApp/#faststream.broker.test.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/","title":"TestKafkaBroker","text":"","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker","title":"faststream.kafka.TestKafkaBroker","text":"
TestKafkaBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[KafkaBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/kafka/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: KafkaBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(  # type: ignore[call-overload,misc]\n        publisher.topic,\n        batch=publisher.batch,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f  # type: ignore[no-any-return]\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: KafkaBroker, publisher: Any\n) -> None\n
Source code in faststream/kafka/test.py
@staticmethod\ndef patch_publisher(broker: KafkaBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> None\n
Source code in faststream/kafka/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> None:\n    broker.handlers.pop(publisher.topic, None)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/","title":"Handler","text":"","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler","title":"faststream.kafka.asyncapi.Handler","text":"
Handler(\n    *topics: str,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    group_id: Optional[str] = None,\n    client_id: str = \"faststream-\" + __version__,\n    builder: Callable[..., AIOKafkaConsumer],\n    is_manual: bool = False,\n    batch: bool = False,\n    batch_timeout_ms: int = 200,\n    max_records: Optional[int] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True\n)\n

Bases: LogicHandler, AsyncAPIOperation

A class to handle logic and async API operations.

METHOD DESCRIPTION schema

Returns a dictionary of channels.

Initialize a Kafka consumer for the specified topics.

PARAMETER DESCRIPTION *topics

Variable length argument list of topics to consume from.

TYPE: str DEFAULT: ()

group_id

Optional group ID for the consumer.

TYPE: Optional[str] DEFAULT: None

client_id

Client ID for the consumer.

TYPE: str DEFAULT: 'faststream-' + __version__

builder

Callable that constructs an AIOKafkaConsumer instance.

TYPE: Callable[..., AIOKafkaConsumer]

batch

Flag indicating whether to consume messages in batches.

TYPE: bool DEFAULT: False

batch_timeout_ms

Timeout in milliseconds for batch consumption.

TYPE: int DEFAULT: 200

max_records

Maximum number of records to consume in a batch.

TYPE: Optional[int] DEFAULT: None

title

Optional title for the consumer.

TYPE: Optional[str] DEFAULT: None

description

Optional description for the consumer.

TYPE: Optional[str] DEFAULT: None

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/kafka/handler.py
@override\ndef __init__(\n    self,\n    *topics: str,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # Kafka information\n    group_id: Optional[str] = None,\n    client_id: str = \"faststream-\" + __version__,\n    builder: Callable[..., AIOKafkaConsumer],\n    is_manual: bool = False,\n    batch: bool = False,\n    batch_timeout_ms: int = 200,\n    max_records: Optional[int] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    \"\"\"Initialize a Kafka consumer for the specified topics.\n\n    Args:\n        *topics: Variable length argument list of topics to consume from.\n        group_id: Optional group ID for the consumer.\n        client_id: Client ID for the consumer.\n        builder: Callable that constructs an AIOKafkaConsumer instance.\n        batch: Flag indicating whether to consume messages in batches.\n        batch_timeout_ms: Timeout in milliseconds for batch consumption.\n        max_records: Maximum number of records to consume in a batch.\n        title: Optional title for the consumer.\n        description: Optional description for the consumer.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.group_id = group_id\n    self.client_id = client_id\n    self.topics = topics\n\n    self.batch = batch\n    self.batch_timeout_ms = batch_timeout_ms\n    self.max_records = max_records\n    self.is_manual = is_manual\n\n    self.builder = builder\n    self.task = None\n    self.consumer = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = batch\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.batch_timeout_ms","title":"batch_timeout_ms instance-attribute","text":"
batch_timeout_ms = batch_timeout_ms\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.builder","title":"builder instance-attribute","text":"
builder = builder\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.client_id","title":"client_id instance-attribute","text":"
client_id = client_id\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.consumer","title":"consumer class-attribute instance-attribute","text":"
consumer: Optional[AIOKafkaConsumer] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.group_id","title":"group_id class-attribute instance-attribute","text":"
group_id: Optional[str] = group_id\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.is_manual","title":"is_manual instance-attribute","text":"
is_manual = is_manual\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.max_records","title":"max_records instance-attribute","text":"
max_records = max_records\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.task","title":"task class-attribute instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.topics","title":"topics instance-attribute","text":"
topics: Sequence[str] = topics\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        ConsumerRecord, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: CustomParser[\n        Union[ConsumerRecord, Tuple[ConsumerRecord, ...]],\n        KafkaMessage,\n    ],\n    decoder: Optional[CustomDecoder[KafkaMessage]],\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[ConsumerRecord, ...]]],\n    ],\n    middlewares: Optional[\n        Sequence[Callable[[ConsumerRecord], BaseMiddleware]]\n    ]\n) -> None\n

Adds a call to the handler.

PARAMETER DESCRIPTION handler

The handler function to be called.

TYPE: HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn]

dependant

The dependant model.

TYPE: CallModel[P_HandlerParams, T_HandlerReturn]

parser

Optional custom parser for parsing the input.

TYPE: CustomParser[Union[ConsumerRecord, Tuple[ConsumerRecord, ...]], KafkaMessage]

decoder

Optional custom decoder for decoding the input.

TYPE: Optional[CustomDecoder[KafkaMessage]]

filter

The filter for filtering the input.

TYPE: Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[ConsumerRecord, ...]]]]

middlewares

Optional sequence of middlewares to be applied.

TYPE: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]]

RETURNS DESCRIPTION None

None

Source code in faststream/kafka/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: CustomParser[\n        Union[ConsumerRecord, Tuple[ConsumerRecord, ...]], KafkaMessage\n    ],\n    decoder: Optional[CustomDecoder[KafkaMessage]],\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[ConsumerRecord, ...]]],\n    ],\n    middlewares: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]],\n) -> None:\n    \"\"\"Adds a call to the handler.\n\n    Args:\n        handler: The handler function to be called.\n        dependant: The dependant model.\n        parser: Optional custom parser for parsing the input.\n        decoder: Optional custom decoder for decoding the input.\n        filter: The filter for filtering the input.\n        middlewares: Optional sequence of middlewares to be applied.\n\n    Returns:\n        None\n\n    \"\"\"\n    parser_ = resolve_custom_func(  # type: ignore[type-var]\n        parser,  # type: ignore[arg-type]\n        (\n            AioKafkaParser.parse_message_batch  # type: ignore[arg-type]\n            if self.batch\n            else AioKafkaParser.parse_message\n        ),\n    )\n    decoder_ = resolve_custom_func(\n        decoder,  # type: ignore[arg-type]\n        (\n            AioKafkaParser.decode_message_batch  # type: ignore[arg-type]\n            if self.batch\n            else AioKafkaParser.decode_message\n        ),\n    )\n    super().add_call(\n        handler=handler,\n        parser=parser_,\n        decoder=decoder_,\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/kafka/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.consumer is not None:\n        await self.consumer.stop()\n        self.consumer = None\n\n    if self.task is not None:\n        self.task.cancel()\n        self.task = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(\n    topics: Sequence[str], group_id: Optional[str] = None\n) -> str\n
Source code in faststream/kafka/handler.py
@staticmethod\ndef get_routing_hash(topics: Sequence[str], group_id: Optional[str] = None) -> str:\n    return \"\".join((*topics, group_id or \"\"))\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/kafka/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    channels = {}\n\n    payloads = self.get_payloads()\n\n    for t in self.topics:\n        handler_name = self._title or f\"{t}:{self.call_name}\"\n        channels[handler_name] = Channel(\n            description=self.description,\n            subscribe=Operation(\n                message=Message(\n                    title=f\"{handler_name}:Message\",\n                    payload=resolve_payloads(payloads),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(kafka=kafka.ChannelBinding(topic=t)),\n        )\n\n    return channels\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.start","title":"start async","text":"
start(\n    **consumer_kwargs: Unpack[ConsumerConnectionParams],\n) -> None\n

Start the consumer.

PARAMETER DESCRIPTION **consumer_kwargs

Additional keyword arguments to pass to the consumer.

TYPE: Unpack[ConsumerConnectionParams] DEFAULT: {}

RETURNS DESCRIPTION None

None

Source code in faststream/kafka/handler.py
@override\nasync def start(  # type: ignore[override]\n    self,\n    **consumer_kwargs: Unpack[ConsumerConnectionParams],\n) -> None:\n    \"\"\"Start the consumer.\n\n    Args:\n        **consumer_kwargs: Additional keyword arguments to pass to the consumer.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.consumer = consumer = self.builder(\n        *self.topics,\n        group_id=self.group_id,\n        client_id=self.client_id,\n        **consumer_kwargs,\n    )\n    await consumer.start()\n    self.task = asyncio.create_task(self._consume())\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/","title":"Publisher","text":"","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher","title":"faststream.kafka.asyncapi.Publisher","text":"

Bases: LogicPublisher, AsyncAPIOperation

A class representing a publisher.

METHOD DESCRIPTION schema

returns the schema for the publisher

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported

","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = field(default=False)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.client_id","title":"client_id class-attribute instance-attribute","text":"
client_id: str = field(default='faststream-' + __version__)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.key","title":"key class-attribute instance-attribute","text":"
key: Optional[bytes] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.name","title":"name property","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.partition","title":"partition class-attribute instance-attribute","text":"
partition: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = ''\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.timestamp_ms","title":"timestamp_ms class-attribute instance-attribute","text":"
timestamp_ms: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.topic","title":"topic class-attribute instance-attribute","text":"
topic: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.publish","title":"publish async","text":"
publish(\n    *messages: SendableMessage,\n    message: SendableMessage = \"\",\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None\n) -> None\n

Publish messages to a topic.

PARAMETER DESCRIPTION *messages

Variable length argument list of SendableMessage objects.

TYPE: SendableMessage DEFAULT: ()

message

A SendableMessage object. Default is an empty string.

TYPE: SendableMessage DEFAULT: ''

key

Optional bytes object representing the message key.

TYPE: Optional[bytes] DEFAULT: None

partition

Optional integer representing the partition to publish the message to.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

Optional integer representing the timestamp of the message in milliseconds.

TYPE: Optional[int] DEFAULT: None

headers

Optional dictionary of header key-value pairs.

TYPE: Optional[Dict[str, str]] DEFAULT: None

correlation_id

Optional string representing the correlation ID of the message.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION AssertionError

If _producer is not set up.

AssertionError

If batch flag is not set and there are multiple messages.

ValueError

If message is not a sequence when messages is empty.

Source code in faststream/kafka/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *messages: SendableMessage,\n    message: SendableMessage = \"\",\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n) -> None:\n    \"\"\"Publish messages to a topic.\n\n    Args:\n        *messages: Variable length argument list of SendableMessage objects.\n        message: A SendableMessage object. Default is an empty string.\n        key: Optional bytes object representing the message key.\n        partition: Optional integer representing the partition to publish the message to.\n        timestamp_ms: Optional integer representing the timestamp of the message in milliseconds.\n        headers: Optional dictionary of header key-value pairs.\n        correlation_id: Optional string representing the correlation ID of the message.\n\n    Returns:\n        None\n\n    Raises:\n        AssertionError: If `_producer` is not set up.\n        AssertionError: If `batch` flag is not set and there are multiple messages.\n        ValueError: If `message` is not a sequence when `messages` is empty.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    assert (  # nosec B101\n        self.batch or len(messages) < 2\n    ), \"You can't send multiple messages without `batch` flag\"\n    assert self.topic, \"You have to specify outgoing topic\"  # nosec B101\n\n    if not self.batch:\n        return await self._producer.publish(\n            message=next(iter(messages), message),\n            topic=self.topic,\n            key=key or self.key,\n            partition=partition or self.partition,\n            timestamp_ms=timestamp_ms or self.timestamp_ms,\n            correlation_id=correlation_id,\n            headers=headers or self.headers,\n            reply_to=self.reply_to or \"\",\n        )\n    else:\n        to_send: Sequence[SendableMessage]\n        if not messages:\n            if not isinstance(message, Sequence):\n                raise ValueError(\n                    f\"Message: {message} should be Sequence type to send in batch\"\n                )\n            else:\n                to_send = message\n        else:\n            to_send = messages\n\n        await self._producer.publish_batch(\n            *to_send,\n            topic=self.topic,\n            partition=partition or self.partition,\n            timestamp_ms=timestamp_ms or self.timestamp_ms,\n            headers=headers or self.headers,\n        )\n        return None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/kafka/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    return {\n        self.name: Channel(\n            description=self.description,\n            publish=Operation(\n                message=Message(\n                    title=f\"{self.name}:Message\",\n                    payload=resolve_payloads(payloads, \"Publisher\"),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(kafka=kafka.ChannelBinding(topic=self.topic)),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/","title":"KafkaBroker","text":"","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker","title":"faststream.kafka.broker.KafkaBroker","text":"
KafkaBroker(\n    bootstrap_servers: Union[\n        str, Iterable[str]\n    ] = \"localhost\",\n    *,\n    protocol: str = None,\n    protocol_version: str = \"auto\",\n    client_id: str = \"faststream-\" + __version__,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: KafkaLoggingMixin, BrokerAsyncUsecase[ConsumerRecord, ConsumerConnectionParams]

KafkaBroker is a class for managing Kafka message consumption and publishing. It extends BrokerAsyncUsecase to handle asynchronous operations.

PARAMETER DESCRIPTION bootstrap_servers

Kafka bootstrap server(s).

TYPE: Union[str, Iterable[str]] DEFAULT: 'localhost'

protocol

The protocol used (default is \"kafka\").

TYPE: str DEFAULT: None

protocol_version

The Kafka protocol version (default is \"auto\").

TYPE: str DEFAULT: 'auto'

client_id

The client ID for the Kafka client.

TYPE: str DEFAULT: 'faststream-' + __version__

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

METHOD DESCRIPTION connect

Establishes a connection to Kafka.

start

Starts the KafkaBroker and message handlers.

publish

Publishes a message to Kafka.

Initialize a KafkaBroker instance.

PARAMETER DESCRIPTION bootstrap_servers

Kafka bootstrap server(s).

TYPE: Union[str, Iterable[str]] DEFAULT: 'localhost'

protocol

The protocol used (default is \"kafka\").

TYPE: str DEFAULT: None

protocol_version

The Kafka protocol version (default is \"auto\").

TYPE: str DEFAULT: 'auto'

client_id

The client ID for the Kafka client.

TYPE: str DEFAULT: 'faststream-' + __version__

security

Security protocol to use in communication with the broker (default is None).

TYPE: Optional[BaseSecurity] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/kafka/broker.py
def __init__(\n    self,\n    bootstrap_servers: Union[str, Iterable[str]] = \"localhost\",\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: str = \"auto\",\n    client_id: str = \"faststream-\" + __version__,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Initialize a KafkaBroker instance.\n\n    Args:\n        bootstrap_servers (Union[str, Iterable[str]]): Kafka bootstrap server(s).\n        protocol (str): The protocol used (default is \"kafka\").\n        protocol_version (str): The Kafka protocol version (default is \"auto\").\n        client_id (str): The client ID for the Kafka client.\n        security (Optional[BaseSecurity]): Security protocol to use in communication with the broker (default is None).\n        **kwargs: Additional keyword arguments.\n    \"\"\"\n    if protocol is None:\n        if security is not None and security.use_ssl:\n            protocol = \"kafka-secure\"\n        else:\n            protocol = \"kafka\"\n\n    super().__init__(\n        url=[bootstrap_servers]\n        if isinstance(bootstrap_servers, str)\n        else list(bootstrap_servers),\n        protocol=protocol,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n        client_id=client_id,\n        bootstrap_servers=bootstrap_servers,\n    )\n    self.client_id = client_id\n    self._producer = None\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.client_id","title":"client_id instance-attribute","text":"
client_id = client_id\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[str, Handler]\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.url","title":"url instance-attribute","text":"
url: List[str]\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.connect","title":"connect async","text":"
connect(\n    *args: Any, **kwargs: Any\n) -> ConsumerConnectionParams\n

Establishes a connection to Kafka and returns connection parameters.

PARAMETER DESCRIPTION *args

Additional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION ConsumerConnectionParams

The connection parameters.

TYPE: ConsumerConnectionParams

Source code in faststream/kafka/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> ConsumerConnectionParams:\n    \"\"\"\n    Establishes a connection to Kafka and returns connection parameters.\n\n    Args:\n        *args: Additional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        ConsumerConnectionParams: The connection parameters.\n    \"\"\"\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.publish","title":"publish async","text":"
publish(*args: Any, **kwargs: Any) -> None\n

Publish a message to Kafka.

PARAMETER DESCRIPTION *args

Positional arguments for message publishing.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments for message publishing.

TYPE: Any DEFAULT: {}

RAISES DESCRIPTION RuntimeError

If KafkaBroker is not started yet.

Source code in faststream/kafka/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Publish a message to Kafka.\n\n    Args:\n        *args: Positional arguments for message publishing.\n        **kwargs: Keyword arguments for message publishing.\n\n    Raises:\n        RuntimeError: If KafkaBroker is not started yet.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.publish_batch","title":"publish_batch async","text":"
publish_batch(*args: Any, **kwargs: Any) -> None\n

Publish a batch of messages to Kafka.

PARAMETER DESCRIPTION *args

Positional arguments for message publishing.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments for message publishing.

TYPE: Any DEFAULT: {}

RAISES DESCRIPTION RuntimeError

If KafkaBroker is not started yet.

Source code in faststream/kafka/broker.py
async def publish_batch(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Publish a batch of messages to Kafka.\n\n    Args:\n        *args: Positional arguments for message publishing.\n        **kwargs: Keyword arguments for message publishing.\n\n    Raises:\n        RuntimeError: If KafkaBroker is not started yet.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    await self._producer.publish_batch(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.publisher","title":"publisher","text":"
publisher(\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n

Create a message publisher for the specified topic.

PARAMETER DESCRIPTION topic

The topic to publish messages to.

TYPE: str

key

Message key.

TYPE: Optional[bytes] DEFAULT: None

partition

Partition to send the message to.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

Message timestamp in milliseconds.

TYPE: Optional[int] DEFAULT: None

headers

Message headers.

TYPE: Optional[Dict[str, str]] DEFAULT: None

reply_to

The topic to which responses should be sent.

TYPE: str DEFAULT: ''

batch

Whether to publish messages in batches.

TYPE: bool DEFAULT: False

title

AsyncAPI title.

TYPE: Optional[str] DEFAULT: None

description

AsyncAPI description.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION Publisher

A message publisher.

TYPE: Publisher

Source code in faststream/kafka/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"\n    Create a message publisher for the specified topic.\n\n    Args:\n        topic (str): The topic to publish messages to.\n        key (Optional[bytes]): Message key.\n        partition (Optional[int]): Partition to send the message to.\n        timestamp_ms (Optional[int]): Message timestamp in milliseconds.\n        headers (Optional[Dict[str, str]]): Message headers.\n        reply_to (str): The topic to which responses should be sent.\n        batch (bool): Whether to publish messages in batches.\n        title (Optional[str]): AsyncAPI title.\n        description (Optional[str]): AsyncAPI description.\n\n    Returns:\n        Publisher: A message publisher.\n    \"\"\"\n    publisher = self._publishers.get(\n        topic,\n        Publisher(\n            topic=topic,\n            client_id=self.client_id,\n            key=key,\n            batch=batch,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(topic, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.start","title":"start async","text":"
start() -> None\n

Start the KafkaBroker and message handlers.

Source code in faststream/kafka/broker.py
async def start(self) -> None:\n    \"\"\"\n    Start the KafkaBroker and message handlers.\n    \"\"\"\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n\n    for handler in self.handlers.values():\n        c = self._get_log_context(None, handler.topics, handler.group_id)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(**(self._connection or {}))\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.subscriber","title":"subscriber","text":"
subscriber(\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    value_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\", \"earliest\", \"none\"\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[\n        AbstractPartitionAssignor\n    ] = (RoundRobinPartitionAssignor),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\", \"read_committed\"\n    ] = \"read_uncommitted\",\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        Union[\n            CustomParser[\n                aiokafka.ConsumerRecord, KafkaMessage\n            ],\n            CustomParser[\n                Tuple[aiokafka.ConsumerRecord, ...],\n                KafkaMessage,\n            ],\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[\n            StreamMessage[\n                Tuple[aiokafka.ConsumerRecord, ...]\n            ]\n        ],\n    ] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    Union[\n        HandlerCallWrapper[\n            aiokafka.ConsumerRecord,\n            P_HandlerParams,\n            T_HandlerReturn,\n        ],\n        HandlerCallWrapper[\n            Tuple[aiokafka.ConsumerRecord, ...],\n            P_HandlerParams,\n            T_HandlerReturn,\n        ],\n    ],\n]\n

Create a message subscriber for the specified topics.

PARAMETER DESCRIPTION *topics

The topics to subscribe to.

TYPE: str DEFAULT: ()

group_id

The Kafka consumer group ID.

TYPE: Optional[str] DEFAULT: None

key_deserializer

Key deserializer function.

TYPE: Optional[Callable[[bytes], Any]] DEFAULT: None

value_deserializer

Value deserializer function.

TYPE: Optional[Callable[[bytes], Any]] DEFAULT: None

fetch_max_wait_ms

The maximum time to wait for data.

TYPE: int DEFAULT: 500

fetch_max_bytes

The maximum number of bytes to fetch.

TYPE: int DEFAULT: 52428800

fetch_min_bytes

The minimum number of bytes to fetch.

TYPE: int DEFAULT: 1

max_partition_fetch_bytes

The maximum bytes to fetch for a partition.

TYPE: int DEFAULT: 1 * 1024 * 1024

auto_offset_reset

Auto offset reset policy.

TYPE: Literal['latest', 'earliest', 'none'] DEFAULT: 'latest'

auto_commit

Whether to enable auto-commit.

TYPE: bool DEFAULT: True

auto_commit_interval_ms

Auto-commit interval in milliseconds.

TYPE: int DEFAULT: 5000

check_crcs

Whether to check CRCs.

TYPE: bool DEFAULT: True

partition_assignment_strategy

Partition assignment strategy.

TYPE: Sequence[AbstractPartitionAssignor] DEFAULT: (RoundRobinPartitionAssignor)

max_poll_interval_ms

Maximum poll interval in milliseconds.

TYPE: int DEFAULT: 300000

rebalance_timeout_ms

Rebalance timeout in milliseconds.

TYPE: Optional[int] DEFAULT: None

session_timeout_ms

Session timeout in milliseconds.

TYPE: int DEFAULT: 10000

heartbeat_interval_ms

Heartbeat interval in milliseconds.

TYPE: int DEFAULT: 3000

consumer_timeout_ms

Consumer timeout in milliseconds.

TYPE: int DEFAULT: 200

max_poll_records

Maximum number of records to poll.

TYPE: Optional[int] DEFAULT: None

exclude_internal_topics

Whether to exclude internal topics.

TYPE: bool DEFAULT: True

isolation_level

Isolation level.

TYPE: Literal['read_uncommitted', 'read_committed'] DEFAULT: 'read_uncommitted'

dependencies

Additional dependencies for message handling.

TYPE: Sequence[Depends] DEFAULT: ()

parser

Message parser.

TYPE: Optional[Union[CustomParser[ConsumerRecord], CustomParser[Tuple[ConsumerRecord, ...]]]] DEFAULT: None

decoder

Message decoder.

TYPE: Optional[CustomDecoder] DEFAULT: None

middlewares

Message middlewares.

TYPE: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]] DEFAULT: None

filter

Message filter.

TYPE: Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[ConsumerRecord, ...]]]] DEFAULT: default_filter

batch

Whether to process messages in batches.

TYPE: bool DEFAULT: False

max_records

Maximum number of records to process in each batch.

TYPE: Optional[int] DEFAULT: None

batch_timeout_ms

Batch timeout in milliseconds.

TYPE: int DEFAULT: 200

no_ack

Whether not to ack/nack/reject messages.

TYPE: bool DEFAULT: False

title

AsyncAPI title.

TYPE: Optional[str] DEFAULT: None

description

AsyncAPI description.

TYPE: Optional[str] DEFAULT: None

**original_kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Callable

A decorator that wraps a message handler function.

TYPE: Callable[[Callable[P_HandlerParams, T_HandlerReturn]], Union[HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[Tuple[ConsumerRecord, ...], P_HandlerParams, T_HandlerReturn]]]

Source code in faststream/kafka/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[Callable[[bytes], Any]] = None,\n    value_deserializer: Optional[Callable[[bytes], Any]] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\",\n        \"earliest\",\n        \"none\",\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[AbstractPartitionAssignor] = (\n        RoundRobinPartitionAssignor,\n    ),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\",\n        \"read_committed\",\n    ] = \"read_uncommitted\",\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        Union[\n            CustomParser[aiokafka.ConsumerRecord, KafkaMessage],\n            CustomParser[Tuple[aiokafka.ConsumerRecord, ...], KafkaMessage],\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord],\n                BaseMiddleware,\n            ]\n        ]\n    ] = None,\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[aiokafka.ConsumerRecord, ...]]],\n    ] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    Union[\n        HandlerCallWrapper[\n            aiokafka.ConsumerRecord, P_HandlerParams, T_HandlerReturn\n        ],\n        HandlerCallWrapper[\n            Tuple[aiokafka.ConsumerRecord, ...], P_HandlerParams, T_HandlerReturn\n        ],\n    ],\n]:\n    \"\"\"\n    Create a message subscriber for the specified topics.\n\n    Args:\n        *topics (str): The topics to subscribe to.\n        group_id (Optional[str]): The Kafka consumer group ID.\n        key_deserializer (Optional[Callable[[bytes], Any]]): Key deserializer function.\n        value_deserializer (Optional[Callable[[bytes], Any]]): Value deserializer function.\n        fetch_max_wait_ms (int): The maximum time to wait for data.\n        fetch_max_bytes (int): The maximum number of bytes to fetch.\n        fetch_min_bytes (int): The minimum number of bytes to fetch.\n        max_partition_fetch_bytes (int): The maximum bytes to fetch for a partition.\n        auto_offset_reset (Literal[\"latest\", \"earliest\", \"none\"]): Auto offset reset policy.\n        auto_commit (bool): Whether to enable auto-commit.\n        auto_commit_interval_ms (int): Auto-commit interval in milliseconds.\n        check_crcs (bool): Whether to check CRCs.\n        partition_assignment_strategy (Sequence[AbstractPartitionAssignor]): Partition assignment strategy.\n        max_poll_interval_ms (int): Maximum poll interval in milliseconds.\n        rebalance_timeout_ms (Optional[int]): Rebalance timeout in milliseconds.\n        session_timeout_ms (int): Session timeout in milliseconds.\n        heartbeat_interval_ms (int): Heartbeat interval in milliseconds.\n        consumer_timeout_ms (int): Consumer timeout in milliseconds.\n        max_poll_records (Optional[int]): Maximum number of records to poll.\n        exclude_internal_topics (bool): Whether to exclude internal topics.\n        isolation_level (Literal[\"read_uncommitted\", \"read_committed\"]): Isolation level.\n        dependencies (Sequence[Depends]): Additional dependencies for message handling.\n        parser (Optional[Union[CustomParser[aiokafka.ConsumerRecord], CustomParser[Tuple[aiokafka.ConsumerRecord, ...]]]]): Message parser.\n        decoder (Optional[CustomDecoder]): Message decoder.\n        middlewares (Optional[Sequence[Callable[[aiokafka.ConsumerRecord], BaseMiddleware]]]): Message middlewares.\n        filter (Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[aiokafka.ConsumerRecord, ...]]]]): Message filter.\n        batch (bool): Whether to process messages in batches.\n        max_records (Optional[int]): Maximum number of records to process in each batch.\n        batch_timeout_ms (int): Batch timeout in milliseconds.\n        no_ack (bool): Whether not to ack/nack/reject messages.\n        title (Optional[str]): AsyncAPI title.\n        description (Optional[str]): AsyncAPI description.\n        **original_kwargs: Additional keyword arguments.\n\n    Returns:\n        Callable: A decorator that wraps a message handler function.\n    \"\"\"\n    super().subscriber()\n\n    self._setup_log_context(topics, group_id)\n\n    if not auto_commit and not group_id:\n        raise ValueError(\"You should install `group_id` with manual commit mode\")\n\n    key = Handler.get_routing_hash(topics, group_id)\n    builder = partial(\n        aiokafka.AIOKafkaConsumer,\n        key_deserializer=key_deserializer,\n        value_deserializer=value_deserializer,\n        fetch_max_wait_ms=fetch_max_wait_ms,\n        fetch_max_bytes=fetch_max_bytes,\n        fetch_min_bytes=fetch_min_bytes,\n        max_partition_fetch_bytes=max_partition_fetch_bytes,\n        auto_offset_reset=auto_offset_reset,\n        enable_auto_commit=auto_commit,\n        auto_commit_interval_ms=auto_commit_interval_ms,\n        check_crcs=check_crcs,\n        partition_assignment_strategy=partition_assignment_strategy,\n        max_poll_interval_ms=max_poll_interval_ms,\n        rebalance_timeout_ms=rebalance_timeout_ms,\n        session_timeout_ms=session_timeout_ms,\n        heartbeat_interval_ms=heartbeat_interval_ms,\n        consumer_timeout_ms=consumer_timeout_ms,\n        max_poll_records=max_poll_records,\n        exclude_internal_topics=exclude_internal_topics,\n        isolation_level=isolation_level,\n    )\n    handler = self.handlers.get(\n        key,\n        Handler(\n            *topics,\n            log_context_builder=partial(\n                self._get_log_context,\n                topics=topics,\n                group_id=group_id,\n            ),\n            is_manual=not auto_commit,\n            group_id=group_id,\n            client_id=self.client_id,\n            builder=builder,\n            description=description,\n            title=title,\n            batch=batch,\n            batch_timeout_ms=batch_timeout_ms,\n            max_records=max_records,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n        ),\n    )\n\n    self.handlers[key] = handler\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[\n        aiokafka.ConsumerRecord, P_HandlerParams, T_HandlerReturn\n    ]:\n        \"\"\"A wrapper function for a consumer handler.\n\n        Args:\n            func : The consumer handler function to be wrapped.\n\n        Returns:\n            The wrapped handler call.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        handler_call, dependant = self._wrap_handler(\n            func=func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/kafka/fastapi/Context/#faststream.broker.fastapi.context.Context","title":"faststream.broker.fastapi.context.Context","text":"
Context(name: str) -> Any\n
Source code in faststream/broker/fastapi/context.py
def Context(name: str) -> Any:\n    return params.Depends(\n        lambda: context.resolve(name),\n        use_cache=True,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/","title":"KafkaRouter","text":"","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter","title":"faststream.kafka.fastapi.KafkaRouter","text":"
KafkaRouter(\n    bootstrap_servers: Union[\n        str, Iterable[str]\n    ] = \"localhost\",\n    *,\n    client_id: str = \"faststream-\" + __version__,\n    request_timeout_ms: int = 40 * 1000,\n    retry_backoff_ms: int = 100,\n    metadata_max_age_ms: int = 5 * 60 * 1000,\n    api_version: str = \"auto\",\n    connections_max_idle_ms: int = 540000,\n    security: Optional[BaseSecurity] = None,\n    acks: Union[\n        Literal[0, 1, -1, \"all\"], object\n    ] = _missing,\n    key_serializer: Optional[Callable[[Any], bytes]] = None,\n    value_serializer: Optional[\n        Callable[[Any], bytes]\n    ] = None,\n    compression_type: Optional[\n        Literal[\"gzip\", \"snappy\", \"lz4\", \"zstd\"]\n    ] = None,\n    max_batch_size: int = 16384,\n    partitioner: Callable[\n        [bytes, List[Partition], List[Partition]], Partition\n    ] = DefaultPartitioner(),\n    max_request_size: int = 1048576,\n    linger_ms: int = 0,\n    send_backoff_ms: int = 100,\n    enable_idempotence: bool = False,\n    transactional_id: Optional[str] = None,\n    transaction_timeout_ms: int = 60000,\n    loop: Optional[AbstractEventLoop] = None,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id),\n    graceful_timeout: Optional[float] = None,\n    apply_types: bool = True,\n    validate: bool = True,\n    decoder: Optional[CustomDecoder[KafkaMessage]] = None,\n    parser: Optional[\n        CustomParser[aiokafka.ConsumerRecord, KafkaMessage]\n    ] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    asyncapi_url: Union[str, List[str], None] = None,\n    protocol: str = \"kafka\",\n    protocol_version: str = \"auto\",\n    description: Optional[str] = None,\n    asyncapi_tags: Optional[Sequence[asyncapi.Tag]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    setup_state: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any\n)\n

Bases: StreamRouter[ConsumerRecord]

A class to route Kafka streams.

METHOD DESCRIPTION _setup_log_context

sets up the log context for the main broker and including broker

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.broker","title":"broker instance-attribute","text":"
broker: KafkaBroker\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.broker_class","title":"broker_class class-attribute instance-attribute","text":"
broker_class: Type[KafkaBroker] = KB\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any\n) -> HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n]\n

Add an API message queue route.

PARAMETER DESCRIPTION path

The path of the route.

TYPE: Union[NameRequired, str]

*extra

Additional path segments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint function to be called for this route.

TYPE: Callable[P_HandlerParams, T_HandlerReturn]

dependencies

The dependencies required by the endpoint function.

TYPE: Sequence[Depends]

**broker_kwargs

Additional keyword arguments to be passed to the broker.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]

The handler call wrapper for the route.

Source code in faststream/broker/fastapi/router.py
def add_api_mq_route(\n    self,\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any,\n) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n    \"\"\"Add an API message queue route.\n\n    Args:\n        path: The path of the route.\n        *extra: Additional path segments.\n        endpoint: The endpoint function to be called for this route.\n        dependencies: The dependencies required by the endpoint function.\n        **broker_kwargs: Additional keyword arguments to be passed to the broker.\n\n    Returns:\n        The handler call wrapper for the route.\n\n    \"\"\"\n    route: StreamRoute[MsgType, P_HandlerParams, T_HandlerReturn] = StreamRoute(\n        path,\n        *extra,\n        endpoint=endpoint,\n        dependencies=dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        broker=self.broker,\n        **broker_kwargs,\n    )\n    self.routes.append(route)\n    return route.handler\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.publisher","title":"publisher","text":"
publisher(\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.subscriber","title":"subscriber","text":"
subscriber(\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function decorator for subscribing to a message queue.

PARAMETER DESCRIPTION path

The path to subscribe to. Can be a string or a NameRequired object.

*extra

Additional path segments. Can be a NameRequired object or a string.

DEFAULT: ()

dependencies

Optional sequence of dependencies.

DEFAULT: None

**broker_kwargs

Additional keyword arguments for the broker.

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable decorator that adds the decorated function as an endpoint for the specified path.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def subscriber(\n    self,\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function decorator for subscribing to a message queue.\n\n    Args:\n        path : The path to subscribe to. Can be a string or a `NameRequired` object.\n        *extra : Additional path segments. Can be a `NameRequired` object or a string.\n        dependencies : Optional sequence of dependencies.\n        **broker_kwargs : Additional keyword arguments for the broker.\n\n    Returns:\n        A callable decorator that adds the decorated function as an endpoint for the specified path.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    def decorator(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n        \"\"\"A decorator function.\n\n        Args:\n            func: The function to be decorated.\n\n        Returns:\n            The decorated function.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        return self.add_api_mq_route(\n            path,\n            *extra,\n            endpoint=func,\n            dependencies=current_dependencies,\n            **broker_kwargs,\n        )\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/","title":"LogicHandler","text":"","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler","title":"faststream.kafka.handler.LogicHandler","text":"
LogicHandler(\n    *topics: str,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    group_id: Optional[str] = None,\n    client_id: str = \"faststream-\" + __version__,\n    builder: Callable[..., AIOKafkaConsumer],\n    is_manual: bool = False,\n    batch: bool = False,\n    batch_timeout_ms: int = 200,\n    max_records: Optional[int] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True\n)\n

Bases: AsyncHandler[ConsumerRecord]

A class to handle logic for consuming messages from Kafka.

METHOD DESCRIPTION __init__

constructor method for the LogicHandler class

start

method to start consuming messages from Kafka

close

method to close the Kafka consumer and cancel the consuming task

add_call

method to add a handler call for processing consumed messages

_consume

method to consume messages from Kafka and call the appropriate handler

Initialize a Kafka consumer for the specified topics.

PARAMETER DESCRIPTION *topics

Variable length argument list of topics to consume from.

TYPE: str DEFAULT: ()

group_id

Optional group ID for the consumer.

TYPE: Optional[str] DEFAULT: None

client_id

Client ID for the consumer.

TYPE: str DEFAULT: 'faststream-' + __version__

builder

Callable that constructs an AIOKafkaConsumer instance.

TYPE: Callable[..., AIOKafkaConsumer]

batch

Flag indicating whether to consume messages in batches.

TYPE: bool DEFAULT: False

batch_timeout_ms

Timeout in milliseconds for batch consumption.

TYPE: int DEFAULT: 200

max_records

Maximum number of records to consume in a batch.

TYPE: Optional[int] DEFAULT: None

title

Optional title for the consumer.

TYPE: Optional[str] DEFAULT: None

description

Optional description for the consumer.

TYPE: Optional[str] DEFAULT: None

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/kafka/handler.py
@override\ndef __init__(\n    self,\n    *topics: str,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # Kafka information\n    group_id: Optional[str] = None,\n    client_id: str = \"faststream-\" + __version__,\n    builder: Callable[..., AIOKafkaConsumer],\n    is_manual: bool = False,\n    batch: bool = False,\n    batch_timeout_ms: int = 200,\n    max_records: Optional[int] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    \"\"\"Initialize a Kafka consumer for the specified topics.\n\n    Args:\n        *topics: Variable length argument list of topics to consume from.\n        group_id: Optional group ID for the consumer.\n        client_id: Client ID for the consumer.\n        builder: Callable that constructs an AIOKafkaConsumer instance.\n        batch: Flag indicating whether to consume messages in batches.\n        batch_timeout_ms: Timeout in milliseconds for batch consumption.\n        max_records: Maximum number of records to consume in a batch.\n        title: Optional title for the consumer.\n        description: Optional description for the consumer.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.group_id = group_id\n    self.client_id = client_id\n    self.topics = topics\n\n    self.batch = batch\n    self.batch_timeout_ms = batch_timeout_ms\n    self.max_records = max_records\n    self.is_manual = is_manual\n\n    self.builder = builder\n    self.task = None\n    self.consumer = None\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = batch\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.batch_timeout_ms","title":"batch_timeout_ms instance-attribute","text":"
batch_timeout_ms = batch_timeout_ms\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.builder","title":"builder instance-attribute","text":"
builder = builder\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.client_id","title":"client_id instance-attribute","text":"
client_id = client_id\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.consumer","title":"consumer class-attribute instance-attribute","text":"
consumer: Optional[AIOKafkaConsumer] = None\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.group_id","title":"group_id class-attribute instance-attribute","text":"
group_id: Optional[str] = group_id\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.is_manual","title":"is_manual instance-attribute","text":"
is_manual = is_manual\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.max_records","title":"max_records instance-attribute","text":"
max_records = max_records\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.task","title":"task class-attribute instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.topics","title":"topics instance-attribute","text":"
topics: Sequence[str] = topics\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        ConsumerRecord, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: CustomParser[\n        Union[ConsumerRecord, Tuple[ConsumerRecord, ...]],\n        KafkaMessage,\n    ],\n    decoder: Optional[CustomDecoder[KafkaMessage]],\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[ConsumerRecord, ...]]],\n    ],\n    middlewares: Optional[\n        Sequence[Callable[[ConsumerRecord], BaseMiddleware]]\n    ]\n) -> None\n

Adds a call to the handler.

PARAMETER DESCRIPTION handler

The handler function to be called.

TYPE: HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn]

dependant

The dependant model.

TYPE: CallModel[P_HandlerParams, T_HandlerReturn]

parser

Optional custom parser for parsing the input.

TYPE: CustomParser[Union[ConsumerRecord, Tuple[ConsumerRecord, ...]], KafkaMessage]

decoder

Optional custom decoder for decoding the input.

TYPE: Optional[CustomDecoder[KafkaMessage]]

filter

The filter for filtering the input.

TYPE: Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[ConsumerRecord, ...]]]]

middlewares

Optional sequence of middlewares to be applied.

TYPE: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]]

RETURNS DESCRIPTION None

None

Source code in faststream/kafka/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: CustomParser[\n        Union[ConsumerRecord, Tuple[ConsumerRecord, ...]], KafkaMessage\n    ],\n    decoder: Optional[CustomDecoder[KafkaMessage]],\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[ConsumerRecord, ...]]],\n    ],\n    middlewares: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]],\n) -> None:\n    \"\"\"Adds a call to the handler.\n\n    Args:\n        handler: The handler function to be called.\n        dependant: The dependant model.\n        parser: Optional custom parser for parsing the input.\n        decoder: Optional custom decoder for decoding the input.\n        filter: The filter for filtering the input.\n        middlewares: Optional sequence of middlewares to be applied.\n\n    Returns:\n        None\n\n    \"\"\"\n    parser_ = resolve_custom_func(  # type: ignore[type-var]\n        parser,  # type: ignore[arg-type]\n        (\n            AioKafkaParser.parse_message_batch  # type: ignore[arg-type]\n            if self.batch\n            else AioKafkaParser.parse_message\n        ),\n    )\n    decoder_ = resolve_custom_func(\n        decoder,  # type: ignore[arg-type]\n        (\n            AioKafkaParser.decode_message_batch  # type: ignore[arg-type]\n            if self.batch\n            else AioKafkaParser.decode_message\n        ),\n    )\n    super().add_call(\n        handler=handler,\n        parser=parser_,\n        decoder=decoder_,\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/kafka/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.consumer is not None:\n        await self.consumer.stop()\n        self.consumer = None\n\n    if self.task is not None:\n        self.task.cancel()\n        self.task = None\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(\n    topics: Sequence[str], group_id: Optional[str] = None\n) -> str\n
Source code in faststream/kafka/handler.py
@staticmethod\ndef get_routing_hash(topics: Sequence[str], group_id: Optional[str] = None) -> str:\n    return \"\".join((*topics, group_id or \"\"))\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.start","title":"start async","text":"
start(\n    **consumer_kwargs: Unpack[ConsumerConnectionParams],\n) -> None\n

Start the consumer.

PARAMETER DESCRIPTION **consumer_kwargs

Additional keyword arguments to pass to the consumer.

TYPE: Unpack[ConsumerConnectionParams] DEFAULT: {}

RETURNS DESCRIPTION None

None

Source code in faststream/kafka/handler.py
@override\nasync def start(  # type: ignore[override]\n    self,\n    **consumer_kwargs: Unpack[ConsumerConnectionParams],\n) -> None:\n    \"\"\"Start the consumer.\n\n    Args:\n        **consumer_kwargs: Additional keyword arguments to pass to the consumer.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.consumer = consumer = self.builder(\n        *self.topics,\n        group_id=self.group_id,\n        client_id=self.client_id,\n        **consumer_kwargs,\n    )\n    await consumer.start()\n    self.task = asyncio.create_task(self._consume())\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/","title":"KafkaMessage","text":"","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage","title":"faststream.kafka.message.KafkaMessage","text":"
KafkaMessage(\n    *args: Any,\n    consumer: aiokafka.AIOKafkaConsumer,\n    is_manual: bool = False,\n    **kwargs: Any\n)\n

Bases: StreamMessage[ConsumerRecord]

Represents a Kafka message in the FastStream framework.

This class extends StreamMessage and is specialized for handling Kafka ConsumerRecord objects.

METHOD DESCRIPTION ack

Acknowledge the Kafka message.

nack

Negative acknowledgment of the Kafka message.

reject

Reject the Kafka message.

Source code in faststream/kafka/message.py
def __init__(\n    self,\n    *args: Any,\n    consumer: aiokafka.AIOKafkaConsumer,\n    is_manual: bool = False,\n    **kwargs: Any,\n) -> None:\n    super().__init__(*args, **kwargs)\n\n    self.is_manual = is_manual\n    self.consumer = consumer\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.consumer","title":"consumer instance-attribute","text":"
consumer = consumer\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.is_manual","title":"is_manual instance-attribute","text":"
is_manual = is_manual\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.ack","title":"ack async","text":"
ack(**kwargs: Any) -> None\n

Acknowledge the Kafka message.

PARAMETER DESCRIPTION **kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

This method does not return a value.

TYPE: None

Source code in faststream/kafka/message.py
async def ack(self, **kwargs: Any) -> None:\n    \"\"\"\n    Acknowledge the Kafka message.\n\n    Args:\n        **kwargs (Any): Additional keyword arguments.\n\n    Returns:\n        None: This method does not return a value.\n    \"\"\"\n    if self.is_manual and not self.commited:\n        await self.consumer.commit()\n        await super().ack()\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.nack","title":"nack async","text":"
nack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def nack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.reject","title":"reject async","text":"
reject(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def reject(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/","title":"AioKafkaParser","text":"","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/#faststream.kafka.parser.AioKafkaParser","title":"faststream.kafka.parser.AioKafkaParser","text":"","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/#faststream.kafka.parser.AioKafkaParser.decode_message","title":"decode_message async staticmethod","text":"
decode_message(\n    msg: StreamMessage[ConsumerRecord],\n) -> DecodedMessage\n

Decodes a message.

PARAMETER DESCRIPTION msg

The message to be decoded.

TYPE: StreamMessage[ConsumerRecord]

RETURNS DESCRIPTION DecodedMessage

The decoded message.

Source code in faststream/kafka/parser.py
@staticmethod\nasync def decode_message(msg: StreamMessage[ConsumerRecord]) -> DecodedMessage:\n    \"\"\"Decodes a message.\n\n    Args:\n        msg: The message to be decoded.\n\n    Returns:\n        The decoded message.\n\n    \"\"\"\n    return decode_message(msg)\n
","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/#faststream.kafka.parser.AioKafkaParser.decode_message_batch","title":"decode_message_batch async classmethod","text":"
decode_message_batch(\n    msg: StreamMessage[Tuple[ConsumerRecord, ...]]\n) -> List[DecodedMessage]\n

Decode a batch of messages.

PARAMETER DESCRIPTION msg

A stream message containing a tuple of consumer records.

TYPE: StreamMessage[Tuple[ConsumerRecord, ...]]

RETURNS DESCRIPTION List[DecodedMessage]

A list of decoded messages.

Source code in faststream/kafka/parser.py
@classmethod\nasync def decode_message_batch(\n    cls, msg: StreamMessage[Tuple[ConsumerRecord, ...]]\n) -> List[DecodedMessage]:\n    \"\"\"Decode a batch of messages.\n\n    Args:\n        msg: A stream message containing a tuple of consumer records.\n\n    Returns:\n        A list of decoded messages.\n\n    \"\"\"\n    return [decode_message(await cls.parse_message(m)) for m in msg.raw_message]\n
","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/#faststream.kafka.parser.AioKafkaParser.parse_message","title":"parse_message async staticmethod","text":"
parse_message(\n    message: ConsumerRecord,\n) -> StreamMessage[ConsumerRecord]\n

Parses a Kafka message.

PARAMETER DESCRIPTION message

The Kafka message to parse.

TYPE: ConsumerRecord

RETURNS DESCRIPTION StreamMessage[ConsumerRecord]

A StreamMessage object representing the parsed message.

Source code in faststream/kafka/parser.py
@staticmethod\nasync def parse_message(\n    message: ConsumerRecord,\n) -> StreamMessage[ConsumerRecord]:\n    \"\"\"Parses a Kafka message.\n\n    Args:\n        message: The Kafka message to parse.\n\n    Returns:\n        A StreamMessage object representing the parsed message.\n\n    \"\"\"\n    headers = {i: j.decode() for i, j in message.headers}\n    handler = context.get_local(\"handler_\")\n    return KafkaMessage(\n        body=message.value,\n        headers=headers,\n        reply_to=headers.get(\"reply_to\", \"\"),\n        content_type=headers.get(\"content-type\"),\n        message_id=f\"{message.offset}-{message.timestamp}\",\n        correlation_id=headers.get(\"correlation_id\", str(uuid4())),\n        raw_message=message,\n        consumer=handler.consumer,\n        is_manual=handler.is_manual,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/#faststream.kafka.parser.AioKafkaParser.parse_message_batch","title":"parse_message_batch async staticmethod","text":"
parse_message_batch(\n    message: Tuple[ConsumerRecord, ...]\n) -> KafkaMessage\n

Parses a batch of messages from a Kafka consumer.

PARAMETER DESCRIPTION message

A tuple of ConsumerRecord objects representing the messages to parse.

RETURNS DESCRIPTION KafkaMessage

A StreamMessage object containing the parsed messages.

RAISES DESCRIPTION NotImplementedError

If any of the messages are silent (i.e., have no sound).

Static Method

This method is a static method. It does not require an instance of the class to be called.

Source code in faststream/kafka/parser.py
@staticmethod\nasync def parse_message_batch(\n    message: Tuple[ConsumerRecord, ...],\n) -> KafkaMessage:\n    \"\"\"Parses a batch of messages from a Kafka consumer.\n\n    Args:\n        message : A tuple of ConsumerRecord objects representing the messages to parse.\n\n    Returns:\n        A StreamMessage object containing the parsed messages.\n\n    Raises:\n        NotImplementedError: If any of the messages are silent (i.e., have no sound).\n\n    Static Method:\n        This method is a static method. It does not require an instance of the class to be called.\n\n    \"\"\"\n    first = message[0]\n    last = message[-1]\n    headers = {i: j.decode() for i, j in first.headers}\n    handler = context.get_local(\"handler_\")\n    return KafkaMessage(\n        body=[m.value for m in message],\n        headers=headers,\n        reply_to=headers.get(\"reply_to\", \"\"),\n        content_type=headers.get(\"content-type\"),\n        message_id=f\"{first.offset}-{last.offset}-{first.timestamp}\",\n        correlation_id=headers.get(\"correlation_id\", str(uuid4())),\n        raw_message=message,\n        consumer=handler.consumer,\n        is_manual=handler.is_manual,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/producer/AioKafkaFastProducer/","title":"AioKafkaFastProducer","text":"","boost":0.5},{"location":"api/faststream/kafka/producer/AioKafkaFastProducer/#faststream.kafka.producer.AioKafkaFastProducer","title":"faststream.kafka.producer.AioKafkaFastProducer","text":"
AioKafkaFastProducer(producer: AIOKafkaProducer)\n

A class to represent a fast Kafka producer.

METHOD DESCRIPTION publish

Publishes a message to a Kafka topic.

stop

Stops the Kafka producer.

publish_batch

Publishes a batch of messages to a Kafka topic.

Initialize the class.

PARAMETER DESCRIPTION producer

An instance of AIOKafkaProducer.

TYPE: AIOKafkaProducer

Source code in faststream/kafka/producer.py
def __init__(\n    self,\n    producer: AIOKafkaProducer,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        producer: An instance of AIOKafkaProducer.\n\n    \"\"\"\n    self._producer = producer\n
","boost":0.5},{"location":"api/faststream/kafka/producer/AioKafkaFastProducer/#faststream.kafka.producer.AioKafkaFastProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\"\n) -> None\n

Publish a message to a topic.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

topic

The topic to publish the message to.

TYPE: str

key

The key associated with the message.

TYPE: Optional[bytes] DEFAULT: None

partition

The partition to which the message should be sent.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

The timestamp of the message in milliseconds.

TYPE: Optional[int] DEFAULT: None

headers

Additional headers to be included with the message.

TYPE: Optional[Dict[str, str]] DEFAULT: None

correlation_id

The correlation ID of the message.

TYPE: Optional[str] DEFAULT: None

reply_to

The topic to which the reply should be sent.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION AssertionError

If the broker is not connected.

Source code in faststream/kafka/producer.py
async def publish(\n    self,\n    message: SendableMessage,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\",\n) -> None:\n    \"\"\"Publish a message to a topic.\n\n    Args:\n        message: The message to be published.\n        topic: The topic to publish the message to.\n        key: The key associated with the message.\n        partition: The partition to which the message should be sent.\n        timestamp_ms: The timestamp of the message in milliseconds.\n        headers: Additional headers to be included with the message.\n        correlation_id: The correlation ID of the message.\n        reply_to: The topic to which the reply should be sent.\n\n    Returns:\n        None\n\n    Raises:\n        AssertionError: If the broker is not connected.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n\n    message, content_type = encode_message(message)\n\n    headers_to_send = {\n        \"content-type\": content_type or \"\",\n        \"correlation_id\": correlation_id or str(uuid4()),\n        **(headers or {}),\n    }\n\n    if reply_to:\n        headers_to_send.update({\"reply_to\": reply_to})\n\n    await self._producer.send(\n        topic=topic,\n        value=message,\n        key=key,\n        partition=partition,\n        timestamp_ms=timestamp_ms,\n        headers=[(i, (j or \"\").encode()) for i, j in headers_to_send.items()],\n    )\n\n    return None\n
","boost":0.5},{"location":"api/faststream/kafka/producer/AioKafkaFastProducer/#faststream.kafka.producer.AioKafkaFastProducer.publish_batch","title":"publish_batch async","text":"
publish_batch(\n    *msgs: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None\n) -> None\n

Publish a batch of messages to a topic.

PARAMETER DESCRIPTION *msgs

Variable length argument list of messages to be sent.

TYPE: SendableMessage DEFAULT: ()

topic

The topic to which the messages should be published.

TYPE: str

partition

The partition to which the messages should be sent. Defaults to None.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

The timestamp to be associated with the messages. Defaults to None.

TYPE: Optional[int] DEFAULT: None

headers

Additional headers to be included with the messages. Defaults to None.

TYPE: Optional[Dict[str, str]] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION AssertionError

If the broker is not connected.

Source code in faststream/kafka/producer.py
async def publish_batch(\n    self,\n    *msgs: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n) -> None:\n    \"\"\"Publish a batch of messages to a topic.\n\n    Args:\n        *msgs: Variable length argument list of messages to be sent.\n        topic: The topic to which the messages should be published.\n        partition: The partition to which the messages should be sent. Defaults to None.\n        timestamp_ms: The timestamp to be associated with the messages. Defaults to None.\n        headers: Additional headers to be included with the messages. Defaults to None.\n\n    Returns:\n        None\n\n    Raises:\n        AssertionError: If the broker is not connected.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n\n    batch = self._producer.create_batch()\n\n    for msg in msgs:\n        message, content_type = encode_message(msg)\n\n        headers_to_send = {\n            \"content-type\": content_type or \"\",\n            **(headers or {}),\n        }\n\n        batch.append(\n            key=None,\n            value=message,\n            timestamp=timestamp_ms,\n            headers=[(i, j.encode()) for i, j in headers_to_send.items()],\n        )\n\n    await self._producer.send_batch(batch, topic, partition=partition)\n
","boost":0.5},{"location":"api/faststream/kafka/producer/AioKafkaFastProducer/#faststream.kafka.producer.AioKafkaFastProducer.stop","title":"stop async","text":"
stop() -> None\n
Source code in faststream/kafka/producer.py
async def stop(self) -> None:\n    if self._producer is not None:  # pragma: no branch\n        await self._producer.stop()\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/","title":"LogicPublisher","text":"","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher","title":"faststream.kafka.publisher.LogicPublisher dataclass","text":"

Bases: ABCPublisher[ConsumerRecord]

A class to publish messages to a Kafka topic.

METHOD DESCRIPTION publish

Publishes messages to the Kafka topic

RAISES DESCRIPTION AssertionError

If _producer is not set up or if multiple messages are sent without the batch flag

","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = field(default=False)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.client_id","title":"client_id class-attribute instance-attribute","text":"
client_id: str = field(default='faststream-' + __version__)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.key","title":"key class-attribute instance-attribute","text":"
key: Optional[bytes] = None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.partition","title":"partition class-attribute instance-attribute","text":"
partition: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = ''\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.timestamp_ms","title":"timestamp_ms class-attribute instance-attribute","text":"
timestamp_ms: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.topic","title":"topic class-attribute instance-attribute","text":"
topic: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.publish","title":"publish async","text":"
publish(\n    *messages: SendableMessage,\n    message: SendableMessage = \"\",\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None\n) -> None\n

Publish messages to a topic.

PARAMETER DESCRIPTION *messages

Variable length argument list of SendableMessage objects.

TYPE: SendableMessage DEFAULT: ()

message

A SendableMessage object. Default is an empty string.

TYPE: SendableMessage DEFAULT: ''

key

Optional bytes object representing the message key.

TYPE: Optional[bytes] DEFAULT: None

partition

Optional integer representing the partition to publish the message to.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

Optional integer representing the timestamp of the message in milliseconds.

TYPE: Optional[int] DEFAULT: None

headers

Optional dictionary of header key-value pairs.

TYPE: Optional[Dict[str, str]] DEFAULT: None

correlation_id

Optional string representing the correlation ID of the message.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION AssertionError

If _producer is not set up.

AssertionError

If batch flag is not set and there are multiple messages.

ValueError

If message is not a sequence when messages is empty.

Source code in faststream/kafka/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *messages: SendableMessage,\n    message: SendableMessage = \"\",\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n) -> None:\n    \"\"\"Publish messages to a topic.\n\n    Args:\n        *messages: Variable length argument list of SendableMessage objects.\n        message: A SendableMessage object. Default is an empty string.\n        key: Optional bytes object representing the message key.\n        partition: Optional integer representing the partition to publish the message to.\n        timestamp_ms: Optional integer representing the timestamp of the message in milliseconds.\n        headers: Optional dictionary of header key-value pairs.\n        correlation_id: Optional string representing the correlation ID of the message.\n\n    Returns:\n        None\n\n    Raises:\n        AssertionError: If `_producer` is not set up.\n        AssertionError: If `batch` flag is not set and there are multiple messages.\n        ValueError: If `message` is not a sequence when `messages` is empty.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    assert (  # nosec B101\n        self.batch or len(messages) < 2\n    ), \"You can't send multiple messages without `batch` flag\"\n    assert self.topic, \"You have to specify outgoing topic\"  # nosec B101\n\n    if not self.batch:\n        return await self._producer.publish(\n            message=next(iter(messages), message),\n            topic=self.topic,\n            key=key or self.key,\n            partition=partition or self.partition,\n            timestamp_ms=timestamp_ms or self.timestamp_ms,\n            correlation_id=correlation_id,\n            headers=headers or self.headers,\n            reply_to=self.reply_to or \"\",\n        )\n    else:\n        to_send: Sequence[SendableMessage]\n        if not messages:\n            if not isinstance(message, Sequence):\n                raise ValueError(\n                    f\"Message: {message} should be Sequence type to send in batch\"\n                )\n            else:\n                to_send = message\n        else:\n            to_send = messages\n\n        await self._producer.publish_batch(\n            *to_send,\n            topic=self.topic,\n            partition=partition or self.partition,\n            timestamp_ms=timestamp_ms or self.timestamp_ms,\n            headers=headers or self.headers,\n        )\n        return None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/","title":"KafkaRouter","text":"","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter","title":"faststream.kafka.router.KafkaRouter","text":"
KafkaRouter(\n    prefix: str = \"\",\n    handlers: Sequence[KafkaRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[aiokafka.ConsumerRecord, KafkaMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[KafkaMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: KafkaRouter

A class to represent a Kafka router.

METHOD DESCRIPTION _get_publisher_key

Get the key for a publisher

_update_publisher_prefix

Update the prefix of a publisher

publisher

Create a new publisher

Source code in faststream/kafka/router.py
        publisher: The publisher object.\n\n    Returns:\n        The publisher key.\n\n    \"\"\"\n    return publisher.topic\n\n@override\n@staticmethod\ndef _update_publisher_prefix(  # type: ignore[override]\n    prefix: str,\n    publisher: Publisher,\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.publisher","title":"publisher","text":"
publisher(\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n

Publishes a message to a topic.

PARAMETER DESCRIPTION topic

The topic to publish the message to.

TYPE: str

key

The key associated with the message.

TYPE: bytes DEFAULT: None

partition

The partition to publish the message to.

TYPE: int DEFAULT: None

timestamp_ms

The timestamp of the message in milliseconds.

TYPE: int DEFAULT: None

headers

Additional headers for the message.

TYPE: Dict[str, str] DEFAULT: None

reply_to

The topic to reply to.

TYPE: str DEFAULT: ''

batch

Whether to publish the message as part of a batch.

TYPE: bool DEFAULT: False

title

The title of the message.

TYPE: str DEFAULT: None

description

The description of the message.

TYPE: str DEFAULT: None

RETURNS DESCRIPTION Publisher

The publisher object used to publish the message.

TYPE: Publisher

Source code in faststream/kafka/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"Publishes a message to a topic.\n\n    Args:\n        topic (str): The topic to publish the message to.\n        key (bytes, optional): The key associated with the message.\n        partition (int, optional): The partition to publish the message to.\n        timestamp_ms (int, optional): The timestamp of the message in milliseconds.\n        headers (Dict[str, str], optional): Additional headers for the message.\n        reply_to (str, optional): The topic to reply to.\n        batch (bool, optional): Whether to publish the message as part of a batch.\n        title (str, optional): The title of the message.\n        description (str, optional): The description of the message.\n\n    Returns:\n        Publisher: The publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            topic=topic,\n            key=key,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            batch=batch,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.subscriber","title":"subscriber","text":"
subscriber(\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    value_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\", \"earliest\", \"none\"\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[\n        AbstractPartitionAssignor\n    ] = (RoundRobinPartitionAssignor),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\", \"read_committed\"\n    ] = \"read_uncommitted\",\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[aiokafka.ConsumerRecord, KafkaMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[KafkaMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Filter[KafkaMessage] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    retry: Union[bool, int] = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aiokafka.ConsumerRecord,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n
Source code in faststream/kafka/router.py
    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"Publishes a message to a topic.\n\n    Args:\n        topic (str): The topic to publish the message to.\n        key (bytes, optional): The key associated with the message.\n        partition (int, optional): The partition to publish the message to.\n        timestamp_ms (int, optional): The timestamp of the message in milliseconds.\n        headers (Dict[str, str], optional): Additional headers for the message.\n        reply_to (str, optional): The topic to reply to.\n        batch (bool, optional): Whether to publish the message as part of a batch.\n        title (str, optional): The title of the message.\n        description (str, optional): The description of the message.\n\n    Returns:\n        Publisher: The publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            topic=topic,\n            key=key,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            batch=batch,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/security/parse_security/","title":"parse_security","text":"","boost":0.5},{"location":"api/faststream/kafka/security/parse_security/#faststream.kafka.security.parse_security","title":"faststream.kafka.security.parse_security","text":"
parse_security(security: Optional[BaseSecurity]) -> AnyDict\n
Source code in faststream/kafka/security.py
def parse_security(security: Optional[BaseSecurity]) -> AnyDict:\n    if security is None:\n        return {}\n    elif type(security) == BaseSecurity:\n        return _parse_base_security(security)\n    elif type(security) == SASLPlaintext:\n        return _parse_sasl_plaintext(security)\n    elif type(security) == SASLScram256:\n        return _parse_sasl_scram256(security)\n    elif type(security) == SASLScram512:\n        return _parse_sasl_scram512(security)\n    else:\n        raise NotImplementedError(f\"KafkaBroker does not support {type(security)}\")\n
","boost":0.5},{"location":"api/faststream/kafka/shared/logging/KafkaLoggingMixin/","title":"KafkaLoggingMixin","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/logging/KafkaLoggingMixin/#faststream.kafka.shared.logging.KafkaLoggingMixin","title":"faststream.kafka.shared.logging.KafkaLoggingMixin","text":"
KafkaLoggingMixin(\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any\n)\n

Bases: LoggingMixin

A class that provides logging functionality for Kafka.

METHOD DESCRIPTION __init__

initializes the KafkaLoggingMixin object

_get_log_context

returns the log context for a given message and topics

fmt

returns the log format string

_setup_log_context

sets up the log context for a given list of topics

Initialize the class.

PARAMETER DESCRIPTION *args

Variable length argument list

TYPE: Any DEFAULT: ()

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: access_logger

log_level

Log level (default: logging.INFO)

TYPE: int DEFAULT: INFO

log_fmt

Optional log format string

TYPE: Optional[str] DEFAULT: None

**kwargs

Arbitrary keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None

Source code in faststream/kafka/shared/logging.py
def __init__(\n    self,\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        *args: Variable length argument list\n        logger: Optional logger object\n        log_level: Log level (default: logging.INFO)\n        log_fmt: Optional log format string\n        **kwargs: Arbitrary keyword arguments\n\n    Returns:\n        None\n\n    \"\"\"\n    super().__init__(\n        *args,\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n        **kwargs,\n    )\n    self._max_topic_len = 4\n    self._max_group_len = 0\n
","boost":0.5},{"location":"api/faststream/kafka/shared/logging/KafkaLoggingMixin/#faststream.kafka.shared.logging.KafkaLoggingMixin.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/logging/KafkaLoggingMixin/#faststream.kafka.shared.logging.KafkaLoggingMixin.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/kafka/shared/logging/KafkaLoggingMixin/#faststream.kafka.shared.logging.KafkaLoggingMixin.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/","title":"ABCPublisher","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher","title":"faststream.kafka.shared.publisher.ABCPublisher dataclass","text":"

Bases: ABC, BasePublisher[MsgType]

A class representing an ABCPublisher.

","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = None\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.key","title":"key class-attribute instance-attribute","text":"
key: Optional[bytes] = None\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.partition","title":"partition class-attribute instance-attribute","text":"
partition: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = ''\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.timestamp_ms","title":"timestamp_ms class-attribute instance-attribute","text":"
timestamp_ms: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.topic","title":"topic class-attribute instance-attribute","text":"
topic: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.publish","title":"publish abstractmethod async","text":"
publish(\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

correlation_id

Optional correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/publisher.py
@abstractmethod\nasync def publish(\n    self,\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        correlation_id: Optional correlation ID for the message.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/","title":"BrokerRouter","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter","title":"faststream.broker.router.BrokerRouter","text":"
BrokerRouter(\n    prefix: str = \"\",\n    handlers: Sequence[\n        BrokerRoute[MsgType, SendableMessage]\n    ] = (),\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    include_in_schema: Optional[bool] = None,\n)\n

Bases: Generic[PublisherKeyType, MsgType]

A generic class representing a broker router.

METHOD DESCRIPTION _get_publisher_key

abstract method to get the publisher key

_update_publisher_prefix

abstract method to update the publisher prefix

__init__

constructor method

subscriber

abstract method to define a subscriber

_wrap_subscriber

method to wrap a subscriber function

publisher

abstract method to define a publisher

include_router

method to include a router

include_routers

method to include multiple routers

Initialize a class object.

PARAMETER DESCRIPTION prefix

Prefix for the object.

TYPE: str DEFAULT: ''

handlers

Handlers for the object.

TYPE: Sequence[BrokerRoute[MsgType, SendableMessage]] DEFAULT: ()

dependencies

Dependencies for the object.

TYPE: Sequence[Depends] DEFAULT: ()

middlewares

Middlewares for the object.

TYPE: Optional[Sequence[Callable[[StreamMessage[MsgType]], AsyncContextManager[None]]]] DEFAULT: None

parser

Parser for the object.

TYPE: Optional[CustomParser[MsgType]] DEFAULT: None

decoder

Decoder for the object.

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

Source code in faststream/broker/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[BrokerRoute[MsgType, SendableMessage]] = (),\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    include_in_schema: Optional[bool] = None,\n) -> None:\n    \"\"\"Initialize a class object.\n\n    Args:\n        prefix (str): Prefix for the object.\n        handlers (Sequence[BrokerRoute[MsgType, SendableMessage]]): Handlers for the object.\n        dependencies (Sequence[Depends]): Dependencies for the object.\n        middlewares (Optional[Sequence[Callable[[StreamMessage[MsgType]], AsyncContextManager[None]]]]): Middlewares for the object.\n        parser (Optional[CustomParser[MsgType]]): Parser for the object.\n        decoder (Optional[CustomDecoder[StreamMessage[MsgType]]]): Decoder for the object.\n\n    \"\"\"\n    self.prefix = prefix\n    self.include_in_schema = include_in_schema\n    self._handlers = list(handlers)\n    self._publishers = {}\n    self._dependencies = dependencies\n    self._middlewares = middlewares\n    self._parser = parser\n    self._decoder = decoder\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.subscriber","title":"subscriber abstractmethod","text":"
subscriber(\n    subj: str,\n    *args: Any,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    include_in_schema: Optional[bool] = None,\n    **kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function to subscribe to a subject.

PARAMETER DESCRIPTION subj

subject to subscribe to

*args

additional arguments

DEFAULT: ()

dependencies

sequence of dependencies

DEFAULT: ()

middlewares

optional sequence of middlewares

DEFAULT: None

parser

optional custom parser

DEFAULT: None

decoder

optional custom decoder

DEFAULT: None

**kwargs

additional keyword arguments

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable handler function

RAISES DESCRIPTION NotImplementedError

If the function is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef subscriber(\n    self,\n    subj: str,\n    *args: Any,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    include_in_schema: Optional[bool] = None,\n    **kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function to subscribe to a subject.\n\n    Args:\n        subj : subject to subscribe to\n        *args : additional arguments\n        dependencies : sequence of dependencies\n        middlewares : optional sequence of middlewares\n        parser : optional custom parser\n        decoder : optional custom decoder\n        **kwargs : additional keyword arguments\n\n    Returns:\n        A callable handler function\n\n    Raises:\n        NotImplementedError: If the function is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRoute/","title":"KafkaRoute","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/","title":"KafkaRouter","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter","title":"faststream.kafka.shared.router.KafkaRouter","text":"
KafkaRouter(\n    prefix: str = \"\",\n    handlers: Sequence[\n        KafkaRoute[ConsumerRecord, SendableMessage]\n    ] = (),\n    **kwargs: Any\n)\n

Bases: BrokerRouter[str, ConsumerRecord]

A class to represent a Kafka router.

METHOD DESCRIPTION subscriber

decorator for subscribing to topics and handling messages

Initialize the class.

PARAMETER DESCRIPTION prefix

Prefix string.

TYPE: str DEFAULT: ''

handlers

Sequence of KafkaRoute objects.

TYPE: Sequence[BrokerRoute[ConsumerRecord, SendableMessage]] DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/kafka/shared/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[KafkaRoute[ConsumerRecord, SendableMessage]] = (),\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        prefix (str): Prefix string.\n        handlers (Sequence[KafkaRoute[ConsumerRecord, SendableMessage]]): Sequence of KafkaRoute objects.\n        **kwargs (Any): Additional keyword arguments.\n\n    \"\"\"\n    for h in handlers:\n        h.args = tuple(prefix + x for x in h.args)\n    super().__init__(prefix, handlers, **kwargs)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.subscriber","title":"subscriber","text":"
subscriber(\n    *topics: str, **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        ConsumerRecord, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function to subscribe to topics.

PARAMETER DESCRIPTION *topics

variable number of topic names

DEFAULT: ()

**broker_kwargs

keyword arguments for the broker

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn]]

A callable function that wraps the handler function

Source code in faststream/kafka/shared/router.py
def subscriber(\n    self,\n    *topics: str,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function to subscribe to topics.\n\n    Args:\n        *topics : variable number of topic names\n        **broker_kwargs : keyword arguments for the broker\n\n    Returns:\n        A callable function that wraps the handler function\n\n    \"\"\"\n    return self._wrap_subscriber(\n        *(self.prefix + x for x in topics),\n        **broker_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/","title":"ConsumerConnectionParams","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams","title":"faststream.kafka.shared.schemas.ConsumerConnectionParams","text":"

Bases: TypedDict

A class to represent the connection parameters for a consumer.

","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.api_version","title":"api_version instance-attribute","text":"
api_version: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.bootstrap_servers","title":"bootstrap_servers instance-attribute","text":"
bootstrap_servers: Required[Union[str, List[str]]]\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.client_id","title":"client_id instance-attribute","text":"
client_id: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.connections_max_idle_ms","title":"connections_max_idle_ms instance-attribute","text":"
connections_max_idle_ms: int\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.loop","title":"loop instance-attribute","text":"
loop: Optional[AbstractEventLoop]\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.metadata_max_age_ms","title":"metadata_max_age_ms instance-attribute","text":"
metadata_max_age_ms: int\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.request_timeout_ms","title":"request_timeout_ms instance-attribute","text":"
request_timeout_ms: int\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.retry_backoff_ms","title":"retry_backoff_ms instance-attribute","text":"
retry_backoff_ms: int\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_kerberos_domain_name","title":"sasl_kerberos_domain_name instance-attribute","text":"
sasl_kerberos_domain_name: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_kerberos_service_name","title":"sasl_kerberos_service_name instance-attribute","text":"
sasl_kerberos_service_name: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_mechanism","title":"sasl_mechanism instance-attribute","text":"
sasl_mechanism: Literal[\n    \"PLAIN\",\n    \"GSSAPI\",\n    \"SCRAM-SHA-256\",\n    \"SCRAM-SHA-512\",\n    \"OAUTHBEARER\",\n]\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_oauth_token_provider","title":"sasl_oauth_token_provider instance-attribute","text":"
sasl_oauth_token_provider: AbstractTokenProvider\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_plain_password","title":"sasl_plain_password instance-attribute","text":"
sasl_plain_password: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_plain_username","title":"sasl_plain_username instance-attribute","text":"
sasl_plain_username: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.security_protocol","title":"security_protocol instance-attribute","text":"
security_protocol: Literal['SSL', 'PLAINTEXT']\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context: ssl.SSLContext\n
","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/","title":"FakeProducer","text":"","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/#faststream.kafka.test.FakeProducer","title":"faststream.kafka.test.FakeProducer","text":"
FakeProducer(broker: KafkaBroker)\n

Bases: AioKafkaFastProducer

A fake Kafka producer for testing purposes.

This class extends AioKafkaFastProducer and is used to simulate Kafka message publishing during tests.

Initialize the FakeProducer.

PARAMETER DESCRIPTION broker

The KafkaBroker instance to associate with this FakeProducer.

TYPE: KafkaBroker

Source code in faststream/kafka/test.py
def __init__(self, broker: KafkaBroker) -> None:\n    \"\"\"\n    Initialize the FakeProducer.\n\n    Args:\n        broker (KafkaBroker): The KafkaBroker instance to associate with this FakeProducer.\n    \"\"\"\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/#faststream.kafka.test.FakeProducer.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/#faststream.kafka.test.FakeProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\",\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False\n) -> Optional[SendableMessage]\n

Publish a message to the Kafka broker.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

topic

The Kafka topic to publish the message to.

TYPE: str

key

The message key. Defaults to None.

TYPE: Optional[bytes] DEFAULT: None

partition

The Kafka partition to use. Defaults to None.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

The message timestamp in milliseconds. Defaults to None.

TYPE: Optional[int] DEFAULT: None

headers

Additional headers for the message. Defaults to None.

TYPE: Optional[Dict[str, str]] DEFAULT: None

correlation_id

The correlation ID for the message. Defaults to None.

TYPE: Optional[str] DEFAULT: None

reply_to

The topic to which responses should be sent. Defaults to \"\".

TYPE: str DEFAULT: ''

rpc

If True, treat the message as an RPC request. Defaults to False.

TYPE: bool DEFAULT: False

rpc_timeout

Timeout for RPC requests. Defaults to None.

TYPE: Optional[float] DEFAULT: None

raise_timeout

If True, raise an exception on timeout. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION Optional[SendableMessage]

Optional[SendableMessage]: The response message, if this was an RPC request, otherwise None.

Source code in faststream/kafka/test.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\",\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False,\n) -> Optional[SendableMessage]:\n    \"\"\"\n    Publish a message to the Kafka broker.\n\n    Args:\n        message (SendableMessage): The message to be published.\n        topic (str): The Kafka topic to publish the message to.\n        key (Optional[bytes], optional): The message key. Defaults to None.\n        partition (Optional[int], optional): The Kafka partition to use. Defaults to None.\n        timestamp_ms (Optional[int], optional): The message timestamp in milliseconds. Defaults to None.\n        headers (Optional[Dict[str, str]], optional): Additional headers for the message. Defaults to None.\n        correlation_id (Optional[str], optional): The correlation ID for the message. Defaults to None.\n        reply_to (str, optional): The topic to which responses should be sent. Defaults to \"\".\n        rpc (bool, optional): If True, treat the message as an RPC request. Defaults to False.\n        rpc_timeout (Optional[float], optional): Timeout for RPC requests. Defaults to None.\n        raise_timeout (bool, optional): If True, raise an exception on timeout. Defaults to False.\n\n    Returns:\n        Optional[SendableMessage]: The response message, if this was an RPC request, otherwise None.\n    \"\"\"\n    incoming = build_message(\n        message=message,\n        topic=topic,\n        key=key,\n        partition=partition,\n        timestamp_ms=timestamp_ms,\n        headers=headers,\n        correlation_id=correlation_id,\n        reply_to=reply_to,\n    )\n\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        if topic in handler.topics:\n            return await call_handler(\n                handler=handler,\n                message=[incoming] if handler.batch else incoming,\n                rpc=rpc,\n                rpc_timeout=rpc_timeout,\n                raise_timeout=raise_timeout,\n            )\n\n    return None\n
","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/#faststream.kafka.test.FakeProducer.publish_batch","title":"publish_batch async","text":"
publish_batch(\n    *msgs: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None\n) -> None\n

Publish a batch of messages to the Kafka broker.

PARAMETER DESCRIPTION *msgs

Variable number of messages to be published.

TYPE: SendableMessage DEFAULT: ()

topic

The Kafka topic to publish the messages to.

TYPE: str

partition

The Kafka partition to use. Defaults to None.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

The message timestamp in milliseconds. Defaults to None.

TYPE: Optional[int] DEFAULT: None

headers

Additional headers for the messages. Defaults to None.

TYPE: Optional[Dict[str, str]] DEFAULT: None

RETURNS DESCRIPTION None

This method does not return a value.

TYPE: None

Source code in faststream/kafka/test.py
async def publish_batch(\n    self,\n    *msgs: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n) -> None:\n    \"\"\"\n    Publish a batch of messages to the Kafka broker.\n\n    Args:\n        *msgs (SendableMessage): Variable number of messages to be published.\n        topic (str): The Kafka topic to publish the messages to.\n        partition (Optional[int], optional): The Kafka partition to use. Defaults to None.\n        timestamp_ms (Optional[int], optional): The message timestamp in milliseconds. Defaults to None.\n        headers (Optional[Dict[str, str]], optional): Additional headers for the messages. Defaults to None.\n\n    Returns:\n        None: This method does not return a value.\n    \"\"\"\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        if topic in handler.topics:\n            await call_handler(\n                handler=handler,\n                message=[\n                    build_message(\n                        message=message,\n                        topic=topic,\n                        partition=partition,\n                        timestamp_ms=timestamp_ms,\n                        headers=headers,\n                    )\n                    for message in msgs\n                ],\n            )\n\n    return None\n
","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/#faststream.kafka.test.FakeProducer.stop","title":"stop async","text":"
stop() -> None\n
Source code in faststream/kafka/producer.py
async def stop(self) -> None:\n    if self._producer is not None:  # pragma: no branch\n        await self._producer.stop()\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/","title":"TestKafkaBroker","text":"","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker","title":"faststream.kafka.test.TestKafkaBroker","text":"
TestKafkaBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[KafkaBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/kafka/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: KafkaBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(  # type: ignore[call-overload,misc]\n        publisher.topic,\n        batch=publisher.batch,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f  # type: ignore[no-any-return]\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: KafkaBroker, publisher: Any\n) -> None\n
Source code in faststream/kafka/test.py
@staticmethod\ndef patch_publisher(broker: KafkaBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> None\n
Source code in faststream/kafka/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> None:\n    broker.handlers.pop(publisher.topic, None)\n
","boost":0.5},{"location":"api/faststream/kafka/test/build_message/","title":"build_message","text":"","boost":0.5},{"location":"api/faststream/kafka/test/build_message/#faststream.kafka.test.build_message","title":"faststream.kafka.test.build_message","text":"
build_message(\n    message: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    key: Optional[bytes] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\"\n) -> ConsumerRecord\n

Build a Kafka ConsumerRecord for a sendable message.

PARAMETER DESCRIPTION message

The sendable message to be encoded.

TYPE: SendableMessage

topic

The Kafka topic for the message.

TYPE: str

partition

The Kafka partition for the message. Defaults to None.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

The message timestamp in milliseconds. Defaults to None.

TYPE: Optional[int] DEFAULT: None

key

The message key. Defaults to None.

TYPE: Optional[bytes] DEFAULT: None

headers

Additional headers for the message. Defaults to None.

TYPE: Optional[Dict[str, str]] DEFAULT: None

correlation_id

The correlation ID for the message. Defaults to None.

TYPE: Optional[str] DEFAULT: None

reply_to

The topic to which responses should be sent. Defaults to \"\".

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION ConsumerRecord

A Kafka ConsumerRecord object.

TYPE: ConsumerRecord

Source code in faststream/kafka/test.py
def build_message(\n    message: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    key: Optional[bytes] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\",\n) -> ConsumerRecord:\n    \"\"\"\n    Build a Kafka ConsumerRecord for a sendable message.\n\n    Args:\n        message (SendableMessage): The sendable message to be encoded.\n        topic (str): The Kafka topic for the message.\n        partition (Optional[int], optional): The Kafka partition for the message. Defaults to None.\n        timestamp_ms (Optional[int], optional): The message timestamp in milliseconds. Defaults to None.\n        key (Optional[bytes], optional): The message key. Defaults to None.\n        headers (Optional[Dict[str, str]], optional): Additional headers for the message. Defaults to None.\n        correlation_id (Optional[str], optional): The correlation ID for the message. Defaults to None.\n        reply_to (str, optional): The topic to which responses should be sent. Defaults to \"\".\n\n    Returns:\n        ConsumerRecord: A Kafka ConsumerRecord object.\n    \"\"\"\n    msg, content_type = encode_message(message)\n    k = key or b\"\"\n    headers = {\n        \"content-type\": content_type or \"\",\n        \"correlation_id\": correlation_id or str(uuid4()),\n        \"reply_to\": reply_to,\n        **(headers or {}),\n    }\n\n    return ConsumerRecord(\n        value=msg,\n        topic=topic,\n        partition=partition or 0,\n        timestamp=timestamp_ms or int(datetime.now().timestamp()),\n        timestamp_type=0,\n        key=k,\n        serialized_key_size=len(k),\n        serialized_value_size=len(msg),\n        checksum=sum(msg),\n        offset=0,\n        headers=[(i, j.encode()) for i, j in headers.items()],\n    )\n
","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/","title":"ColourizedFormatter","text":"","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/#faststream.log.formatter.ColourizedFormatter","title":"faststream.log.formatter.ColourizedFormatter","text":"
ColourizedFormatter(\n    fmt: Optional[str] = None,\n    datefmt: Optional[str] = None,\n    style: Literal[\"%\", \"{\", \"$\"] = \"%\",\n    use_colors: Optional[bool] = None,\n)\n

Bases: Formatter

A class to format log messages with colorized level names.

METHOD DESCRIPTION __init__

Initialize the formatter with specified format strings.

color_level_name

Colorize the level name based on the log level.

formatMessage

Format the log record message with colorized level name.

Initialize the formatter with specified format strings.

Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.

Use a style parameter of '%', '{' or '$' to specify that you want to use one of %-formatting, :meth:str.format ({}) formatting or :class:string.Template formatting in your format string.

Source code in faststream/log/formatter.py
def __init__(\n    self,\n    fmt: Optional[str] = None,\n    datefmt: Optional[str] = None,\n    style: Literal[\"%\", \"{\", \"$\"] = \"%\",\n    use_colors: Optional[bool] = None,\n) -> None:\n    \"\"\"\n    Initialize the formatter with specified format strings.\n\n    Initialize the formatter either with the specified format string, or a\n    default as described above. Allow for specialized date formatting with\n    the optional datefmt argument. If datefmt is omitted, you get an\n    ISO8601-like (or RFC 3339-like) format.\n\n    Use a style parameter of '%', '{' or '$' to specify that you want to\n    use one of %-formatting, :meth:`str.format` (``{}``) formatting or\n    :class:`string.Template` formatting in your format string.\n    \"\"\"\n    if use_colors in (True, False):\n        self.use_colors = use_colors\n    else:\n        self.use_colors = sys.stdout.isatty()\n    super().__init__(fmt=fmt, datefmt=datefmt, style=style)\n
","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/#faststream.log.formatter.ColourizedFormatter.level_name_colors","title":"level_name_colors class-attribute instance-attribute","text":"
level_name_colors: DefaultDict[\n    str, Callable[[str], str]\n] = defaultdict(\n    lambda: str,\n    **{\n        str(logging.DEBUG): lambda: click.style(\n            str(level_name), fg=\"cyan\"\n        ),\n        str(logging.INFO): lambda: click.style(\n            str(level_name), fg=\"green\"\n        ),\n        str(logging.WARNING): lambda: click.style(\n            str(level_name), fg=\"yellow\"\n        ),\n        str(logging.ERROR): lambda: click.style(\n            str(level_name), fg=\"red\"\n        ),\n        str(logging.CRITICAL): lambda: click.style(\n            str(level_name), fg=\"bright_red\"\n        ),\n    }\n)\n
","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/#faststream.log.formatter.ColourizedFormatter.use_colors","title":"use_colors instance-attribute","text":"
use_colors = use_colors\n
","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/#faststream.log.formatter.ColourizedFormatter.color_level_name","title":"color_level_name","text":"
color_level_name(level_name: str, level_no: int) -> str\n

Returns the colored level name.

PARAMETER DESCRIPTION level_name

The name of the level.

TYPE: str

level_no

The number of the level.

TYPE: int

RETURNS DESCRIPTION str

The colored level name.

RAISES DESCRIPTION KeyError

If the level number is not found in the level name colors dictionary.

Source code in faststream/log/formatter.py
def color_level_name(self, level_name: str, level_no: int) -> str:\n    \"\"\"Returns the colored level name.\n\n    Args:\n        level_name: The name of the level.\n        level_no: The number of the level.\n\n    Returns:\n        The colored level name.\n\n    Raises:\n        KeyError: If the level number is not found in the level name colors dictionary.\n\n    \"\"\"\n    return self.level_name_colors[str(level_no)](level_name)\n
","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/#faststream.log.formatter.ColourizedFormatter.formatMessage","title":"formatMessage","text":"
formatMessage(record: logging.LogRecord) -> str\n

Formats the log message.

PARAMETER DESCRIPTION record

The log record to format.

TYPE: LogRecord

RETURNS DESCRIPTION str

The formatted log message.

TYPE: str

Source code in faststream/log/formatter.py
def formatMessage(self, record: logging.LogRecord) -> str:\n    \"\"\"Formats the log message.\n\n    Args:\n        record (logging.LogRecord): The log record to format.\n\n    Returns:\n        str: The formatted log message.\n\n    \"\"\"\n    levelname = expand_log_field(record.levelname, 8)\n    if self.use_colors is True:  # pragma: no cover\n        levelname = self.color_level_name(levelname, record.levelno)\n    record.__dict__[\"levelname\"] = levelname\n    return super().formatMessage(record)\n
","boost":0.5},{"location":"api/faststream/log/formatter/expand_log_field/","title":"expand_log_field","text":"","boost":0.5},{"location":"api/faststream/log/formatter/expand_log_field/#faststream.log.formatter.expand_log_field","title":"faststream.log.formatter.expand_log_field","text":"
expand_log_field(field: str, symbols: int) -> str\n

Expands a log field by adding spaces.

PARAMETER DESCRIPTION field

The log field to expand.

TYPE: str

symbols

The desired length of the expanded field.

TYPE: int

RETURNS DESCRIPTION str

The expanded log field.

Source code in faststream/log/formatter.py
def expand_log_field(field: str, symbols: int) -> str:\n    \"\"\"Expands a log field by adding spaces.\n\n    Args:\n        field: The log field to expand.\n        symbols: The desired length of the expanded field.\n\n    Returns:\n        The expanded log field.\n\n    \"\"\"\n    return field + (\" \" * (symbols - len(field)))\n
","boost":0.5},{"location":"api/faststream/log/formatter/make_record_with_extra/","title":"make_record_with_extra","text":"","boost":0.5},{"location":"api/faststream/log/formatter/make_record_with_extra/#faststream.log.formatter.make_record_with_extra","title":"faststream.log.formatter.make_record_with_extra","text":"
make_record_with_extra(\n    self: logging.Logger,\n    name: str,\n    level: int,\n    fn: str,\n    lno: int,\n    msg: str,\n    args: Tuple[str],\n    exc_info: Optional[\n        Union[\n            Tuple[\n                Type[BaseException],\n                BaseException,\n                Optional[TracebackType],\n            ],\n            Tuple[None, None, None],\n        ]\n    ],\n    func: Optional[str] = None,\n    extra: Optional[Mapping[str, object]] = None,\n    sinfo: Optional[str] = None,\n) -> logging.LogRecord\n

Creates a log record with additional information.

PARAMETER DESCRIPTION self

The logger object.

TYPE: Logger

name

The name of the logger.

TYPE: str

level

The logging level.

TYPE: int

fn

The filename where the log message originated.

TYPE: str

lno

The line number where the log message originated.

TYPE: int

msg

The log message.

TYPE: str

args

The arguments for the log message.

TYPE: Tuple[str]

exc_info

Information about an exception.

TYPE: Optional[Union[Tuple[Type[BaseException], BaseException, Optional[TracebackType]], Tuple[None, None, None]]]

func

The name of the function where the log message originated.

TYPE: Optional[str] DEFAULT: None

extra

Additional information to include in the log record.

TYPE: Optional[Mapping[str, object]] DEFAULT: None

sinfo

Stack information.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION LogRecord

The log record.

Note

If extra is None, it will be set to the value of context.get_local(\"log_context\").

Source code in faststream/log/formatter.py
def make_record_with_extra(\n    self: logging.Logger,\n    name: str,\n    level: int,\n    fn: str,\n    lno: int,\n    msg: str,\n    args: Tuple[str],\n    exc_info: Optional[\n        Union[\n            Tuple[Type[BaseException], BaseException, Optional[TracebackType]],\n            Tuple[None, None, None],\n        ]\n    ],\n    func: Optional[str] = None,\n    extra: Optional[Mapping[str, object]] = None,\n    sinfo: Optional[str] = None,\n) -> logging.LogRecord:\n    \"\"\"Creates a log record with additional information.\n\n    Args:\n        self: The logger object.\n        name: The name of the logger.\n        level: The logging level.\n        fn: The filename where the log message originated.\n        lno: The line number where the log message originated.\n        msg: The log message.\n        args: The arguments for the log message.\n        exc_info: Information about an exception.\n        func: The name of the function where the log message originated.\n        extra: Additional information to include in the log record.\n        sinfo: Stack information.\n\n    Returns:\n        The log record.\n\n    Note:\n        If `extra` is `None`, it will be set to the value of `context.get_local(\"log_context\")`.\n\n    \"\"\"\n    if extra is None:\n        extra = context.get_local(\n            \"log_context\", default=context.get(\"default_log_context\")\n        )\n\n    record = original_makeRecord(\n        self,\n        name,\n        level,\n        fn,\n        lno,\n        msg,\n        args,\n        exc_info,\n        func,\n        extra,\n        sinfo,\n    )\n\n    return record\n
","boost":0.5},{"location":"api/faststream/log/logging/configure_formatter/","title":"configure_formatter","text":"","boost":0.5},{"location":"api/faststream/log/logging/configure_formatter/#faststream.log.logging.configure_formatter","title":"faststream.log.logging.configure_formatter","text":"
configure_formatter(\n    formatter: Type[logging.Formatter],\n    *args: Any,\n    **kwargs: Any\n) -> logging.Formatter\n

Configures a logging formatter.

PARAMETER DESCRIPTION formatter

The type of logging formatter to configure.

TYPE: Type[Formatter]

*args

Additional positional arguments to pass to the formatter constructor.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments to pass to the formatter constructor.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Formatter

An instance of the configured logging formatter.

Source code in faststream/log/logging.py
def configure_formatter(\n    formatter: Type[logging.Formatter], *args: Any, **kwargs: Any\n) -> logging.Formatter:\n    \"\"\"Configures a logging formatter.\n\n    Args:\n        formatter: The type of logging formatter to configure.\n        *args: Additional positional arguments to pass to the formatter constructor.\n        **kwargs: Additional keyword arguments to pass to the formatter constructor.\n\n    Returns:\n        An instance of the configured logging formatter.\n\n    \"\"\"\n    return formatter(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/nats/AckPolicy/","title":"AckPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/AckPolicy/#nats.js.api.AckPolicy","title":"nats.js.api.AckPolicy","text":"

Bases: str, Enum

Policies defining how messages should be acknowledged.

If an ack is required but is not received within the AckWait window, the message will be redelivered.

References ","boost":0.5},{"location":"api/faststream/nats/AckPolicy/#nats.js.api.AckPolicy.ALL","title":"ALL class-attribute instance-attribute","text":"
ALL = 'all'\n
","boost":0.5},{"location":"api/faststream/nats/AckPolicy/#nats.js.api.AckPolicy.EXPLICIT","title":"EXPLICIT class-attribute instance-attribute","text":"
EXPLICIT = 'explicit'\n
","boost":0.5},{"location":"api/faststream/nats/AckPolicy/#nats.js.api.AckPolicy.NONE","title":"NONE class-attribute instance-attribute","text":"
NONE = 'none'\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/","title":"ConsumerConfig","text":"","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig","title":"nats.js.api.ConsumerConfig dataclass","text":"

Bases: Base

Consumer configuration.

References ","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.ack_policy","title":"ack_policy class-attribute instance-attribute","text":"
ack_policy: Optional[AckPolicy] = AckPolicy.EXPLICIT\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.ack_wait","title":"ack_wait class-attribute instance-attribute","text":"
ack_wait: Optional[float] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.deliver_group","title":"deliver_group class-attribute instance-attribute","text":"
deliver_group: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.deliver_policy","title":"deliver_policy class-attribute instance-attribute","text":"
deliver_policy: Optional[DeliverPolicy] = DeliverPolicy.ALL\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.deliver_subject","title":"deliver_subject class-attribute instance-attribute","text":"
deliver_subject: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.durable_name","title":"durable_name class-attribute instance-attribute","text":"
durable_name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.filter_subject","title":"filter_subject class-attribute instance-attribute","text":"
filter_subject: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.flow_control","title":"flow_control class-attribute instance-attribute","text":"
flow_control: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.headers_only","title":"headers_only class-attribute instance-attribute","text":"
headers_only: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.idle_heartbeat","title":"idle_heartbeat class-attribute instance-attribute","text":"
idle_heartbeat: Optional[float] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.inactive_threshold","title":"inactive_threshold class-attribute instance-attribute","text":"
inactive_threshold: Optional[float] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.max_ack_pending","title":"max_ack_pending class-attribute instance-attribute","text":"
max_ack_pending: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.max_deliver","title":"max_deliver class-attribute instance-attribute","text":"
max_deliver: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.max_waiting","title":"max_waiting class-attribute instance-attribute","text":"
max_waiting: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.mem_storage","title":"mem_storage class-attribute instance-attribute","text":"
mem_storage: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.num_replicas","title":"num_replicas class-attribute instance-attribute","text":"
num_replicas: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.opt_start_seq","title":"opt_start_seq class-attribute instance-attribute","text":"
opt_start_seq: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.opt_start_time","title":"opt_start_time class-attribute instance-attribute","text":"
opt_start_time: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.rate_limit_bps","title":"rate_limit_bps class-attribute instance-attribute","text":"
rate_limit_bps: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.replay_policy","title":"replay_policy class-attribute instance-attribute","text":"
replay_policy: Optional[ReplayPolicy] = ReplayPolicy.INSTANT\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.sample_freq","title":"sample_freq class-attribute instance-attribute","text":"
sample_freq: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n
Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    result = super().as_dict()\n    result['ack_wait'] = self._to_nanoseconds(self.ack_wait)\n    result['idle_heartbeat'] = self._to_nanoseconds(self.idle_heartbeat)\n    result['inactive_threshold'] = self._to_nanoseconds(\n        self.inactive_threshold\n    )\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any])\n
Source code in nats/js/api.py
@classmethod\ndef from_response(cls, resp: Dict[str, Any]):\n    cls._convert_nanoseconds(resp, 'ack_wait')\n    cls._convert_nanoseconds(resp, 'idle_heartbeat')\n    cls._convert_nanoseconds(resp, 'inactive_threshold')\n    return super().from_response(resp)\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/","title":"DeliverPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy","title":"nats.js.api.DeliverPolicy","text":"

Bases: str, Enum

When a consumer is first created, it can specify where in the stream it wants to start receiving messages.

This is the DeliverPolicy, and this enumeration defines allowed values.

References ","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.ALL","title":"ALL class-attribute instance-attribute","text":"
ALL = 'all'\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.BY_START_SEQUENCE","title":"BY_START_SEQUENCE class-attribute instance-attribute","text":"
BY_START_SEQUENCE = 'by_start_sequence'\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.BY_START_TIME","title":"BY_START_TIME class-attribute instance-attribute","text":"
BY_START_TIME = 'by_start_time'\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.LAST","title":"LAST class-attribute instance-attribute","text":"
LAST = 'last'\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.LAST_PER_SUBJECT","title":"LAST_PER_SUBJECT class-attribute instance-attribute","text":"
LAST_PER_SUBJECT = 'last_per_subject'\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.NEW","title":"NEW class-attribute instance-attribute","text":"
NEW = 'new'\n
","boost":0.5},{"location":"api/faststream/nats/DiscardPolicy/","title":"DiscardPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/DiscardPolicy/#nats.js.api.DiscardPolicy","title":"nats.js.api.DiscardPolicy","text":"

Bases: str, Enum

Discard policy when a stream reaches its limits

","boost":0.5},{"location":"api/faststream/nats/DiscardPolicy/#nats.js.api.DiscardPolicy.NEW","title":"NEW class-attribute instance-attribute","text":"
NEW = 'new'\n
","boost":0.5},{"location":"api/faststream/nats/DiscardPolicy/#nats.js.api.DiscardPolicy.OLD","title":"OLD class-attribute instance-attribute","text":"
OLD = 'old'\n
","boost":0.5},{"location":"api/faststream/nats/ExternalStream/","title":"ExternalStream","text":"","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream","title":"nats.js.api.ExternalStream dataclass","text":"

Bases: Base

","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream.api","title":"api instance-attribute","text":"
api: str\n
","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream.deliver","title":"deliver class-attribute instance-attribute","text":"
deliver: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/JStream/","title":"JStream","text":"","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream","title":"faststream.nats.JStream","text":"
JStream(\n    name: str,\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any\n)\n

Bases: NameRequired

Source code in faststream/nats/js_stream.py
def __init__(\n    self,\n    name: str,\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any,\n) -> None:\n    super().__init__(\n        name=name,\n        declare=declare,\n        subjects=[],\n        config=StreamConfig(\n            *args,\n            name=name,\n            **kwargs,  # type: ignore[misc]\n        ),\n    )\n
","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream.config","title":"config instance-attribute","text":"
config: StreamConfig\n
","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream.declare","title":"declare class-attribute instance-attribute","text":"
declare: bool = Field(default=True)\n
","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream.subjects","title":"subjects class-attribute instance-attribute","text":"
subjects: List[str] = Field(default_factory=list)\n
","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/","title":"NatsBroker","text":"","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker","title":"faststream.nats.NatsBroker","text":"
NatsBroker(\n    servers: Union[str, Sequence[str]] = (\n        \"nats://localhost:4222\"\n    ),\n    *,\n    security: Optional[BaseSecurity] = None,\n    protocol: str = \"nats\",\n    protocol_version: Optional[str] = \"custom\",\n    **kwargs: Any\n)\n

Bases: NatsLoggingMixin, BrokerAsyncUsecase[Msg, Client]

Source code in faststream/nats/broker.py
def __init__(\n    self,\n    servers: Union[str, Sequence[str]] = (\"nats://localhost:4222\",),  # noqa: B006\n    *,\n    security: Optional[BaseSecurity] = None,\n    protocol: str = \"nats\",\n    protocol_version: Optional[str] = \"custom\",\n    **kwargs: Any,\n) -> None:\n    kwargs.update(parse_security(security))\n\n    if kwargs.get(\"tls\"):  # pragma: no cover\n        warnings.warn(\n            (\n                \"\\nNATS `tls` option was deprecated and will be removed in 0.4.0\"\n                \"\\nPlease, use `security` with `BaseSecurity` or `SASLPlaintext` instead\"\n            ),\n            DeprecationWarning,\n            stacklevel=2,\n        )\n\n    super().__init__(\n        url=([servers] if isinstance(servers, str) else list(servers)),\n        protocol=protocol,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n    )\n\n    self.__is_connected = False\n    self._producer = None\n\n    # JS options\n    self.stream = None\n    self._js_producer = None\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[Subject, Handler]\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.stream","title":"stream instance-attribute","text":"
stream: Optional[JetStreamContext] = None\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.url","title":"url instance-attribute","text":"
url: List[str]\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.connect","title":"connect async","text":"
connect(*args: Any, **kwargs: Any) -> Client\n
Source code in faststream/nats/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Client:\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        self.__set_publisher_producer(p)\n    return connection\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, stream: Optional[str] = None, **kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    stream: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[DecodedMessage]:\n    if stream is None:\n        assert self._producer, NOT_CONNECTED_YET  # nosec B101\n        return await self._producer.publish(*args, **kwargs)\n    else:\n        assert self._js_producer, NOT_CONNECTED_YET  # nosec B101\n        return await self._js_producer.publish(\n            *args,\n            stream=stream,\n            **kwargs,  # type: ignore[misc]\n        )\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.publisher","title":"publisher","text":"
publisher(\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    stream: Union[str, JStream, None] = None,\n    timeout: Optional[float] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/nats/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    # Core\n    reply_to: str = \"\",\n    # JS\n    stream: Union[str, JStream, None] = None,\n    timeout: Optional[float] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    if (stream := stream_builder.stream(stream)) is not None:\n        stream.subjects.append(subject)\n\n    publisher = self._publishers.get(\n        subject,\n        Publisher(\n            subject=subject,\n            headers=headers,\n            # Core\n            reply_to=reply_to,\n            # JS\n            timeout=timeout,\n            stream=stream,\n            # AsyncAPI\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(subject, publisher)\n    self.__set_publisher_producer(publisher)\n    return publisher\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.start","title":"start async","text":"
start() -> None\n
Source code in faststream/nats/broker.py
async def start(self) -> None:\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n    assert (\n        self._connection and self.stream\n    ), \"Broker should be started already\"  # nosec B101\n\n    for handler in self.handlers.values():\n        stream = handler.stream\n\n        if (is_js := stream is not None) and stream.declare:\n            try:  # pragma: no branch\n                await self.stream.add_stream(\n                    config=stream.config,\n                    subjects=stream.subjects,\n                )\n\n            except nats.js.errors.BadRequestError as e:\n                old_config = (await self.stream.stream_info(stream.name)).config\n\n                c = self._get_log_context(None, \"\")\n                if (\n                    e.description\n                    == \"stream name already in use with a different configuration\"\n                ):\n                    self._log(str(e), logging.WARNING, c)\n                    await self.stream.update_stream(\n                        config=stream.config,\n                        subjects=tuple(\n                            set(old_config.subjects or ()).union(stream.subjects)\n                        ),\n                    )\n\n                else:  # pragma: no cover\n                    self._log(str(e), logging.ERROR, c, exc_info=e)\n\n            finally:\n                # prevent from double declaration\n                stream.declare = False\n\n        c = self._get_log_context(\n            None,\n            subject=handler.subject,\n            queue=handler.queue,\n            stream=stream.name if stream else \"\",\n        )\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self.stream if is_js else self._connection)\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/nats/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    # Core arguments\n    max_msgs: int = 0,\n    # JS arguments\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    # pull arguments\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    # custom\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[Sequence[Callable[[Msg], BaseMiddleware]]] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],\n]:\n    stream = stream_builder.stream(stream)\n\n    if pull_sub is not None and stream is None:\n        raise ValueError(\"Pull subscriber can be used only with a stream\")\n\n    self._setup_log_context(\n        queue=queue,\n        subject=subject,\n        stream=stream.name if stream else None,\n    )\n    super().subscriber()\n\n    extra_options: AnyDict = {\n        \"pending_msgs_limit\": pending_msgs_limit\n        or (\n            DEFAULT_JS_SUB_PENDING_MSGS_LIMIT\n            if stream\n            else DEFAULT_SUB_PENDING_MSGS_LIMIT\n        ),\n        \"pending_bytes_limit\": pending_bytes_limit\n        or (\n            DEFAULT_JS_SUB_PENDING_BYTES_LIMIT\n            if stream\n            else DEFAULT_SUB_PENDING_BYTES_LIMIT\n        ),\n    }\n\n    if stream:\n        extra_options.update(\n            {\n                \"durable\": durable,\n                \"stream\": stream.name,\n                \"config\": config,\n            }\n        )\n\n        if pull_sub is not None:\n            extra_options.update({\"inbox_prefix\": inbox_prefix})\n\n        else:\n            extra_options.update(\n                {\n                    \"ordered_consumer\": ordered_consumer,\n                    \"idle_heartbeat\": idle_heartbeat,\n                    \"flow_control\": flow_control,\n                    \"deliver_policy\": deliver_policy,\n                    \"headers_only\": headers_only,\n                    \"manual_ack\": not ack_first,\n                }\n            )\n\n    else:\n        extra_options.update(\n            {\n                \"max_msgs\": max_msgs,\n            }\n        )\n\n    key = Handler.get_routing_hash(subject)\n    handler = self.handlers[key] = self.handlers.get(\n        key,\n        Handler(\n            subject=subject,\n            queue=queue,\n            stream=stream,\n            pull_sub=pull_sub,\n            extra_options=extra_options,\n            title=title,\n            description=description,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n            log_context_builder=partial(\n                self._get_log_context,\n                stream=stream.name if stream else \"\",\n                subject=subject,\n                queue=queue,\n            ),\n        ),\n    )\n\n    if stream:\n        stream.subjects.append(handler.subject)\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn,]:\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/nats/NatsRoute/","title":"NatsRoute","text":"","boost":0.5},{"location":"api/faststream/nats/NatsRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/nats/NatsRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/nats/NatsRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/nats/NatsRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/","title":"NatsRouter","text":"","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter","title":"faststream.nats.NatsRouter","text":"
NatsRouter(\n    prefix: str = \"\",\n    handlers: Sequence[NatsRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: NatsRouter

Source code in faststream/nats/router.py
    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.publisher","title":"publisher","text":"
publisher(\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/nats/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            subject=subject,\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    retry: bool = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
","boost":0.5},{"location":"api/faststream/nats/Placement/","title":"Placement","text":"","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement","title":"nats.js.api.Placement dataclass","text":"

Bases: Base

Placement directives to consider when placing replicas of this stream

","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement.cluster","title":"cluster class-attribute instance-attribute","text":"
cluster: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/PullSub/","title":"PullSub","text":"","boost":0.5},{"location":"api/faststream/nats/PullSub/#faststream.nats.PullSub","title":"faststream.nats.PullSub","text":"
PullSub(\n    batch_size: int = 1,\n    timeout: Optional[float] = 5.0,\n    batch: bool = False,\n)\n

Bases: BaseModel

Source code in faststream/nats/pull_sub.py
def __init__(\n    self,\n    batch_size: int = 1,\n    timeout: Optional[float] = 5.0,\n    batch: bool = False,\n) -> None:\n    super().__init__(\n        batch_size=batch_size,\n        timeout=timeout,\n        batch=batch,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/PullSub/#faststream.nats.PullSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = Field(default=False)\n
","boost":0.5},{"location":"api/faststream/nats/PullSub/#faststream.nats.PullSub.batch_size","title":"batch_size class-attribute instance-attribute","text":"
batch_size: int = Field(default=1)\n
","boost":0.5},{"location":"api/faststream/nats/PullSub/#faststream.nats.PullSub.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: Optional[float] = Field(default=5.0)\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/","title":"RePublish","text":"","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish","title":"nats.js.api.RePublish dataclass","text":"

Bases: Base

RePublish is for republishing messages once committed to a stream. The original subject cis remapped from the subject pattern to the destination pattern.

","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.dest","title":"dest class-attribute instance-attribute","text":"
dest: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.headers_only","title":"headers_only class-attribute instance-attribute","text":"
headers_only: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.src","title":"src class-attribute instance-attribute","text":"
src: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/ReplayPolicy/","title":"ReplayPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/ReplayPolicy/#nats.js.api.ReplayPolicy","title":"nats.js.api.ReplayPolicy","text":"

Bases: str, Enum

The replay policy applies when the DeliverPolicy is one of

since those deliver policies begin reading the stream at a position other than the end.

References ","boost":0.5},{"location":"api/faststream/nats/ReplayPolicy/#nats.js.api.ReplayPolicy.INSTANT","title":"INSTANT class-attribute instance-attribute","text":"
INSTANT = 'instant'\n
","boost":0.5},{"location":"api/faststream/nats/ReplayPolicy/#nats.js.api.ReplayPolicy.ORIGINAL","title":"ORIGINAL class-attribute instance-attribute","text":"
ORIGINAL = 'original'\n
","boost":0.5},{"location":"api/faststream/nats/RetentionPolicy/","title":"RetentionPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/RetentionPolicy/#nats.js.api.RetentionPolicy","title":"nats.js.api.RetentionPolicy","text":"

Bases: str, Enum

How message retention is considered

","boost":0.5},{"location":"api/faststream/nats/RetentionPolicy/#nats.js.api.RetentionPolicy.INTEREST","title":"INTEREST class-attribute instance-attribute","text":"
INTEREST = 'interest'\n
","boost":0.5},{"location":"api/faststream/nats/RetentionPolicy/#nats.js.api.RetentionPolicy.LIMITS","title":"LIMITS class-attribute instance-attribute","text":"
LIMITS = 'limits'\n
","boost":0.5},{"location":"api/faststream/nats/RetentionPolicy/#nats.js.api.RetentionPolicy.WORK_QUEUE","title":"WORK_QUEUE class-attribute instance-attribute","text":"
WORK_QUEUE = 'workqueue'\n
","boost":0.5},{"location":"api/faststream/nats/StorageType/","title":"StorageType","text":"","boost":0.5},{"location":"api/faststream/nats/StorageType/#nats.js.api.StorageType","title":"nats.js.api.StorageType","text":"

Bases: str, Enum

The type of storage backend

","boost":0.5},{"location":"api/faststream/nats/StorageType/#nats.js.api.StorageType.FILE","title":"FILE class-attribute instance-attribute","text":"
FILE = 'file'\n
","boost":0.5},{"location":"api/faststream/nats/StorageType/#nats.js.api.StorageType.MEMORY","title":"MEMORY class-attribute instance-attribute","text":"
MEMORY = 'memory'\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/","title":"StreamConfig","text":"","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig","title":"nats.js.api.StreamConfig dataclass","text":"

Bases: Base

StreamConfig represents the configuration of a stream.

","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.allow_direct","title":"allow_direct class-attribute instance-attribute","text":"
allow_direct: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.allow_rollup_hdrs","title":"allow_rollup_hdrs class-attribute instance-attribute","text":"
allow_rollup_hdrs: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.deny_delete","title":"deny_delete class-attribute instance-attribute","text":"
deny_delete: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.deny_purge","title":"deny_purge class-attribute instance-attribute","text":"
deny_purge: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.discard","title":"discard class-attribute instance-attribute","text":"
discard: Optional[DiscardPolicy] = DiscardPolicy.OLD\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.duplicate_window","title":"duplicate_window class-attribute instance-attribute","text":"
duplicate_window: float = 0\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_age","title":"max_age class-attribute instance-attribute","text":"
max_age: Optional[float] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_bytes","title":"max_bytes class-attribute instance-attribute","text":"
max_bytes: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_consumers","title":"max_consumers class-attribute instance-attribute","text":"
max_consumers: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_msg_size","title":"max_msg_size class-attribute instance-attribute","text":"
max_msg_size: Optional[int] = -1\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_msgs","title":"max_msgs class-attribute instance-attribute","text":"
max_msgs: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_msgs_per_subject","title":"max_msgs_per_subject class-attribute instance-attribute","text":"
max_msgs_per_subject: int = -1\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.mirror","title":"mirror class-attribute instance-attribute","text":"
mirror: Optional[StreamSource] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.mirror_direct","title":"mirror_direct class-attribute instance-attribute","text":"
mirror_direct: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.no_ack","title":"no_ack class-attribute instance-attribute","text":"
no_ack: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.num_replicas","title":"num_replicas class-attribute instance-attribute","text":"
num_replicas: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.placement","title":"placement class-attribute instance-attribute","text":"
placement: Optional[Placement] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.republish","title":"republish class-attribute instance-attribute","text":"
republish: Optional[RePublish] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.retention","title":"retention class-attribute instance-attribute","text":"
retention: Optional[RetentionPolicy] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.sealed","title":"sealed class-attribute instance-attribute","text":"
sealed: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.sources","title":"sources class-attribute instance-attribute","text":"
sources: Optional[List[StreamSource]] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.storage","title":"storage class-attribute instance-attribute","text":"
storage: Optional[StorageType] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.subjects","title":"subjects class-attribute instance-attribute","text":"
subjects: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.template_owner","title":"template_owner class-attribute instance-attribute","text":"
template_owner: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n
Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    result = super().as_dict()\n    result['duplicate_window'] = self._to_nanoseconds(\n        self.duplicate_window\n    )\n    result['max_age'] = self._to_nanoseconds(self.max_age)\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any])\n
Source code in nats/js/api.py
@classmethod\ndef from_response(cls, resp: Dict[str, Any]):\n    cls._convert_nanoseconds(resp, 'max_age')\n    cls._convert_nanoseconds(resp, 'duplicate_window')\n    cls._convert(resp, 'placement', Placement)\n    cls._convert(resp, 'mirror', StreamSource)\n    cls._convert(resp, 'sources', StreamSource)\n    cls._convert(resp, 'republish', RePublish)\n    return super().from_response(resp)\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/","title":"StreamSource","text":"","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource","title":"nats.js.api.StreamSource dataclass","text":"

Bases: Base

","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.external","title":"external class-attribute instance-attribute","text":"
external: Optional[ExternalStream] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.filter_subject","title":"filter_subject class-attribute instance-attribute","text":"
filter_subject: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.opt_start_seq","title":"opt_start_seq class-attribute instance-attribute","text":"
opt_start_seq: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any])\n
Source code in nats/js/api.py
@classmethod\ndef from_response(cls, resp: Dict[str, Any]):\n    cls._convert(resp, 'external', ExternalStream)\n    return super().from_response(resp)\n
","boost":0.5},{"location":"api/faststream/nats/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/nats/TestApp/#faststream.broker.test.TestApp","title":"faststream.broker.test.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/nats/TestApp/#faststream.broker.test.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/","title":"TestNatsBroker","text":"","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker","title":"faststream.nats.TestNatsBroker","text":"
TestNatsBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[NatsBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/nats/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: NatsBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(publisher.subject, _raw=True)\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(broker: NatsBroker, publisher: Any) -> None\n
Source code in faststream/nats/test.py
@staticmethod\ndef patch_publisher(broker: NatsBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> None\n
Source code in faststream/nats/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> None:\n    broker.handlers.pop(Handler.get_routing_hash(publisher.subject), None)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/","title":"Handler","text":"","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler","title":"faststream.nats.asyncapi.Handler","text":"
Handler(\n    subject: str,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    queue: str = \"\",\n    stream: Optional[JStream] = None,\n    pull_sub: Optional[PullSub] = None,\n    extra_options: Optional[AnyDict] = None,\n    graceful_timeout: Optional[float] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n)\n

Bases: LogicNatsHandler

Source code in faststream/nats/handler.py
def __init__(\n    self,\n    subject: str,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    queue: str = \"\",\n    stream: Optional[JStream] = None,\n    pull_sub: Optional[PullSub] = None,\n    extra_options: Optional[AnyDict] = None,\n    graceful_timeout: Optional[float] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    reg, path = compile_path(subject, replace_symbol=\"*\")\n    self.subject = path\n    self.path_regex = reg\n\n    self.queue = queue\n\n    self.stream = stream\n    self.pull_sub = pull_sub\n    self.extra_options = extra_options or {}\n\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        include_in_schema=include_in_schema,\n        title=title,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.task = None\n    self.subscription = None\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.extra_options","title":"extra_options instance-attribute","text":"
extra_options = extra_options or {}\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.path_regex","title":"path_regex instance-attribute","text":"
path_regex = reg\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.pull_sub","title":"pull_sub instance-attribute","text":"
pull_sub = pull_sub\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.queue","title":"queue instance-attribute","text":"
queue = queue\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.stream","title":"stream instance-attribute","text":"
stream = stream\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.subject","title":"subject instance-attribute","text":"
subject = path\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.subscription","title":"subscription instance-attribute","text":"
subscription: Union[\n    None,\n    Subscription,\n    JetStreamContext.PushSubscription,\n    JetStreamContext.PullSubscription,\n] = None\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.task","title":"task class-attribute instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[Msg, NatsMessage]],\n    decoder: Optional[CustomDecoder[NatsMessage]],\n    filter: Filter[NatsMessage],\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ]\n) -> None\n
Source code in faststream/nats/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[Msg, NatsMessage]],\n    decoder: Optional[CustomDecoder[NatsMessage]],\n    filter: Filter[NatsMessage],\n    middlewares: Optional[Sequence[Callable[[Msg], BaseMiddleware]]],\n) -> None:\n    parser_ = Parser if self.stream is None else JsParser\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, parser_.parse_message),\n        decoder=resolve_custom_func(decoder, parser_.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/nats/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.subscription is not None:\n        await self.subscription.unsubscribe()\n        self.subscription = None\n\n    if self.task is not None:\n        self.task.cancel()\n        self.task = None\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(subject: str) -> str\n
Source code in faststream/nats/handler.py
@staticmethod\ndef get_routing_hash(subject: str) -> str:\n    return subject\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/nats/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n    handler_name = self._title or f\"{self.subject}:{self.call_name}\"\n    return {\n        handler_name: Channel(\n            description=self.description,\n            subscribe=Operation(\n                message=Message(\n                    title=f\"{handler_name}:Message\",\n                    payload=resolve_payloads(payloads),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                nats=nats.ChannelBinding(\n                    subject=self.subject,\n                    queue=self.queue or None,\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.start","title":"start async","text":"
start(connection: Union[Client, JetStreamContext]) -> None\n
Source code in faststream/nats/handler.py
@override\nasync def start(self, connection: Union[Client, JetStreamContext]) -> None:  # type: ignore[override]\n    if self.pull_sub is not None:\n        connection = cast(JetStreamContext, connection)\n\n        if self.stream is None:\n            raise ValueError(\"Pull subscriber can be used only with a stream\")\n\n        self.subscription = await connection.pull_subscribe(\n            subject=self.subject,\n            **self.extra_options,\n        )\n        self.task = asyncio.create_task(self._consume())\n\n    else:\n        self.subscription = await connection.subscribe(\n            subject=self.subject,\n            queue=self.queue,\n            cb=self.consume,  # type: ignore[arg-type]\n            **self.extra_options,\n        )\n\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/","title":"Publisher","text":"","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher","title":"faststream.nats.asyncapi.Publisher","text":"

Bases: LogicPublisher

","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.name","title":"name property","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.stream","title":"stream class-attribute instance-attribute","text":"
stream: Optional[JStream] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.subject","title":"subject class-attribute instance-attribute","text":"
subject: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: Optional[float] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.publish","title":"publish async","text":"
publish(\n    message: SendableMessage = \"\",\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[Dict[str, str]] = None,\n    **producer_kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage = \"\",\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[Dict[str, str]] = None,\n    **producer_kwargs: Any,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    assert self.subject, \"You have to specify outgoing subject\"  # nosec B101\n\n    extra: AnyDict = {\n        \"reply_to\": reply_to or self.reply_to,\n    }\n    if self.stream is not None:\n        extra.update(\n            {\n                \"stream\": self.stream.name,\n                \"timeout\": self.timeout,\n            }\n        )\n\n    return await self._producer.publish(\n        message=message,\n        subject=self.subject,\n        headers=headers or self.headers,\n        correlation_id=correlation_id,\n        **extra,\n        **producer_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/nats/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    return {\n        self.name: Channel(\n            description=self.description,\n            publish=Operation(\n                message=Message(\n                    title=f\"{self.name}:Message\",\n                    payload=resolve_payloads(payloads, \"Publisher\"),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                nats=nats.ChannelBinding(\n                    subject=self.subject,\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/","title":"NatsBroker","text":"","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker","title":"faststream.nats.broker.NatsBroker","text":"
NatsBroker(\n    servers: Union[str, Sequence[str]] = (\n        \"nats://localhost:4222\"\n    ),\n    *,\n    security: Optional[BaseSecurity] = None,\n    protocol: str = \"nats\",\n    protocol_version: Optional[str] = \"custom\",\n    **kwargs: Any\n)\n

Bases: NatsLoggingMixin, BrokerAsyncUsecase[Msg, Client]

Source code in faststream/nats/broker.py
def __init__(\n    self,\n    servers: Union[str, Sequence[str]] = (\"nats://localhost:4222\",),  # noqa: B006\n    *,\n    security: Optional[BaseSecurity] = None,\n    protocol: str = \"nats\",\n    protocol_version: Optional[str] = \"custom\",\n    **kwargs: Any,\n) -> None:\n    kwargs.update(parse_security(security))\n\n    if kwargs.get(\"tls\"):  # pragma: no cover\n        warnings.warn(\n            (\n                \"\\nNATS `tls` option was deprecated and will be removed in 0.4.0\"\n                \"\\nPlease, use `security` with `BaseSecurity` or `SASLPlaintext` instead\"\n            ),\n            DeprecationWarning,\n            stacklevel=2,\n        )\n\n    super().__init__(\n        url=([servers] if isinstance(servers, str) else list(servers)),\n        protocol=protocol,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n    )\n\n    self.__is_connected = False\n    self._producer = None\n\n    # JS options\n    self.stream = None\n    self._js_producer = None\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[Subject, Handler]\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.stream","title":"stream instance-attribute","text":"
stream: Optional[JetStreamContext] = None\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.url","title":"url instance-attribute","text":"
url: List[str]\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.connect","title":"connect async","text":"
connect(*args: Any, **kwargs: Any) -> Client\n
Source code in faststream/nats/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Client:\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        self.__set_publisher_producer(p)\n    return connection\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, stream: Optional[str] = None, **kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    stream: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[DecodedMessage]:\n    if stream is None:\n        assert self._producer, NOT_CONNECTED_YET  # nosec B101\n        return await self._producer.publish(*args, **kwargs)\n    else:\n        assert self._js_producer, NOT_CONNECTED_YET  # nosec B101\n        return await self._js_producer.publish(\n            *args,\n            stream=stream,\n            **kwargs,  # type: ignore[misc]\n        )\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.publisher","title":"publisher","text":"
publisher(\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    stream: Union[str, JStream, None] = None,\n    timeout: Optional[float] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/nats/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    # Core\n    reply_to: str = \"\",\n    # JS\n    stream: Union[str, JStream, None] = None,\n    timeout: Optional[float] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    if (stream := stream_builder.stream(stream)) is not None:\n        stream.subjects.append(subject)\n\n    publisher = self._publishers.get(\n        subject,\n        Publisher(\n            subject=subject,\n            headers=headers,\n            # Core\n            reply_to=reply_to,\n            # JS\n            timeout=timeout,\n            stream=stream,\n            # AsyncAPI\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(subject, publisher)\n    self.__set_publisher_producer(publisher)\n    return publisher\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.start","title":"start async","text":"
start() -> None\n
Source code in faststream/nats/broker.py
async def start(self) -> None:\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n    assert (\n        self._connection and self.stream\n    ), \"Broker should be started already\"  # nosec B101\n\n    for handler in self.handlers.values():\n        stream = handler.stream\n\n        if (is_js := stream is not None) and stream.declare:\n            try:  # pragma: no branch\n                await self.stream.add_stream(\n                    config=stream.config,\n                    subjects=stream.subjects,\n                )\n\n            except nats.js.errors.BadRequestError as e:\n                old_config = (await self.stream.stream_info(stream.name)).config\n\n                c = self._get_log_context(None, \"\")\n                if (\n                    e.description\n                    == \"stream name already in use with a different configuration\"\n                ):\n                    self._log(str(e), logging.WARNING, c)\n                    await self.stream.update_stream(\n                        config=stream.config,\n                        subjects=tuple(\n                            set(old_config.subjects or ()).union(stream.subjects)\n                        ),\n                    )\n\n                else:  # pragma: no cover\n                    self._log(str(e), logging.ERROR, c, exc_info=e)\n\n            finally:\n                # prevent from double declaration\n                stream.declare = False\n\n        c = self._get_log_context(\n            None,\n            subject=handler.subject,\n            queue=handler.queue,\n            stream=stream.name if stream else \"\",\n        )\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self.stream if is_js else self._connection)\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/nats/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    # Core arguments\n    max_msgs: int = 0,\n    # JS arguments\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    # pull arguments\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    # custom\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[Sequence[Callable[[Msg], BaseMiddleware]]] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],\n]:\n    stream = stream_builder.stream(stream)\n\n    if pull_sub is not None and stream is None:\n        raise ValueError(\"Pull subscriber can be used only with a stream\")\n\n    self._setup_log_context(\n        queue=queue,\n        subject=subject,\n        stream=stream.name if stream else None,\n    )\n    super().subscriber()\n\n    extra_options: AnyDict = {\n        \"pending_msgs_limit\": pending_msgs_limit\n        or (\n            DEFAULT_JS_SUB_PENDING_MSGS_LIMIT\n            if stream\n            else DEFAULT_SUB_PENDING_MSGS_LIMIT\n        ),\n        \"pending_bytes_limit\": pending_bytes_limit\n        or (\n            DEFAULT_JS_SUB_PENDING_BYTES_LIMIT\n            if stream\n            else DEFAULT_SUB_PENDING_BYTES_LIMIT\n        ),\n    }\n\n    if stream:\n        extra_options.update(\n            {\n                \"durable\": durable,\n                \"stream\": stream.name,\n                \"config\": config,\n            }\n        )\n\n        if pull_sub is not None:\n            extra_options.update({\"inbox_prefix\": inbox_prefix})\n\n        else:\n            extra_options.update(\n                {\n                    \"ordered_consumer\": ordered_consumer,\n                    \"idle_heartbeat\": idle_heartbeat,\n                    \"flow_control\": flow_control,\n                    \"deliver_policy\": deliver_policy,\n                    \"headers_only\": headers_only,\n                    \"manual_ack\": not ack_first,\n                }\n            )\n\n    else:\n        extra_options.update(\n            {\n                \"max_msgs\": max_msgs,\n            }\n        )\n\n    key = Handler.get_routing_hash(subject)\n    handler = self.handlers[key] = self.handlers.get(\n        key,\n        Handler(\n            subject=subject,\n            queue=queue,\n            stream=stream,\n            pull_sub=pull_sub,\n            extra_options=extra_options,\n            title=title,\n            description=description,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n            log_context_builder=partial(\n                self._get_log_context,\n                stream=stream.name if stream else \"\",\n                subject=subject,\n                queue=queue,\n            ),\n        ),\n    )\n\n    if stream:\n        stream.subjects.append(handler.subject)\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn,]:\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/nats/fastapi/Context/#faststream.broker.fastapi.context.Context","title":"faststream.broker.fastapi.context.Context","text":"
Context(name: str) -> Any\n
Source code in faststream/broker/fastapi/context.py
def Context(name: str) -> Any:\n    return params.Depends(\n        lambda: context.resolve(name),\n        use_cache=True,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/","title":"NatsRouter","text":"","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter","title":"faststream.nats.fastapi.NatsRouter","text":"
NatsRouter(\n    servers: Union[str, Sequence[str]] = (\n        \"nats://localhost:4222\"\n    ),\n    *,\n    error_cb: Optional[ErrorCallback] = None,\n    disconnected_cb: Optional[Callback] = None,\n    closed_cb: Optional[Callback] = None,\n    discovered_server_cb: Optional[Callback] = None,\n    reconnected_cb: Optional[Callback] = None,\n    name: Optional[str] = None,\n    pedantic: bool = False,\n    verbose: bool = False,\n    allow_reconnect: bool = True,\n    connect_timeout: int = DEFAULT_CONNECT_TIMEOUT,\n    reconnect_time_wait: int = DEFAULT_RECONNECT_TIME_WAIT,\n    max_reconnect_attempts: int = DEFAULT_MAX_RECONNECT_ATTEMPTS,\n    ping_interval: int = DEFAULT_PING_INTERVAL,\n    max_outstanding_pings: int = DEFAULT_MAX_OUTSTANDING_PINGS,\n    dont_randomize: bool = False,\n    flusher_queue_size: int = DEFAULT_MAX_FLUSHER_QUEUE_SIZE,\n    no_echo: bool = False,\n    tls: Optional[ssl.SSLContext] = None,\n    tls_hostname: Optional[str] = None,\n    user: Optional[str] = None,\n    password: Optional[str] = None,\n    token: Optional[str] = None,\n    drain_timeout: int = DEFAULT_DRAIN_TIMEOUT,\n    signature_cb: Optional[SignatureCallback] = None,\n    user_jwt_cb: Optional[JWTCallback] = None,\n    user_credentials: Optional[Credentials] = None,\n    nkeys_seed: Optional[str] = None,\n    inbox_prefix: Union[str, bytes] = DEFAULT_INBOX_PREFIX,\n    pending_size: int = DEFAULT_PENDING_SIZE,\n    flush_timeout: Optional[float] = None,\n    graceful_timeout: Optional[float] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    asyncapi_url: Union[str, List[str], None] = None,\n    protocol: str = \"nats\",\n    protocol_version: Optional[str] = \"0.9.1\",\n    description: Optional[str] = None,\n    asyncapi_tags: Optional[Sequence[asyncapi.Tag]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    setup_state: bool = True,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n)\n

Bases: StreamRouter[Msg]

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.broker","title":"broker instance-attribute","text":"
broker: NatsBroker\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.broker_class","title":"broker_class class-attribute instance-attribute","text":"
broker_class = NB\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    subject: str,\n    *,\n    endpoint: Callable[..., T_HandlerReturn],\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    retry: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    **__service_kwargs: Any\n) -> Callable[[Msg, bool], Awaitable[T_HandlerReturn]]\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.publisher","title":"publisher","text":"
publisher(\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    stream: Union[str, JStream, None] = None,\n    timeout: Optional[float] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    retry: bool = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/","title":"LogicNatsHandler","text":"","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler","title":"faststream.nats.handler.LogicNatsHandler","text":"
LogicNatsHandler(\n    subject: str,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    queue: str = \"\",\n    stream: Optional[JStream] = None,\n    pull_sub: Optional[PullSub] = None,\n    extra_options: Optional[AnyDict] = None,\n    graceful_timeout: Optional[float] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n)\n

Bases: AsyncHandler[Msg]

Source code in faststream/nats/handler.py
def __init__(\n    self,\n    subject: str,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    queue: str = \"\",\n    stream: Optional[JStream] = None,\n    pull_sub: Optional[PullSub] = None,\n    extra_options: Optional[AnyDict] = None,\n    graceful_timeout: Optional[float] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    reg, path = compile_path(subject, replace_symbol=\"*\")\n    self.subject = path\n    self.path_regex = reg\n\n    self.queue = queue\n\n    self.stream = stream\n    self.pull_sub = pull_sub\n    self.extra_options = extra_options or {}\n\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        include_in_schema=include_in_schema,\n        title=title,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.task = None\n    self.subscription = None\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.extra_options","title":"extra_options instance-attribute","text":"
extra_options = extra_options or {}\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.path_regex","title":"path_regex instance-attribute","text":"
path_regex = reg\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.pull_sub","title":"pull_sub instance-attribute","text":"
pull_sub = pull_sub\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.queue","title":"queue instance-attribute","text":"
queue = queue\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.stream","title":"stream instance-attribute","text":"
stream = stream\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.subject","title":"subject instance-attribute","text":"
subject = path\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.subscription","title":"subscription instance-attribute","text":"
subscription: Union[\n    None,\n    Subscription,\n    JetStreamContext.PushSubscription,\n    JetStreamContext.PullSubscription,\n] = None\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.task","title":"task class-attribute instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[Msg, NatsMessage]],\n    decoder: Optional[CustomDecoder[NatsMessage]],\n    filter: Filter[NatsMessage],\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ]\n) -> None\n
Source code in faststream/nats/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[Msg, NatsMessage]],\n    decoder: Optional[CustomDecoder[NatsMessage]],\n    filter: Filter[NatsMessage],\n    middlewares: Optional[Sequence[Callable[[Msg], BaseMiddleware]]],\n) -> None:\n    parser_ = Parser if self.stream is None else JsParser\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, parser_.parse_message),\n        decoder=resolve_custom_func(decoder, parser_.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/nats/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.subscription is not None:\n        await self.subscription.unsubscribe()\n        self.subscription = None\n\n    if self.task is not None:\n        self.task.cancel()\n        self.task = None\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(subject: str) -> str\n
Source code in faststream/nats/handler.py
@staticmethod\ndef get_routing_hash(subject: str) -> str:\n    return subject\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.start","title":"start async","text":"
start(connection: Union[Client, JetStreamContext]) -> None\n
Source code in faststream/nats/handler.py
@override\nasync def start(self, connection: Union[Client, JetStreamContext]) -> None:  # type: ignore[override]\n    if self.pull_sub is not None:\n        connection = cast(JetStreamContext, connection)\n\n        if self.stream is None:\n            raise ValueError(\"Pull subscriber can be used only with a stream\")\n\n        self.subscription = await connection.pull_subscribe(\n            subject=self.subject,\n            **self.extra_options,\n        )\n        self.task = asyncio.create_task(self._consume())\n\n    else:\n        self.subscription = await connection.subscribe(\n            subject=self.subject,\n            queue=self.queue,\n            cb=self.consume,  # type: ignore[arg-type]\n            **self.extra_options,\n        )\n\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/nats/helpers/StreamBuilder/","title":"StreamBuilder","text":"","boost":0.5},{"location":"api/faststream/nats/helpers/StreamBuilder/#faststream.nats.helpers.StreamBuilder","title":"faststream.nats.helpers.StreamBuilder","text":"
StreamBuilder()\n
Source code in faststream/nats/helpers.py
def __init__(self) -> None:\n    self.streams = {}\n
","boost":0.5},{"location":"api/faststream/nats/helpers/StreamBuilder/#faststream.nats.helpers.StreamBuilder.streams","title":"streams instance-attribute","text":"
streams: Dict[str, JStream] = {}\n
","boost":0.5},{"location":"api/faststream/nats/helpers/StreamBuilder/#faststream.nats.helpers.StreamBuilder.stream","title":"stream","text":"
stream(\n    name: Union[str, JStream, None],\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any\n) -> Optional[JStream]\n
Source code in faststream/nats/helpers.py
def stream(\n    self,\n    name: Union[str, JStream, None],\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any,\n) -> Optional[JStream]:\n    stream = JStream.validate(name)\n\n    if stream is not None:\n        stream = self.streams[stream.name] = self.streams.get(stream.name, stream)\n\n    return stream\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/DiscardPolicy/","title":"DiscardPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/DiscardPolicy/#nats.js.api.DiscardPolicy","title":"nats.js.api.DiscardPolicy","text":"

Bases: str, Enum

Discard policy when a stream reaches its limits

","boost":0.5},{"location":"api/faststream/nats/js_stream/DiscardPolicy/#nats.js.api.DiscardPolicy.NEW","title":"NEW class-attribute instance-attribute","text":"
NEW = 'new'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/DiscardPolicy/#nats.js.api.DiscardPolicy.OLD","title":"OLD class-attribute instance-attribute","text":"
OLD = 'old'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/","title":"ExternalStream","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream","title":"nats.js.api.ExternalStream dataclass","text":"

Bases: Base

","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream.api","title":"api instance-attribute","text":"
api: str\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream.deliver","title":"deliver class-attribute instance-attribute","text":"
deliver: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/","title":"JStream","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream","title":"faststream.nats.js_stream.JStream","text":"
JStream(\n    name: str,\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any\n)\n

Bases: NameRequired

Source code in faststream/nats/js_stream.py
def __init__(\n    self,\n    name: str,\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any,\n) -> None:\n    super().__init__(\n        name=name,\n        declare=declare,\n        subjects=[],\n        config=StreamConfig(\n            *args,\n            name=name,\n            **kwargs,  # type: ignore[misc]\n        ),\n    )\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream.config","title":"config instance-attribute","text":"
config: StreamConfig\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream.declare","title":"declare class-attribute instance-attribute","text":"
declare: bool = Field(default=True)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream.subjects","title":"subjects class-attribute instance-attribute","text":"
subjects: List[str] = Field(default_factory=list)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/","title":"Placement","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement","title":"nats.js.api.Placement dataclass","text":"

Bases: Base

Placement directives to consider when placing replicas of this stream

","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement.cluster","title":"cluster class-attribute instance-attribute","text":"
cluster: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/","title":"RePublish","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish","title":"nats.js.api.RePublish dataclass","text":"

Bases: Base

RePublish is for republishing messages once committed to a stream. The original subject cis remapped from the subject pattern to the destination pattern.

","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.dest","title":"dest class-attribute instance-attribute","text":"
dest: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.headers_only","title":"headers_only class-attribute instance-attribute","text":"
headers_only: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.src","title":"src class-attribute instance-attribute","text":"
src: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RetentionPolicy/","title":"RetentionPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/RetentionPolicy/#nats.js.api.RetentionPolicy","title":"nats.js.api.RetentionPolicy","text":"

Bases: str, Enum

How message retention is considered

","boost":0.5},{"location":"api/faststream/nats/js_stream/RetentionPolicy/#nats.js.api.RetentionPolicy.INTEREST","title":"INTEREST class-attribute instance-attribute","text":"
INTEREST = 'interest'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RetentionPolicy/#nats.js.api.RetentionPolicy.LIMITS","title":"LIMITS class-attribute instance-attribute","text":"
LIMITS = 'limits'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RetentionPolicy/#nats.js.api.RetentionPolicy.WORK_QUEUE","title":"WORK_QUEUE class-attribute instance-attribute","text":"
WORK_QUEUE = 'workqueue'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StorageType/","title":"StorageType","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/StorageType/#nats.js.api.StorageType","title":"nats.js.api.StorageType","text":"

Bases: str, Enum

The type of storage backend

","boost":0.5},{"location":"api/faststream/nats/js_stream/StorageType/#nats.js.api.StorageType.FILE","title":"FILE class-attribute instance-attribute","text":"
FILE = 'file'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StorageType/#nats.js.api.StorageType.MEMORY","title":"MEMORY class-attribute instance-attribute","text":"
MEMORY = 'memory'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/","title":"StreamSource","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource","title":"nats.js.api.StreamSource dataclass","text":"

Bases: Base

","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.external","title":"external class-attribute instance-attribute","text":"
external: Optional[ExternalStream] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.filter_subject","title":"filter_subject class-attribute instance-attribute","text":"
filter_subject: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.opt_start_seq","title":"opt_start_seq class-attribute instance-attribute","text":"
opt_start_seq: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any])\n
Source code in nats/js/api.py
@classmethod\ndef from_response(cls, resp: Dict[str, Any]):\n    cls._convert(resp, 'external', ExternalStream)\n    return super().from_response(resp)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/","title":"NatsMessage","text":"","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage","title":"faststream.nats.message.NatsMessage dataclass","text":"

Bases: StreamMessage[Msg]

","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.is_js","title":"is_js class-attribute instance-attribute","text":"
is_js: bool = True\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.ack","title":"ack async","text":"
ack(**kwargs: Any) -> None\n
Source code in faststream/nats/message.py
async def ack(self, **kwargs: Any) -> None:\n    await super().ack()\n    if self.is_js:\n        if not isinstance(self.raw_message, list):\n            if not self.raw_message._ackd:\n                await self.raw_message.ack()\n\n        else:\n            for m in filter(\n                lambda m: not m._ackd,\n                self.raw_message,\n            ):\n                await m.ack()\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.in_progress","title":"in_progress async","text":"
in_progress(**kwargs: Any) -> None\n
Source code in faststream/nats/message.py
async def in_progress(self, **kwargs: Any) -> None:\n    if self.is_js:\n        if not isinstance(self.raw_message, list):\n            if not self.raw_message._ackd:\n                await self.raw_message.in_progress()\n\n        else:\n            for m in filter(\n                lambda m: not m._ackd,\n                self.raw_message,\n            ):\n                await m.in_progress()\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.nack","title":"nack async","text":"
nack(**kwargs: Any) -> None\n
Source code in faststream/nats/message.py
async def nack(self, **kwargs: Any) -> None:\n    await super().nack()\n    if self.is_js:\n        if not isinstance(self.raw_message, list):\n            if not self.raw_message._ackd:\n                await self.raw_message.nak(**kwargs)\n\n        else:\n            for m in filter(\n                lambda m: not m._ackd,\n                self.raw_message,\n            ):\n                await m.nak(**kwargs)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.reject","title":"reject async","text":"
reject(**kwargs: Any) -> None\n
Source code in faststream/nats/message.py
async def reject(self, **kwargs: Any) -> None:\n    await super().reject()\n    if self.is_js:\n        if not isinstance(self.raw_message, list):\n            if not self.raw_message._ackd:\n                await self.raw_message.term()\n\n        else:\n            for m in filter(\n                lambda m: not m._ackd,\n                self.raw_message,\n            ):\n                await m.term()\n
","boost":0.5},{"location":"api/faststream/nats/parser/NatsParser/","title":"NatsParser","text":"","boost":0.5},{"location":"api/faststream/nats/parser/NatsParser/#faststream.nats.parser.NatsParser","title":"faststream.nats.parser.NatsParser","text":"
NatsParser(is_js: bool)\n
Source code in faststream/nats/parser.py
def __init__(self, is_js: bool) -> None:\n    self.is_js = is_js\n
","boost":0.5},{"location":"api/faststream/nats/parser/NatsParser/#faststream.nats.parser.NatsParser.is_js","title":"is_js instance-attribute","text":"
is_js = is_js\n
","boost":0.5},{"location":"api/faststream/nats/parser/NatsParser/#faststream.nats.parser.NatsParser.decode_message","title":"decode_message async","text":"
decode_message(\n    msg: Union[StreamMessage[Msg], StreamMessage[List[Msg]]]\n) -> DecodedMessage\n
Source code in faststream/nats/parser.py
async def decode_message(\n    self,\n    msg: Union[\n        StreamMessage[Msg],\n        StreamMessage[List[Msg]],\n    ],\n) -> DecodedMessage:\n    if isinstance(msg.raw_message, list):\n        data = []\n\n        path: Optional[AnyDict] = None\n        for m in msg.raw_message:\n            msg = await self.parse_message(m, path=path)\n            path = msg.path\n\n            data.append(decode_message(msg))\n\n        return data\n\n    else:\n        return decode_message(msg)\n
","boost":0.5},{"location":"api/faststream/nats/parser/NatsParser/#faststream.nats.parser.NatsParser.parse_message","title":"parse_message async","text":"
parse_message(\n    message: Union[Msg, List[Msg]],\n    *,\n    path: Optional[AnyDict] = None\n) -> Union[StreamMessage[Msg], StreamMessage[List[Msg]]]\n
Source code in faststream/nats/parser.py
async def parse_message(\n    self, message: Union[Msg, List[Msg]], *, path: Optional[AnyDict] = None\n) -> Union[StreamMessage[Msg], StreamMessage[List[Msg]],]:\n    if isinstance(message, list):\n        return NatsMessage(\n            is_js=self.is_js,\n            raw_message=message,  # type: ignore[arg-type]\n            body=[m.data for m in message],\n        )\n\n    else:\n        path_re: Optional[Pattern[str]]\n        if (\n            path is None\n            and (handler := context.get_local(\"handler_\"))\n            and (path_re := handler.path_regex) is not None\n            and (match := path_re.match(message.subject)) is not None\n        ):\n            path = match.groupdict()\n\n        headers = message.header or {}\n\n        return NatsMessage(\n            is_js=self.is_js,\n            raw_message=message,\n            body=message.data,\n            path=path or {},\n            reply_to=headers.get(\"reply_to\", \"\") if self.is_js else message.reply,\n            headers=headers,\n            content_type=headers.get(\"content-type\", \"\"),\n            message_id=headers.get(\"message_id\", str(uuid4())),\n            correlation_id=headers.get(\"correlation_id\", str(uuid4())),\n        )\n
","boost":0.5},{"location":"api/faststream/nats/producer/NatsFastProducer/","title":"NatsFastProducer","text":"","boost":0.5},{"location":"api/faststream/nats/producer/NatsFastProducer/#faststream.nats.producer.NatsFastProducer","title":"faststream.nats.producer.NatsFastProducer","text":"
NatsFastProducer(\n    connection: Client,\n    parser: Optional[AsyncCustomParser[Msg, NatsMessage]],\n    decoder: Optional[AsyncCustomDecoder[NatsMessage]],\n)\n
Source code in faststream/nats/producer.py
def __init__(\n    self,\n    connection: Client,\n    parser: Optional[AsyncCustomParser[Msg, NatsMessage]],\n    decoder: Optional[AsyncCustomDecoder[NatsMessage]],\n) -> None:\n    self._connection = connection\n    self._parser = resolve_custom_func(parser, Parser.parse_message)\n    self._decoder = resolve_custom_func(decoder, Parser.decode_message)\n
","boost":0.5},{"location":"api/faststream/nats/producer/NatsFastProducer/#faststream.nats.producer.NatsFastProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    subject: str,\n    reply_to: str = \"\",\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/producer.py
async def publish(\n    self,\n    message: SendableMessage,\n    subject: str,\n    reply_to: str = \"\",\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    payload, content_type = encode_message(message)\n\n    headers_to_send = {\n        \"content-type\": content_type or \"\",\n        \"correlation_id\": correlation_id or str(uuid4()),\n        **(headers or {}),\n    }\n\n    client = self._connection\n\n    if rpc:\n        if reply_to:\n            raise WRONG_PUBLISH_ARGS\n\n        token = client._nuid.next()\n        token.extend(token_hex(2).encode())\n        reply_to = token.decode()\n\n        future: asyncio.Future[Msg] = asyncio.Future()\n        sub = await client.subscribe(reply_to, future=future, max_msgs=1)\n        await sub.unsubscribe(limit=1)\n\n    await client.publish(\n        subject=subject,\n        payload=payload,\n        reply=reply_to,\n        headers=headers_to_send,\n    )\n\n    if rpc:\n        msg: Any = None\n        with timeout_scope(rpc_timeout, raise_timeout):\n            msg = await future\n\n        if msg:  # pragma: no branch\n            if msg.headers:  # pragma: no cover\n                if (\n                    msg.headers.get(nats.js.api.Header.STATUS)\n                    == nats.aio.client.NO_RESPONDERS_STATUS\n                ):\n                    raise nats.errors.NoRespondersError\n            return await self._decoder(await self._parser(msg))\n\n    return None\n
","boost":0.5},{"location":"api/faststream/nats/producer/NatsJSFastProducer/","title":"NatsJSFastProducer","text":"","boost":0.5},{"location":"api/faststream/nats/producer/NatsJSFastProducer/#faststream.nats.producer.NatsJSFastProducer","title":"faststream.nats.producer.NatsJSFastProducer","text":"
NatsJSFastProducer(\n    connection: JetStreamContext,\n    parser: Optional[AsyncCustomParser[Msg, NatsMessage]],\n    decoder: Optional[AsyncCustomDecoder[NatsMessage]],\n)\n
Source code in faststream/nats/producer.py
def __init__(\n    self,\n    connection: JetStreamContext,\n    parser: Optional[AsyncCustomParser[Msg, NatsMessage]],\n    decoder: Optional[AsyncCustomDecoder[NatsMessage]],\n) -> None:\n    self._connection = connection\n    self._parser = resolve_custom_func(parser, Parser.parse_message)\n    self._decoder = resolve_custom_func(decoder, Parser.decode_message)\n
","boost":0.5},{"location":"api/faststream/nats/producer/NatsJSFastProducer/#faststream.nats.producer.NatsJSFastProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    stream: Optional[str] = None,\n    timeout: Optional[float] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/producer.py
async def publish(\n    self,\n    message: SendableMessage,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    stream: Optional[str] = None,\n    timeout: Optional[float] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    payload, content_type = encode_message(message)\n\n    headers_to_send = {\n        \"content-type\": content_type or \"\",\n        \"correlation_id\": correlation_id or str(uuid4()),\n        **(headers or {}),\n    }\n\n    if rpc:\n        if reply_to:\n            raise WRONG_PUBLISH_ARGS\n\n        reply_to = str(uuid4())\n        future: asyncio.Future[Msg] = asyncio.Future()\n        sub = await self._connection._nc.subscribe(\n            reply_to, future=future, max_msgs=1\n        )\n        await sub.unsubscribe(limit=1)\n\n    if reply_to:\n        headers_to_send.update({\"reply_to\": reply_to})\n\n    await self._connection.publish(\n        subject=subject,\n        payload=payload,\n        headers=headers_to_send,\n        stream=stream,\n        timeout=timeout,\n    )\n\n    if rpc:\n        msg: Any = None\n        with timeout_scope(rpc_timeout, raise_timeout):\n            msg = await future\n\n        if msg:  # pragma: no branch\n            if msg.headers:  # pragma: no cover\n                if (\n                    msg.headers.get(nats.js.api.Header.STATUS)\n                    == nats.aio.client.NO_RESPONDERS_STATUS\n                ):\n                    raise nats.errors.NoRespondersError\n            return await self._decoder(await self._parser(msg))\n\n    return None\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/","title":"LogicPublisher","text":"","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher","title":"faststream.nats.publisher.LogicPublisher dataclass","text":"

Bases: BasePublisher[Msg]

","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.stream","title":"stream class-attribute instance-attribute","text":"
stream: Optional[JStream] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.subject","title":"subject class-attribute instance-attribute","text":"
subject: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: Optional[float] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.publish","title":"publish async","text":"
publish(\n    message: SendableMessage = \"\",\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[Dict[str, str]] = None,\n    **producer_kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage = \"\",\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[Dict[str, str]] = None,\n    **producer_kwargs: Any,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    assert self.subject, \"You have to specify outgoing subject\"  # nosec B101\n\n    extra: AnyDict = {\n        \"reply_to\": reply_to or self.reply_to,\n    }\n    if self.stream is not None:\n        extra.update(\n            {\n                \"stream\": self.stream.name,\n                \"timeout\": self.timeout,\n            }\n        )\n\n    return await self._producer.publish(\n        message=message,\n        subject=self.subject,\n        headers=headers or self.headers,\n        correlation_id=correlation_id,\n        **extra,\n        **producer_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/nats/pull_sub/PullSub/","title":"PullSub","text":"","boost":0.5},{"location":"api/faststream/nats/pull_sub/PullSub/#faststream.nats.pull_sub.PullSub","title":"faststream.nats.pull_sub.PullSub","text":"
PullSub(\n    batch_size: int = 1,\n    timeout: Optional[float] = 5.0,\n    batch: bool = False,\n)\n

Bases: BaseModel

Source code in faststream/nats/pull_sub.py
def __init__(\n    self,\n    batch_size: int = 1,\n    timeout: Optional[float] = 5.0,\n    batch: bool = False,\n) -> None:\n    super().__init__(\n        batch_size=batch_size,\n        timeout=timeout,\n        batch=batch,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/pull_sub/PullSub/#faststream.nats.pull_sub.PullSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = Field(default=False)\n
","boost":0.5},{"location":"api/faststream/nats/pull_sub/PullSub/#faststream.nats.pull_sub.PullSub.batch_size","title":"batch_size class-attribute instance-attribute","text":"
batch_size: int = Field(default=1)\n
","boost":0.5},{"location":"api/faststream/nats/pull_sub/PullSub/#faststream.nats.pull_sub.PullSub.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: Optional[float] = Field(default=5.0)\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/","title":"NatsRouter","text":"","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter","title":"faststream.nats.router.NatsRouter","text":"
NatsRouter(\n    prefix: str = \"\",\n    handlers: Sequence[NatsRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: NatsRouter

Source code in faststream/nats/router.py
    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.publisher","title":"publisher","text":"
publisher(\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/nats/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            subject=subject,\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    retry: bool = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
","boost":0.5},{"location":"api/faststream/nats/security/parse_security/","title":"parse_security","text":"","boost":0.5},{"location":"api/faststream/nats/security/parse_security/#faststream.nats.security.parse_security","title":"faststream.nats.security.parse_security","text":"
parse_security(security: Optional[BaseSecurity]) -> AnyDict\n
Source code in faststream/nats/security.py
def parse_security(security: Optional[BaseSecurity]) -> AnyDict:\n    if security is None:\n        return {}\n    elif isinstance(security, SASLPlaintext):\n        return _parse_sasl_plaintext(security)\n    elif isinstance(security, BaseSecurity):\n        return _parse_base_security(security)\n    else:\n        raise NotImplementedError(f\"NatsBroker does not support {type(security)}\")\n
","boost":0.5},{"location":"api/faststream/nats/shared/logging/NatsLoggingMixin/","title":"NatsLoggingMixin","text":"","boost":0.5},{"location":"api/faststream/nats/shared/logging/NatsLoggingMixin/#faststream.nats.shared.logging.NatsLoggingMixin","title":"faststream.nats.shared.logging.NatsLoggingMixin","text":"
NatsLoggingMixin(\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any\n)\n

Bases: LoggingMixin

Source code in faststream/nats/shared/logging.py
def __init__(\n    self,\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any,\n) -> None:\n    super().__init__(\n        *args,\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n        **kwargs,\n    )\n    self._max_queue_len = 0\n    self._max_stream_len = 0\n    self._max_subject_len = 4\n
","boost":0.5},{"location":"api/faststream/nats/shared/logging/NatsLoggingMixin/#faststream.nats.shared.logging.NatsLoggingMixin.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/nats/shared/logging/NatsLoggingMixin/#faststream.nats.shared.logging.NatsLoggingMixin.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/nats/shared/logging/NatsLoggingMixin/#faststream.nats.shared.logging.NatsLoggingMixin.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRoute/","title":"NatsRoute","text":"","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/","title":"NatsRouter","text":"","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter","title":"faststream.nats.shared.router.NatsRouter","text":"
NatsRouter(\n    prefix: str = \"\",\n    handlers: Sequence[NatsRoute] = (),\n    **kwargs: Any\n)\n

Bases: BrokerRouter[str, Msg]

Source code in faststream/nats/shared/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[NatsRoute[Msg, SendableMessage]] = (),\n    **kwargs: Any,\n) -> None:\n    for h in handlers:\n        if not (subj := h.kwargs.pop(\"subject\", None)):\n            subj, h.args = h.args[0], h.args[1:]\n        h.args = (prefix + subj, *h.args)\n    super().__init__(prefix, handlers, **kwargs)\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str, **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/nats/shared/router.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    subject: str,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],\n]:\n    return self._wrap_subscriber(\n        self.prefix + subject,\n        **broker_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/test/FakeProducer/","title":"FakeProducer","text":"","boost":0.5},{"location":"api/faststream/nats/test/FakeProducer/#faststream.nats.test.FakeProducer","title":"faststream.nats.test.FakeProducer","text":"
FakeProducer(broker: NatsBroker)\n

Bases: NatsFastProducer

Source code in faststream/nats/test.py
def __init__(self, broker: NatsBroker) -> None:\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/nats/test/FakeProducer/#faststream.nats.test.FakeProducer.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/nats/test/FakeProducer/#faststream.nats.test.FakeProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    subject: str,\n    reply_to: str = \"\",\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    timeout: Optional[float] = None,\n    stream: Optional[str] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False\n) -> Optional[SendableMessage]\n
Source code in faststream/nats/test.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage,\n    subject: str,\n    reply_to: str = \"\",\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    # NatsJSFastProducer compatibility\n    timeout: Optional[float] = None,\n    stream: Optional[str] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False,\n) -> Optional[SendableMessage]:\n    incoming = build_message(\n        message=message,\n        subject=subject,\n        headers=headers,\n        correlation_id=correlation_id,\n        reply_to=reply_to,\n    )\n\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        call = False\n\n        if stream and getattr(handler.stream, \"name\", None) != stream:\n            continue\n\n        if subject == handler.subject:\n            call = True\n\n        else:\n            call = True\n\n            for current, base in zip_longest(\n                subject.split(\".\"),\n                handler.subject.split(\".\"),\n                fillvalue=None,\n            ):\n                if base == \">\":\n                    break\n\n                if base != \"*\" and current != base:\n                    call = False\n                    break\n\n        if call:\n            r = await call_handler(\n                handler=handler,\n                message=[incoming]\n                if getattr(handler.pull_sub, \"batch\", False)\n                else incoming,\n                rpc=rpc,\n                rpc_timeout=rpc_timeout,\n                raise_timeout=raise_timeout,\n            )\n\n            if rpc:\n                return r\n\n    return None\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/","title":"PatchedMessage","text":"","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage","title":"faststream.nats.test.PatchedMessage","text":"

Bases: Msg

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.data","title":"data class-attribute instance-attribute","text":"
data: bytes = b''\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.header","title":"header property","text":"
header: Optional[Dict[str, str]]\n

header returns the headers from a message.

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = None\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.metadata","title":"metadata property","text":"
metadata: Metadata\n

metadata returns the Metadata of a JetStream message.

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.reply","title":"reply class-attribute instance-attribute","text":"
reply: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.sid","title":"sid property","text":"
sid: int\n

sid returns the subscription ID from a message.

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.subject","title":"subject class-attribute instance-attribute","text":"
subject: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack","title":"Ack","text":"","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.AccHash","title":"AccHash class-attribute instance-attribute","text":"
AccHash = 3\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Ack","title":"Ack class-attribute instance-attribute","text":"
Ack = b'+ACK'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Consumer","title":"Consumer class-attribute instance-attribute","text":"
Consumer = 5\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.ConsumerSeq","title":"ConsumerSeq class-attribute instance-attribute","text":"
ConsumerSeq = 8\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Domain","title":"Domain class-attribute instance-attribute","text":"
Domain = 2\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Nak","title":"Nak class-attribute instance-attribute","text":"
Nak = b'-NAK'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.NumDelivered","title":"NumDelivered class-attribute instance-attribute","text":"
NumDelivered = 6\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.NumPending","title":"NumPending class-attribute instance-attribute","text":"
NumPending = 10\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Prefix0","title":"Prefix0 class-attribute instance-attribute","text":"
Prefix0 = '$JS'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Prefix1","title":"Prefix1 class-attribute instance-attribute","text":"
Prefix1 = 'ACK'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Progress","title":"Progress class-attribute instance-attribute","text":"
Progress = b'+WPI'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Stream","title":"Stream class-attribute instance-attribute","text":"
Stream = 4\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.StreamSeq","title":"StreamSeq class-attribute instance-attribute","text":"
StreamSeq = 7\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Term","title":"Term class-attribute instance-attribute","text":"
Term = b'+TERM'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Timestamp","title":"Timestamp class-attribute instance-attribute","text":"
Timestamp = 9\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata","title":"Metadata dataclass","text":"

Metadata is the metadata from a JetStream message.

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.consumer","title":"consumer instance-attribute","text":"
consumer: str\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.domain","title":"domain class-attribute instance-attribute","text":"
domain: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.num_delivered","title":"num_delivered instance-attribute","text":"
num_delivered: int\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.num_pending","title":"num_pending instance-attribute","text":"
num_pending: int\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.sequence","title":"sequence instance-attribute","text":"
sequence: SequencePair\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.stream","title":"stream instance-attribute","text":"
stream: str\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.timestamp","title":"timestamp instance-attribute","text":"
timestamp: datetime.datetime\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.SequencePair","title":"SequencePair dataclass","text":"

SequencePair represents a pair of consumer and stream sequence.

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.SequencePair.consumer","title":"consumer instance-attribute","text":"
consumer: int\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.SequencePair.stream","title":"stream instance-attribute","text":"
stream: int\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.ack","title":"ack async","text":"
ack() -> None\n
Source code in faststream/nats/test.py
async def ack(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.ack_sync","title":"ack_sync async","text":"
ack_sync(timeout: float = 1) -> PatchedMessage\n
Source code in faststream/nats/test.py
async def ack_sync(\n    self, timeout: float = 1\n) -> \"PatchedMessage\":  # pragma: no cover\n    return self\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.in_progress","title":"in_progress async","text":"
in_progress() -> None\n
Source code in faststream/nats/test.py
async def in_progress(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.nak","title":"nak async","text":"
nak(delay: Union[int, float, None] = None) -> None\n
Source code in faststream/nats/test.py
async def nak(self, delay: Union[int, float, None] = None) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.respond","title":"respond async","text":"
respond(data: bytes) -> None\n

respond replies to the inbox of the message if there is one.

Source code in nats/aio/msg.py
async def respond(self, data: bytes) -> None:\n    \"\"\"\n    respond replies to the inbox of the message if there is one.\n    \"\"\"\n    if not self.reply:\n        raise Error('no reply subject available')\n    if not self._client:\n        raise Error('client not set')\n\n    await self._client.publish(self.reply, data, headers=self.headers)\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.term","title":"term async","text":"
term() -> None\n
Source code in faststream/nats/test.py
async def term(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/","title":"TestNatsBroker","text":"","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker","title":"faststream.nats.test.TestNatsBroker","text":"
TestNatsBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[NatsBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/nats/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: NatsBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(publisher.subject, _raw=True)\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(broker: NatsBroker, publisher: Any) -> None\n
Source code in faststream/nats/test.py
@staticmethod\ndef patch_publisher(broker: NatsBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> None\n
Source code in faststream/nats/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> None:\n    broker.handlers.pop(Handler.get_routing_hash(publisher.subject), None)\n
","boost":0.5},{"location":"api/faststream/nats/test/build_message/","title":"build_message","text":"","boost":0.5},{"location":"api/faststream/nats/test/build_message/#faststream.nats.test.build_message","title":"faststream.nats.test.build_message","text":"
build_message(\n    message: SendableMessage,\n    subject: str,\n    *,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[AnyDict] = None\n) -> PatchedMessage\n
Source code in faststream/nats/test.py
def build_message(\n    message: SendableMessage,\n    subject: str,\n    *,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[AnyDict] = None,\n) -> \"PatchedMessage\":\n    msg, content_type = encode_message(message)\n    return PatchedMessage(\n        _client=None,  # type: ignore\n        subject=subject,\n        reply=reply_to,\n        data=msg,\n        headers={\n            \"content-type\": content_type or \"\",\n            \"correlation_id\": correlation_id or str(uuid4()),\n            **(headers or {}),\n        },\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/","title":"ExchangeType","text":"","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType","title":"faststream.rabbit.ExchangeType","text":"

Bases: str, Enum

A class to represent the exchange type.

","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.DIRECT","title":"DIRECT class-attribute instance-attribute","text":"
DIRECT = 'direct'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.FANOUT","title":"FANOUT class-attribute instance-attribute","text":"
FANOUT = 'fanout'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.HEADERS","title":"HEADERS class-attribute instance-attribute","text":"
HEADERS = 'headers'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.TOPIC","title":"TOPIC class-attribute instance-attribute","text":"
TOPIC = 'topic'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.X_CONSISTENT_HASH","title":"X_CONSISTENT_HASH class-attribute instance-attribute","text":"
X_CONSISTENT_HASH = 'x-consistent-hash'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.X_DELAYED_MESSAGE","title":"X_DELAYED_MESSAGE class-attribute instance-attribute","text":"
X_DELAYED_MESSAGE = 'x-delayed-message'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.X_MODULUS_HASH","title":"X_MODULUS_HASH class-attribute instance-attribute","text":"
X_MODULUS_HASH = 'x-modulus-hash'\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/","title":"RabbitBroker","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker","title":"faststream.rabbit.RabbitBroker","text":"
RabbitBroker(\n    url: Union[\n        str, URL, None\n    ] = \"amqp://guest:guest@localhost:5672/\",\n    *,\n    host: str = None,\n    port: int = None,\n    login: str = None,\n    password: str = None,\n    virtualhost: str = None,\n    ssl_options: Optional[aio_pika.abc.SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    max_consumers: Optional[int] = None,\n    protocol: str = None,\n    protocol_version: Optional[str] = \"0.9.1\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: RabbitLoggingMixin, BrokerAsyncUsecase[IncomingMessage, RobustConnection]

A RabbitMQ broker for FastAPI applications.

This class extends the base BrokerAsyncUsecase and provides asynchronous support for RabbitMQ as a message broker.

PARAMETER DESCRIPTION url

The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".

TYPE: Union[str, URL, None] DEFAULT: 'amqp://guest:guest@localhost:5672/'

max_consumers

Maximum number of consumers to limit message consumption. Defaults to None.

TYPE: Optional[int] DEFAULT: None

protocol

The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".

TYPE: str DEFAULT: None

protocol_version

The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".

TYPE: Optional[str] DEFAULT: '0.9.1'

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Initialize the RabbitBroker.

PARAMETER DESCRIPTION url

The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".

TYPE: Union[str, URL, None] DEFAULT: 'amqp://guest:guest@localhost:5672/'

max_consumers

Maximum number of consumers to limit message consumption. Defaults to None.

TYPE: Optional[int] DEFAULT: None

protocol

The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".

TYPE: str DEFAULT: None

protocol_version

The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".

TYPE: Optional[str] DEFAULT: '0.9.1'

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/rabbit/broker.py
def __init__(\n    self,\n    url: Union[str, URL, None] = \"amqp://guest:guest@localhost:5672/\",\n    *,\n    # connection args\n    host: Optional[str] = None,\n    port: Optional[int] = None,\n    login: Optional[str] = None,\n    password: Optional[str] = None,\n    virtualhost: Optional[str] = None,\n    ssl_options: Optional[SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    # broker args\n    max_consumers: Optional[int] = None,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"0.9.1\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Initialize the RabbitBroker.\n\n    Args:\n        url (Union[str, URL, None], optional): The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".\n        max_consumers (Optional[int], optional): Maximum number of consumers to limit message consumption. Defaults to None.\n        protocol (str, optional): The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".\n        protocol_version (Optional[str], optional): The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".\n        **kwargs: Additional keyword arguments.\n    \"\"\"\n    security_args = parse_security(security)\n\n    if (ssl := kwargs.get(\"ssl\")) or kwargs.get(\"ssl_context\"):  # pragma: no cover\n        warnings.warn(\n            (\n                f\"\\nRabbitMQ {'`ssl`' if ssl else '`ssl_context`'} option was deprecated and will be removed in 0.4.0\"\n                \"\\nPlease, use `security` with `BaseSecurity` or `SASLPlaintext` instead\"\n            ),\n            DeprecationWarning,\n            stacklevel=2,\n        )\n\n    amqp_url = build_url(\n        url,\n        host=host,\n        port=port,\n        login=security_args.get(\"login\", login),\n        password=security_args.get(\"password\", password),\n        virtualhost=virtualhost,\n        ssl=security_args.get(\"ssl\", kwargs.pop(\"ssl\", False)),\n        ssl_options=ssl_options,\n        client_properties=client_properties,\n    )\n\n    super().__init__(\n        url=str(amqp_url),\n        protocol_version=protocol_version,\n        security=security,\n        ssl_context=security_args.get(\n            \"ssl_context\",\n            kwargs.pop(\"ssl_context\", None),\n        ),\n        **kwargs,\n    )\n\n    # respect ascynapi_url argument scheme\n    asyncapi_url = build_url(self.url)\n    self.protocol = protocol or asyncapi_url.scheme\n    self.virtual_host = asyncapi_url.path\n\n    self._max_consumers = max_consumers\n\n    self._channel = None\n    self.declarer = None\n    self._producer = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.declarer","title":"declarer instance-attribute","text":"
declarer: Optional[RabbitDeclarer] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[int, Handler]\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol or asyncapi_url.scheme\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.virtual_host","title":"virtual_host instance-attribute","text":"
virtual_host = asyncapi_url.path\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.connect","title":"connect async","text":"
connect(\n    *args: Any, **kwargs: Any\n) -> aio_pika.RobustConnection\n

Connect to the RabbitMQ server.

PARAMETER DESCRIPTION *args

Additional positional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION RobustConnection

aio_pika.RobustConnection: The RabbitMQ connection instance.

Source code in faststream/rabbit/broker.py
async def connect(self, *args: Any, **kwargs: Any) -> aio_pika.RobustConnection:\n    \"\"\"\n    Connect to the RabbitMQ server.\n\n    Args:\n        *args: Additional positional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        aio_pika.RobustConnection: The RabbitMQ connection instance.\n    \"\"\"\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.declare_exchange","title":"declare_exchange async","text":"
declare_exchange(\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange\n

Declare a RabbitMQ exchange.

PARAMETER DESCRIPTION exchange

The RabbitMQ exchange to declare.

TYPE: RabbitExchange

RETURNS DESCRIPTION RobustExchange

aio_pika.RobustExchange: The declared RabbitMQ exchange.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def declare_exchange(\n    self,\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange:\n    \"\"\"\n    Declare a RabbitMQ exchange.\n\n    Args:\n        exchange (RabbitExchange): The RabbitMQ exchange to declare.\n\n    Returns:\n        aio_pika.RobustExchange: The declared RabbitMQ exchange.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n    return await self.declarer.declare_exchange(exchange)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.declare_queue","title":"declare_queue async","text":"
declare_queue(queue: RabbitQueue) -> aio_pika.RobustQueue\n

Declare a RabbitMQ queue.

PARAMETER DESCRIPTION queue

The RabbitMQ queue to declare.

TYPE: RabbitQueue

RETURNS DESCRIPTION RobustQueue

aio_pika.RobustQueue: The declared RabbitMQ queue.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def declare_queue(\n    self,\n    queue: RabbitQueue,\n) -> aio_pika.RobustQueue:\n    \"\"\"\n    Declare a RabbitMQ queue.\n\n    Args:\n        queue (RabbitQueue): The RabbitMQ queue to declare.\n\n    Returns:\n        aio_pika.RobustQueue: The declared RabbitMQ queue.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n    return await self.declarer.declare_queue(queue)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, **kwargs: Any\n) -> Union[\n    aiormq.abc.ConfirmationFrameType, SendableMessage\n]\n

Publish a message to the RabbitMQ broker.

PARAMETER DESCRIPTION *args

Additional positional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Union[ConfirmationFrameType, SendableMessage]

Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The confirmation frame or the response message.

Source code in faststream/rabbit/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Union[aiormq.abc.ConfirmationFrameType, SendableMessage]:\n    \"\"\"\n    Publish a message to the RabbitMQ broker.\n\n    Args:\n        *args: Additional positional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The confirmation frame or the response message.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.publisher","title":"publisher","text":"
publisher(\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Publisher\n

Define a message publisher.

PARAMETER DESCRIPTION queue

The name of the RabbitMQ queue. Defaults to \"\".

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The name of the RabbitMQ exchange. Defaults to None.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key for messages. Defaults to \"\".

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory. Defaults to True.

TYPE: bool DEFAULT: True

immediate

Whether the message should be sent immediately. Defaults to False.

TYPE: bool DEFAULT: False

timeout

Timeout for message publishing. Defaults to None.

TYPE: TimeoutType DEFAULT: None

persist

Whether to persist messages. Defaults to False.

TYPE: bool DEFAULT: False

reply_to

The reply-to queue name. Defaults to None.

TYPE: Optional[str] DEFAULT: None

title

Title for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

description

Description for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional message properties and content.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Publisher

A message publisher instance.

TYPE: Publisher

Source code in faststream/rabbit/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Publisher:\n    \"\"\"\n    Define a message publisher.\n\n    Args:\n        queue (Union[RabbitQueue, str], optional): The name of the RabbitMQ queue. Defaults to \"\".\n        exchange (Union[RabbitExchange, str, None], optional): The name of the RabbitMQ exchange. Defaults to None.\n        routing_key (str, optional): The routing key for messages. Defaults to \"\".\n        mandatory (bool, optional): Whether the message is mandatory. Defaults to True.\n        immediate (bool, optional): Whether the message should be sent immediately. Defaults to False.\n        timeout (TimeoutType, optional): Timeout for message publishing. Defaults to None.\n        persist (bool, optional): Whether to persist messages. Defaults to False.\n        reply_to (Optional[str], optional): The reply-to queue name. Defaults to None.\n        title (Optional[str]): Title for AsyncAPI docs.\n        description (Optional[str]): Description for AsyncAPI docs.\n        **message_kwargs (Any): Additional message properties and content.\n\n    Returns:\n        Publisher: A message publisher instance.\n    \"\"\"\n    q, ex = RabbitQueue.validate(queue), RabbitExchange.validate(exchange)\n\n    publisher = Publisher(\n        title=title,\n        queue=q,\n        exchange=ex,\n        routing_key=routing_key,\n        mandatory=mandatory,\n        immediate=immediate,\n        timeout=timeout,\n        persist=persist,\n        reply_to=reply_to,\n        priority=priority,\n        message_kwargs=message_kwargs,\n        _description=description,\n        _schema=schema,\n        virtual_host=self.virtual_host,\n        include_in_schema=include_in_schema,\n    )\n\n    key = publisher._get_routing_hash()\n    publisher = self._publishers.get(key, publisher)\n    super().publisher(key, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.start","title":"start async","text":"
start() -> None\n

Start the RabbitMQ broker.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def start(self) -> None:\n    \"\"\"\n    Start the RabbitMQ broker.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, RabbitQueue(\"\"), RabbitExchange(\"\")),\n    )\n\n    await super().start()\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n\n    for publisher in self._publishers.values():\n        if publisher.exchange is not None:\n            await self.declare_exchange(publisher.exchange)\n\n    for handler in self.handlers.values():\n        c = self._get_log_context(None, handler.queue, handler.exchange)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self.declarer)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Filter[RabbitMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n

Decorator to define a message subscriber.

PARAMETER DESCRIPTION queue

The name of the RabbitMQ queue.

TYPE: Union[str, RabbitQueue]

exchange

The name of the RabbitMQ exchange. Defaults to None.

TYPE: Union[str, RabbitExchange, None] DEFAULT: None

consume_args

Additional arguments for message consumption.

TYPE: Optional[AnyDict] DEFAULT: None

no_ack

Whether not to ack/nack/reject messages.

TYPE: bool DEFAULT: False

title

Title for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

description

Description for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION Callable

A decorator function for defining message subscribers.

TYPE: Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn]]

Source code in faststream/rabbit/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[aio_pika.IncomingMessage, RabbitMessage]] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[aio_pika.IncomingMessage], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RabbitMessage] = default_filter,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"\n    Decorator to define a message subscriber.\n\n    Args:\n        queue (Union[str, RabbitQueue]): The name of the RabbitMQ queue.\n        exchange (Union[str, RabbitExchange, None], optional): The name of the RabbitMQ exchange. Defaults to None.\n        consume_args (Optional[AnyDict], optional): Additional arguments for message consumption.\n        no_ack (bool): Whether not to ack/nack/reject messages.\n        title (Optional[str]): Title for AsyncAPI docs.\n        description (Optional[str]): Description for AsyncAPI docs.\n\n    Returns:\n        Callable: A decorator function for defining message subscribers.\n    \"\"\"\n    super().subscriber()\n\n    r_queue = RabbitQueue.validate(queue)\n    r_exchange = RabbitExchange.validate(exchange)\n\n    self._setup_log_context(r_queue, r_exchange)\n\n    key = get_routing_hash(r_queue, r_exchange)\n    handler = self.handlers.get(\n        key,\n        Handler(\n            log_context_builder=partial(\n                self._get_log_context, queue=r_queue, exchange=r_exchange\n            ),\n            queue=r_queue,\n            exchange=r_exchange,\n            consume_args=consume_args,\n            description=description,\n            title=title,\n            virtual_host=self.virtual_host,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n        ),\n    )\n\n    self.handlers[key] = handler\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[\n        aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn\n    ]:\n        \"\"\"Wraps a consumer function with additional functionality.\n\n        Args:\n            func: The consumer function to be wrapped.\n\n        Returns:\n            The wrapped consumer function.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            _process_kwargs={\n                \"reply_config\": reply_config,\n            },\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/","title":"RabbitExchange","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange","title":"faststream.rabbit.RabbitExchange","text":"
RabbitExchange(\n    name: str,\n    type: ExchangeType = ExchangeType.DIRECT,\n    durable: bool = False,\n    auto_delete: bool = False,\n    internal: bool = False,\n    passive: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_to: Optional[RabbitExchange] = None,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n)\n

Bases: NameRequired

A class to represent a RabbitMQ exchange.

METHOD DESCRIPTION __hash__

returns the hash value of the exchange

__init__

initializes the RabbitExchange object

Initialize a RabbitExchange object.

PARAMETER DESCRIPTION name

Name of the exchange.

TYPE: str

type

Type of the exchange. Defaults to ExchangeType.DIRECT.

TYPE: ExchangeType DEFAULT: DIRECT

durable

Whether the exchange should survive broker restarts. Defaults to False.

TYPE: bool DEFAULT: False

auto_delete

Whether the exchange should be deleted when no longer in use. Defaults to False.

TYPE: bool DEFAULT: False

internal

Whether the exchange is used for internal purposes and should not be published to directly. Defaults to False.

TYPE: bool DEFAULT: False

passive

Whether to check if the exchange exists before creating it. Defaults to False.

TYPE: bool DEFAULT: False

arguments

Additional arguments for the exchange. Defaults to None.

TYPE: Optional[AnyDict] DEFAULT: None

timeout

Timeout for the operation. Defaults to None.

TYPE: TimeoutType DEFAULT: None

robust

Whether to use robust mode for the exchange. Defaults to True.

TYPE: bool DEFAULT: True

bind_to

Exchange to bind to. Defaults to None.

TYPE: Optional[RabbitExchange] DEFAULT: None

bind_arguments

Arguments for the binding. Defaults to None.

TYPE: Optional[AnyDict] DEFAULT: None

routing_key

Routing key for the exchange. Defaults to \"\".

TYPE: str DEFAULT: ''

RAISES DESCRIPTION NotImplementedError Source code in faststream/rabbit/shared/schemas.py
def __init__(\n    self,\n    name: str,\n    type: ExchangeType = ExchangeType.DIRECT,\n    durable: bool = False,\n    auto_delete: bool = False,\n    internal: bool = False,\n    passive: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_to: Optional[\"RabbitExchange\"] = None,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n) -> None:\n    \"\"\"Initialize a RabbitExchange object.\n\n    Args:\n        name (str): Name of the exchange.\n        type (ExchangeType, optional): Type of the exchange. Defaults to ExchangeType.DIRECT.\n        durable (bool, optional): Whether the exchange should survive broker restarts. Defaults to False.\n        auto_delete (bool, optional): Whether the exchange should be deleted when no longer in use. Defaults to False.\n        internal (bool, optional): Whether the exchange is used for internal purposes and should not be published to directly. Defaults to False.\n        passive (bool, optional): Whether to check if the exchange exists before creating it. Defaults to False.\n        arguments (Optional[AnyDict], optional): Additional arguments for the exchange. Defaults to None.\n        timeout (TimeoutType, optional): Timeout for the operation. Defaults to None.\n        robust (bool, optional): Whether to use robust mode for the exchange. Defaults to True.\n        bind_to (Optional[\"RabbitExchange\"], optional): Exchange to bind to. Defaults to None.\n        bind_arguments (Optional[AnyDict], optional): Arguments for the binding. Defaults to None.\n        routing_key (str, optional): Routing key for the exchange. Defaults to \"\".\n\n    Raises:\n        NotImplementedError:\n\n    \"\"\"\n    if routing_key and bind_to is None:  # pragma: no cover\n        warnings.warn(\n            (\n                \"\\nRabbitExchange `routing_key` is using to bind exchange to another one\"\n                \"\\nIt can be used only with the `bind_to` argument, please setup it too\"\n            ),\n            category=RuntimeWarning,\n            stacklevel=1,\n        )\n\n    super().__init__(\n        name=name,\n        type=type.value,\n        durable=durable,\n        auto_delete=auto_delete,\n        routing_key=routing_key,\n        bind_to=bind_to,\n        bind_arguments=bind_arguments,\n        robust=robust,\n        internal=internal,\n        passive=passive,\n        timeout=timeout,\n        arguments=arguments,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.arguments","title":"arguments class-attribute instance-attribute","text":"
arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.auto_delete","title":"auto_delete class-attribute instance-attribute","text":"
auto_delete: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.bind_arguments","title":"bind_arguments class-attribute instance-attribute","text":"
bind_arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.bind_to","title":"bind_to class-attribute instance-attribute","text":"
bind_to: Optional[RabbitExchange] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.durable","title":"durable class-attribute instance-attribute","text":"
durable: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.internal","title":"internal class-attribute instance-attribute","text":"
internal: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.passive","title":"passive class-attribute instance-attribute","text":"
passive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.robust","title":"robust class-attribute instance-attribute","text":"
robust: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.type","title":"type class-attribute instance-attribute","text":"
type: str = ExchangeType.DIRECT.value\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/","title":"RabbitQueue","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue","title":"faststream.rabbit.RabbitQueue","text":"
RabbitQueue(\n    name: str,\n    durable: bool = False,\n    exclusive: bool = False,\n    passive: bool = False,\n    auto_delete: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n)\n

Bases: NameRequired

A class to represent a RabbitMQ queue.

METHOD DESCRIPTION __hash__

returns the hash value of the queue

routing

returns the routing key of the queue

__init__

initializes the RabbitQueue object with the given parameters

Initialize a class object.

PARAMETER DESCRIPTION name

The name of the object.

TYPE: str

durable

Whether the object is durable. Defaults to False.

TYPE: bool DEFAULT: False

exclusive

Whether the object is exclusive. Defaults to False.

TYPE: bool DEFAULT: False

passive

Whether the object is passive. Defaults to False.

TYPE: bool DEFAULT: False

auto_delete

Whether the object is auto delete. Defaults to False.

TYPE: bool DEFAULT: False

arguments

Additional arguments for the object. Defaults to None.

TYPE: dict DEFAULT: None

timeout

Timeout for the object. Defaults to None.

TYPE: TimeoutType DEFAULT: None

robust

Whether the object is robust. Defaults to True.

TYPE: bool DEFAULT: True

bind_arguments

Bind arguments for the object. Defaults to None.

TYPE: dict DEFAULT: None

routing_key

Routing key for the object. Defaults to \"\".

TYPE: str DEFAULT: ''

Source code in faststream/rabbit/shared/schemas.py
def __init__(\n    self,\n    name: str,\n    durable: bool = False,\n    exclusive: bool = False,\n    passive: bool = False,\n    auto_delete: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n) -> None:\n    \"\"\"Initialize a class object.\n\n    Args:\n        name (str): The name of the object.\n        durable (bool, optional): Whether the object is durable. Defaults to False.\n        exclusive (bool, optional): Whether the object is exclusive. Defaults to False.\n        passive (bool, optional): Whether the object is passive. Defaults to False.\n        auto_delete (bool, optional): Whether the object is auto delete. Defaults to False.\n        arguments (dict, optional): Additional arguments for the object. Defaults to None.\n        timeout (TimeoutType, optional): Timeout for the object. Defaults to None.\n        robust (bool, optional): Whether the object is robust. Defaults to True.\n        bind_arguments (dict, optional): Bind arguments for the object. Defaults to None.\n        routing_key (str, optional): Routing key for the object. Defaults to \"\".\n\n    \"\"\"\n    re, routing_key = compile_path(routing_key, replace_symbol=\"*\")\n    super().__init__(\n        name=name,\n        path_regex=re,\n        durable=durable,\n        exclusive=exclusive,\n        bind_arguments=bind_arguments,\n        routing_key=routing_key,\n        robust=robust,\n        passive=passive,\n        auto_delete=auto_delete,\n        arguments=arguments,\n        timeout=timeout,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.arguments","title":"arguments class-attribute instance-attribute","text":"
arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.auto_delete","title":"auto_delete class-attribute instance-attribute","text":"
auto_delete: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.bind_arguments","title":"bind_arguments class-attribute instance-attribute","text":"
bind_arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.durable","title":"durable class-attribute instance-attribute","text":"
durable: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.exclusive","title":"exclusive class-attribute instance-attribute","text":"
exclusive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'arbitrary_types_allowed': True}\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.name","title":"name class-attribute instance-attribute","text":"
name: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.passive","title":"passive class-attribute instance-attribute","text":"
passive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.path_regex","title":"path_regex class-attribute instance-attribute","text":"
path_regex: Optional[Pattern[str]] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.robust","title":"robust class-attribute instance-attribute","text":"
robust: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.routing","title":"routing property","text":"
routing: str\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.Config.arbitrary_types_allowed","title":"arbitrary_types_allowed class-attribute instance-attribute","text":"
arbitrary_types_allowed = True\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRoute/","title":"RabbitRoute","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/","title":"RabbitRouter","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter","title":"faststream.rabbit.RabbitRouter","text":"
RabbitRouter(\n    prefix: str = \"\",\n    handlers: Sequence[RabbitRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: RabbitRouter

A class representing a RabbitMQ router for publishing messages.

METHOD DESCRIPTION _get_publisher_key

Returns the key for a given Publisher object

_update_publisher_prefix

Updates the prefix of a given Publisher object

publisher

Publishes a message to RabbitMQ

Source code in faststream/rabbit/router.py
_publishers: Dict[int, Publisher]\n\n@staticmethod\ndef _get_publisher_key(publisher: Publisher) -> int:\n    \"\"\"Get the publisher key.\n\n    Args:\n        publisher: The publisher object.\n\n    Returns:\n        The publisher key as an integer.\n\n    \"\"\"\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.publisher","title":"publisher","text":"
publisher(\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Publisher\n

Publishes a message to a RabbitMQ queue or exchange.

PARAMETER DESCRIPTION queue

The RabbitMQ queue to publish the message to. Can be either a RabbitQueue object or a string representing the queue name.

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The RabbitMQ exchange to publish the message to. Can be either a RabbitExchange object, a string representing the exchange name, or None.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key to use when publishing the message.

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory or not.

TYPE: bool DEFAULT: True

immediate

Whether the message should be delivered immediately or not.

TYPE: bool DEFAULT: False

timeout

The timeout for the publish operation.

TYPE: TimeoutType DEFAULT: None

persist

Whether the message should be persisted or not.

TYPE: bool DEFAULT: False

reply_to

The reply-to address for the message.

TYPE: Optional[str] DEFAULT: None

title

The title of the message (AsyncAPI information).

TYPE: Optional[str] DEFAULT: None

description

The description of the message (AsyncAPI information).

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional keyword arguments to include in the message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Publisher

The Publisher object used to publish the message.

Source code in faststream/rabbit/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Publisher:\n    \"\"\"Publishes a message to a RabbitMQ queue or exchange.\n\n    Args:\n        queue: The RabbitMQ queue to publish the message to. Can be either a RabbitQueue object or a string representing the queue name.\n        exchange: The RabbitMQ exchange to publish the message to. Can be either a RabbitExchange object, a string representing the exchange name, or None.\n        routing_key: The routing key to use when publishing the message.\n        mandatory: Whether the message is mandatory or not.\n        immediate: Whether the message should be delivered immediately or not.\n        timeout: The timeout for the publish operation.\n        persist: Whether the message should be persisted or not.\n        reply_to: The reply-to address for the message.\n        title: The title of the message (AsyncAPI information).\n        description: The description of the message (AsyncAPI information).\n        **message_kwargs: Additional keyword arguments to include in the message.\n\n    Returns:\n        The Publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            queue=RabbitQueue.validate(queue),\n            exchange=RabbitExchange.validate(exchange),\n            routing_key=routing_key,\n            mandatory=mandatory,\n            immediate=immediate,\n            timeout=timeout,\n            persist=persist,\n            reply_to=reply_to,\n            priority=priority,\n            message_kwargs=message_kwargs,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[key] = self._publishers.get(key, new_publisher)\n    return publisher\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    dependencies: Sequence[Depends] = (),\n    filter: Filter[RabbitMessage] = default_filter,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    retry: Union[bool, int] = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n
Source code in faststream/rabbit/router.py
    Returns:\n        Publisher: The updated publisher object.\n\n    Note:\n        This function is intended to be used as a decorator.\n\n    \"\"\"\n    publisher.queue = model_copy(\n        publisher.queue, update={\"name\": prefix + publisher.queue.name}\n    )\n    return publisher\n\n@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n
","boost":0.5},{"location":"api/faststream/rabbit/ReplyConfig/","title":"ReplyConfig","text":"","boost":0.5},{"location":"api/faststream/rabbit/ReplyConfig/#faststream.rabbit.ReplyConfig","title":"faststream.rabbit.ReplyConfig","text":"

Bases: BaseModel

","boost":0.5},{"location":"api/faststream/rabbit/ReplyConfig/#faststream.rabbit.ReplyConfig.immediate","title":"immediate class-attribute instance-attribute","text":"
immediate: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/ReplyConfig/#faststream.rabbit.ReplyConfig.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/ReplyConfig/#faststream.rabbit.ReplyConfig.persist","title":"persist class-attribute instance-attribute","text":"
persist: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/rabbit/TestApp/#faststream.broker.test.TestApp","title":"faststream.broker.test.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/rabbit/TestApp/#faststream.broker.test.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/","title":"TestRabbitBroker","text":"","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker","title":"faststream.rabbit.TestRabbitBroker","text":"
TestRabbitBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[RabbitBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: RabbitBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: RabbitBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(\n        queue=publisher.queue,\n        exchange=publisher.exchange,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: RabbitBroker, publisher: Any\n) -> None\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef patch_publisher(broker: RabbitBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: RabbitBroker, publisher: Publisher\n) -> None\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: RabbitBroker,\n    publisher: Publisher,\n) -> None:\n    broker.handlers.pop(\n        publisher._get_routing_hash(),\n        None,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/","title":"Handler","text":"","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler","title":"faststream.rabbit.asyncapi.Handler","text":"
Handler(\n    queue: RabbitQueue,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    exchange: Optional[RabbitExchange] = None,\n    consume_args: Optional[AnyDict] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    virtual_host: str = \"/\",\n)\n

Bases: LogicHandler

A class that serves as a handler for RMQAsyncAPIChannel and LogicHandler.

METHOD DESCRIPTION - name

Returns the name of the handler.

- get_payloads

Returns a list of payloads.

Initialize a RabbitMQ consumer.

PARAMETER DESCRIPTION queue

RabbitQueue object representing the queue to consume from

TYPE: RabbitQueue

exchange

RabbitExchange object representing the exchange to bind the queue to (optional)

TYPE: Optional[RabbitExchange] DEFAULT: None

consume_args

Additional arguments for consuming from the queue (optional)

TYPE: Optional[AnyDict] DEFAULT: None

description

Description of the consumer (optional)

TYPE: Optional[str] DEFAULT: None

title

Title of the consumer (optional)

TYPE: Optional[str] DEFAULT: None

Source code in faststream/rabbit/handler.py
def __init__(\n    self,\n    queue: RabbitQueue,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # RMQ information\n    exchange: Optional[RabbitExchange] = None,\n    consume_args: Optional[AnyDict] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    virtual_host: str = \"/\",\n) -> None:\n    \"\"\"Initialize a RabbitMQ consumer.\n\n    Args:\n        queue: RabbitQueue object representing the queue to consume from\n        exchange: RabbitExchange object representing the exchange to bind the queue to (optional)\n        consume_args: Additional arguments for consuming from the queue (optional)\n        description: Description of the consumer (optional)\n        title: Title of the consumer (optional)\n\n    \"\"\"\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.queue = queue\n    self.exchange = exchange\n    self.virtual_host = virtual_host\n    self.consume_args = consume_args or {}\n\n    self._consumer_tag = None\n    self._queue_obj = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.consume_args","title":"consume_args instance-attribute","text":"
consume_args: AnyDict = consume_args or {}\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.exchange","title":"exchange instance-attribute","text":"
exchange: Optional[RabbitExchange] = exchange\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.queue","title":"queue instance-attribute","text":"
queue: RabbitQueue = queue\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.virtual_host","title":"virtual_host instance-attribute","text":"
virtual_host = virtual_host\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ],\n    decoder: Optional[CustomDecoder[RabbitMessage]],\n    filter: Filter[RabbitMessage],\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ]\n) -> None\n

Add a call to the handler.

PARAMETER DESCRIPTION handler

The handler for the call.

TYPE: HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn]

dependant

The dependant for the call.

TYPE: CallModel[P_HandlerParams, T_HandlerReturn]

parser

Optional custom parser for the call.

TYPE: Optional[CustomParser[IncomingMessage, RabbitMessage]]

decoder

Optional custom decoder for the call.

TYPE: Optional[CustomDecoder[RabbitMessage]]

filter

The filter for the call.

TYPE: Filter[RabbitMessage]

middlewares

Optional sequence of middlewares for the call.

TYPE: Optional[Sequence[Callable[[IncomingMessage], BaseMiddleware]]]

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[\n        aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[aio_pika.IncomingMessage, RabbitMessage]],\n    decoder: Optional[CustomDecoder[RabbitMessage]],\n    filter: Filter[RabbitMessage],\n    middlewares: Optional[\n        Sequence[Callable[[aio_pika.IncomingMessage], BaseMiddleware]]\n    ],\n) -> None:\n    \"\"\"Add a call to the handler.\n\n    Args:\n        handler: The handler for the call.\n        dependant: The dependant for the call.\n        parser: Optional custom parser for the call.\n        decoder: Optional custom decoder for the call.\n        filter: The filter for the call.\n        middlewares: Optional sequence of middlewares for the call.\n\n    Returns:\n        None\n\n    \"\"\"\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, AioPikaParser.parse_message),\n        decoder=resolve_custom_func(decoder, AioPikaParser.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/rabbit/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self._queue_obj is not None:\n        if self._consumer_tag is not None:  # pragma: no branch\n            await self._queue_obj.cancel(self._consumer_tag)\n            self._consumer_tag = None\n        self._queue_obj = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/rabbit/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    handler_name = (\n        self._title\n        or f\"{self.queue.name}:{getattr(self.exchange, 'name', '_')}:{self.call_name}\"\n    )\n\n    return {\n        handler_name: Channel(\n            description=self.description,  # type: ignore[attr-defined]\n            subscribe=Operation(\n                bindings=OperationBinding(\n                    amqp=amqp.OperationBinding(\n                        cc=self.queue.routing,\n                    ),\n                )\n                if _is_exchange(self.exchange)\n                else None,\n                message=Message(\n                    title=f\"{handler_name}:Message\",\n                    payload=resolve_payloads(payloads),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                amqp=amqp.ChannelBinding(\n                    **{\n                        \"is\": \"routingKey\",  # type: ignore\n                        \"queue\": amqp.Queue(\n                            name=self.queue.name,\n                            durable=self.queue.durable,\n                            exclusive=self.queue.exclusive,\n                            autoDelete=self.queue.auto_delete,\n                            vhost=self.virtual_host,\n                        )\n                        if _is_exchange(self.exchange)\n                        else None,\n                        \"exchange\": (\n                            amqp.Exchange(type=\"default\", vhost=self.virtual_host)\n                            if self.exchange is None\n                            else amqp.Exchange(\n                                type=self.exchange.type,  # type: ignore\n                                name=self.exchange.name,\n                                durable=self.exchange.durable,\n                                autoDelete=self.exchange.auto_delete,\n                                vhost=self.virtual_host,\n                            )\n                        ),\n                    }\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.start","title":"start async","text":"
start(declarer: RabbitDeclarer) -> None\n

Starts the consumer for the RabbitMQ queue.

PARAMETER DESCRIPTION declarer

RabbitDeclarer object used to declare the queue and exchange

TYPE: RabbitDeclarer

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/handler.py
@override\nasync def start(self, declarer: RabbitDeclarer) -> None:  # type: ignore[override]\n    \"\"\"Starts the consumer for the RabbitMQ queue.\n\n    Args:\n        declarer: RabbitDeclarer object used to declare the queue and exchange\n\n    Returns:\n        None\n\n    \"\"\"\n    self._queue_obj = queue = await declarer.declare_queue(self.queue)\n\n    if self.exchange is not None:\n        exchange = await declarer.declare_exchange(self.exchange)\n        await queue.bind(\n            exchange,\n            routing_key=self.queue.routing,\n            arguments=self.queue.bind_arguments,\n        )\n\n    self._consumer_tag = await queue.consume(\n        # NOTE: aio-pika expects AbstractIncomingMessage, not IncomingMessage\n        self.consume,  # type: ignore[arg-type]\n        arguments=self.consume_args,\n    )\n\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/","title":"Publisher","text":"","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher","title":"faststream.rabbit.asyncapi.Publisher","text":"

Bases: LogicPublisher

A class representing a publisher.

METHOD DESCRIPTION get_payloads

Get the payloads for the publisher

","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.exchange","title":"exchange class-attribute instance-attribute","text":"
exchange: Optional[RabbitExchange] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.immediate","title":"immediate class-attribute instance-attribute","text":"
immediate: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.message_kwargs","title":"message_kwargs class-attribute instance-attribute","text":"
message_kwargs: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.name","title":"name property","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.persist","title":"persist class-attribute instance-attribute","text":"
persist: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.priority","title":"priority class-attribute instance-attribute","text":"
priority: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.queue","title":"queue class-attribute instance-attribute","text":"
queue: RabbitQueue = field(default=RabbitQueue(''))\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.routing","title":"routing property","text":"
routing: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.virtual_host","title":"virtual_host class-attribute instance-attribute","text":"
virtual_host: str = '/'\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.publish","title":"publish async","text":"
publish(\n    message: AioPikaSendableMessage = \"\",\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    correlation_id: Optional[str] = None,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Union[\n    aiormq.abc.ConfirmationFrameType, SendableMessage\n]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: AioPikaSendableMessage DEFAULT: ''

rpc

Whether the message is for RPC (Remote Procedure Call).

TYPE: bool DEFAULT: False

rpc_timeout

Timeout for RPC.

TYPE: Optional[float] DEFAULT: 30.0

raise_timeout

Whether to raise an exception if timeout occurs.

TYPE: bool DEFAULT: False

correlation_id

Correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional keyword arguments for the message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Union[ConfirmationFrameType, SendableMessage]

ConfirmationFrameType or SendableMessage: The result of the publish operation.

RAISES DESCRIPTION AssertionError

If _producer is not set up.

Source code in faststream/rabbit/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: AioPikaSendableMessage = \"\",\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    correlation_id: Optional[str] = None,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Union[aiormq.abc.ConfirmationFrameType, SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        rpc: Whether the message is for RPC (Remote Procedure Call).\n        rpc_timeout: Timeout for RPC.\n        raise_timeout: Whether to raise an exception if timeout occurs.\n        correlation_id: Correlation ID for the message.\n        **message_kwargs: Additional keyword arguments for the message.\n\n    Returns:\n        ConfirmationFrameType or SendableMessage: The result of the publish operation.\n\n    Raises:\n        AssertionError: If `_producer` is not set up.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(\n        message=message,\n        exchange=self.exchange,\n        routing_key=self.routing,\n        mandatory=self.mandatory,\n        immediate=self.immediate,\n        timeout=self.timeout,\n        rpc=rpc,\n        rpc_timeout=rpc_timeout,\n        raise_timeout=raise_timeout,\n        persist=self.persist,\n        reply_to=self.reply_to,\n        correlation_id=correlation_id,\n        priority=priority or self.priority,\n        **self.message_kwargs,\n        **message_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/rabbit/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    return {\n        self.name: Channel(\n            description=self.description,  # type: ignore[attr-defined]\n            publish=Operation(\n                bindings=OperationBinding(\n                    amqp=amqp.OperationBinding(\n                        cc=self.routing or None,\n                        deliveryMode=2 if self.persist else 1,\n                        mandatory=self.mandatory,\n                        replyTo=self.reply_to,\n                        priority=self.priority,\n                    ),\n                )\n                if _is_exchange(self.exchange)\n                else None,\n                message=Message(\n                    title=f\"{self.name}:Message\",\n                    payload=resolve_payloads(\n                        payloads,\n                        \"Publisher\",\n                        served_words=2 if self.title is None else 1,\n                    ),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                amqp=amqp.ChannelBinding(\n                    **{\n                        \"is\": \"routingKey\",  # type: ignore\n                        \"queue\": amqp.Queue(\n                            name=self.queue.name,\n                            durable=self.queue.durable,\n                            exclusive=self.queue.exclusive,\n                            autoDelete=self.queue.auto_delete,\n                            vhost=self.virtual_host,\n                        )\n                        if _is_exchange(self.exchange) and self.queue.name\n                        else None,\n                        \"exchange\": (\n                            amqp.Exchange(type=\"default\", vhost=self.virtual_host)\n                            if self.exchange is None\n                            else amqp.Exchange(\n                                type=self.exchange.type,  # type: ignore\n                                name=self.exchange.name,\n                                durable=self.exchange.durable,\n                                autoDelete=self.exchange.auto_delete,\n                                vhost=self.virtual_host,\n                            )\n                        ),\n                    }\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/","title":"RabbitBroker","text":"","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker","title":"faststream.rabbit.broker.RabbitBroker","text":"
RabbitBroker(\n    url: Union[\n        str, URL, None\n    ] = \"amqp://guest:guest@localhost:5672/\",\n    *,\n    host: str = None,\n    port: int = None,\n    login: str = None,\n    password: str = None,\n    virtualhost: str = None,\n    ssl_options: Optional[aio_pika.abc.SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    max_consumers: Optional[int] = None,\n    protocol: str = None,\n    protocol_version: Optional[str] = \"0.9.1\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: RabbitLoggingMixin, BrokerAsyncUsecase[IncomingMessage, RobustConnection]

A RabbitMQ broker for FastAPI applications.

This class extends the base BrokerAsyncUsecase and provides asynchronous support for RabbitMQ as a message broker.

PARAMETER DESCRIPTION url

The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".

TYPE: Union[str, URL, None] DEFAULT: 'amqp://guest:guest@localhost:5672/'

max_consumers

Maximum number of consumers to limit message consumption. Defaults to None.

TYPE: Optional[int] DEFAULT: None

protocol

The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".

TYPE: str DEFAULT: None

protocol_version

The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".

TYPE: Optional[str] DEFAULT: '0.9.1'

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Initialize the RabbitBroker.

PARAMETER DESCRIPTION url

The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".

TYPE: Union[str, URL, None] DEFAULT: 'amqp://guest:guest@localhost:5672/'

max_consumers

Maximum number of consumers to limit message consumption. Defaults to None.

TYPE: Optional[int] DEFAULT: None

protocol

The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".

TYPE: str DEFAULT: None

protocol_version

The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".

TYPE: Optional[str] DEFAULT: '0.9.1'

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/rabbit/broker.py
def __init__(\n    self,\n    url: Union[str, URL, None] = \"amqp://guest:guest@localhost:5672/\",\n    *,\n    # connection args\n    host: Optional[str] = None,\n    port: Optional[int] = None,\n    login: Optional[str] = None,\n    password: Optional[str] = None,\n    virtualhost: Optional[str] = None,\n    ssl_options: Optional[SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    # broker args\n    max_consumers: Optional[int] = None,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"0.9.1\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Initialize the RabbitBroker.\n\n    Args:\n        url (Union[str, URL, None], optional): The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".\n        max_consumers (Optional[int], optional): Maximum number of consumers to limit message consumption. Defaults to None.\n        protocol (str, optional): The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".\n        protocol_version (Optional[str], optional): The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".\n        **kwargs: Additional keyword arguments.\n    \"\"\"\n    security_args = parse_security(security)\n\n    if (ssl := kwargs.get(\"ssl\")) or kwargs.get(\"ssl_context\"):  # pragma: no cover\n        warnings.warn(\n            (\n                f\"\\nRabbitMQ {'`ssl`' if ssl else '`ssl_context`'} option was deprecated and will be removed in 0.4.0\"\n                \"\\nPlease, use `security` with `BaseSecurity` or `SASLPlaintext` instead\"\n            ),\n            DeprecationWarning,\n            stacklevel=2,\n        )\n\n    amqp_url = build_url(\n        url,\n        host=host,\n        port=port,\n        login=security_args.get(\"login\", login),\n        password=security_args.get(\"password\", password),\n        virtualhost=virtualhost,\n        ssl=security_args.get(\"ssl\", kwargs.pop(\"ssl\", False)),\n        ssl_options=ssl_options,\n        client_properties=client_properties,\n    )\n\n    super().__init__(\n        url=str(amqp_url),\n        protocol_version=protocol_version,\n        security=security,\n        ssl_context=security_args.get(\n            \"ssl_context\",\n            kwargs.pop(\"ssl_context\", None),\n        ),\n        **kwargs,\n    )\n\n    # respect ascynapi_url argument scheme\n    asyncapi_url = build_url(self.url)\n    self.protocol = protocol or asyncapi_url.scheme\n    self.virtual_host = asyncapi_url.path\n\n    self._max_consumers = max_consumers\n\n    self._channel = None\n    self.declarer = None\n    self._producer = None\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.declarer","title":"declarer instance-attribute","text":"
declarer: Optional[RabbitDeclarer] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[int, Handler]\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol or asyncapi_url.scheme\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.virtual_host","title":"virtual_host instance-attribute","text":"
virtual_host = asyncapi_url.path\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.connect","title":"connect async","text":"
connect(\n    *args: Any, **kwargs: Any\n) -> aio_pika.RobustConnection\n

Connect to the RabbitMQ server.

PARAMETER DESCRIPTION *args

Additional positional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION RobustConnection

aio_pika.RobustConnection: The RabbitMQ connection instance.

Source code in faststream/rabbit/broker.py
async def connect(self, *args: Any, **kwargs: Any) -> aio_pika.RobustConnection:\n    \"\"\"\n    Connect to the RabbitMQ server.\n\n    Args:\n        *args: Additional positional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        aio_pika.RobustConnection: The RabbitMQ connection instance.\n    \"\"\"\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.declare_exchange","title":"declare_exchange async","text":"
declare_exchange(\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange\n

Declare a RabbitMQ exchange.

PARAMETER DESCRIPTION exchange

The RabbitMQ exchange to declare.

TYPE: RabbitExchange

RETURNS DESCRIPTION RobustExchange

aio_pika.RobustExchange: The declared RabbitMQ exchange.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def declare_exchange(\n    self,\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange:\n    \"\"\"\n    Declare a RabbitMQ exchange.\n\n    Args:\n        exchange (RabbitExchange): The RabbitMQ exchange to declare.\n\n    Returns:\n        aio_pika.RobustExchange: The declared RabbitMQ exchange.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n    return await self.declarer.declare_exchange(exchange)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.declare_queue","title":"declare_queue async","text":"
declare_queue(queue: RabbitQueue) -> aio_pika.RobustQueue\n

Declare a RabbitMQ queue.

PARAMETER DESCRIPTION queue

The RabbitMQ queue to declare.

TYPE: RabbitQueue

RETURNS DESCRIPTION RobustQueue

aio_pika.RobustQueue: The declared RabbitMQ queue.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def declare_queue(\n    self,\n    queue: RabbitQueue,\n) -> aio_pika.RobustQueue:\n    \"\"\"\n    Declare a RabbitMQ queue.\n\n    Args:\n        queue (RabbitQueue): The RabbitMQ queue to declare.\n\n    Returns:\n        aio_pika.RobustQueue: The declared RabbitMQ queue.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n    return await self.declarer.declare_queue(queue)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, **kwargs: Any\n) -> Union[\n    aiormq.abc.ConfirmationFrameType, SendableMessage\n]\n

Publish a message to the RabbitMQ broker.

PARAMETER DESCRIPTION *args

Additional positional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Union[ConfirmationFrameType, SendableMessage]

Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The confirmation frame or the response message.

Source code in faststream/rabbit/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Union[aiormq.abc.ConfirmationFrameType, SendableMessage]:\n    \"\"\"\n    Publish a message to the RabbitMQ broker.\n\n    Args:\n        *args: Additional positional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The confirmation frame or the response message.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.publisher","title":"publisher","text":"
publisher(\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Publisher\n

Define a message publisher.

PARAMETER DESCRIPTION queue

The name of the RabbitMQ queue. Defaults to \"\".

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The name of the RabbitMQ exchange. Defaults to None.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key for messages. Defaults to \"\".

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory. Defaults to True.

TYPE: bool DEFAULT: True

immediate

Whether the message should be sent immediately. Defaults to False.

TYPE: bool DEFAULT: False

timeout

Timeout for message publishing. Defaults to None.

TYPE: TimeoutType DEFAULT: None

persist

Whether to persist messages. Defaults to False.

TYPE: bool DEFAULT: False

reply_to

The reply-to queue name. Defaults to None.

TYPE: Optional[str] DEFAULT: None

title

Title for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

description

Description for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional message properties and content.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Publisher

A message publisher instance.

TYPE: Publisher

Source code in faststream/rabbit/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Publisher:\n    \"\"\"\n    Define a message publisher.\n\n    Args:\n        queue (Union[RabbitQueue, str], optional): The name of the RabbitMQ queue. Defaults to \"\".\n        exchange (Union[RabbitExchange, str, None], optional): The name of the RabbitMQ exchange. Defaults to None.\n        routing_key (str, optional): The routing key for messages. Defaults to \"\".\n        mandatory (bool, optional): Whether the message is mandatory. Defaults to True.\n        immediate (bool, optional): Whether the message should be sent immediately. Defaults to False.\n        timeout (TimeoutType, optional): Timeout for message publishing. Defaults to None.\n        persist (bool, optional): Whether to persist messages. Defaults to False.\n        reply_to (Optional[str], optional): The reply-to queue name. Defaults to None.\n        title (Optional[str]): Title for AsyncAPI docs.\n        description (Optional[str]): Description for AsyncAPI docs.\n        **message_kwargs (Any): Additional message properties and content.\n\n    Returns:\n        Publisher: A message publisher instance.\n    \"\"\"\n    q, ex = RabbitQueue.validate(queue), RabbitExchange.validate(exchange)\n\n    publisher = Publisher(\n        title=title,\n        queue=q,\n        exchange=ex,\n        routing_key=routing_key,\n        mandatory=mandatory,\n        immediate=immediate,\n        timeout=timeout,\n        persist=persist,\n        reply_to=reply_to,\n        priority=priority,\n        message_kwargs=message_kwargs,\n        _description=description,\n        _schema=schema,\n        virtual_host=self.virtual_host,\n        include_in_schema=include_in_schema,\n    )\n\n    key = publisher._get_routing_hash()\n    publisher = self._publishers.get(key, publisher)\n    super().publisher(key, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.start","title":"start async","text":"
start() -> None\n

Start the RabbitMQ broker.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def start(self) -> None:\n    \"\"\"\n    Start the RabbitMQ broker.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, RabbitQueue(\"\"), RabbitExchange(\"\")),\n    )\n\n    await super().start()\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n\n    for publisher in self._publishers.values():\n        if publisher.exchange is not None:\n            await self.declare_exchange(publisher.exchange)\n\n    for handler in self.handlers.values():\n        c = self._get_log_context(None, handler.queue, handler.exchange)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self.declarer)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Filter[RabbitMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n

Decorator to define a message subscriber.

PARAMETER DESCRIPTION queue

The name of the RabbitMQ queue.

TYPE: Union[str, RabbitQueue]

exchange

The name of the RabbitMQ exchange. Defaults to None.

TYPE: Union[str, RabbitExchange, None] DEFAULT: None

consume_args

Additional arguments for message consumption.

TYPE: Optional[AnyDict] DEFAULT: None

no_ack

Whether not to ack/nack/reject messages.

TYPE: bool DEFAULT: False

title

Title for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

description

Description for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION Callable

A decorator function for defining message subscribers.

TYPE: Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn]]

Source code in faststream/rabbit/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[aio_pika.IncomingMessage, RabbitMessage]] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[aio_pika.IncomingMessage], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RabbitMessage] = default_filter,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"\n    Decorator to define a message subscriber.\n\n    Args:\n        queue (Union[str, RabbitQueue]): The name of the RabbitMQ queue.\n        exchange (Union[str, RabbitExchange, None], optional): The name of the RabbitMQ exchange. Defaults to None.\n        consume_args (Optional[AnyDict], optional): Additional arguments for message consumption.\n        no_ack (bool): Whether not to ack/nack/reject messages.\n        title (Optional[str]): Title for AsyncAPI docs.\n        description (Optional[str]): Description for AsyncAPI docs.\n\n    Returns:\n        Callable: A decorator function for defining message subscribers.\n    \"\"\"\n    super().subscriber()\n\n    r_queue = RabbitQueue.validate(queue)\n    r_exchange = RabbitExchange.validate(exchange)\n\n    self._setup_log_context(r_queue, r_exchange)\n\n    key = get_routing_hash(r_queue, r_exchange)\n    handler = self.handlers.get(\n        key,\n        Handler(\n            log_context_builder=partial(\n                self._get_log_context, queue=r_queue, exchange=r_exchange\n            ),\n            queue=r_queue,\n            exchange=r_exchange,\n            consume_args=consume_args,\n            description=description,\n            title=title,\n            virtual_host=self.virtual_host,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n        ),\n    )\n\n    self.handlers[key] = handler\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[\n        aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn\n    ]:\n        \"\"\"Wraps a consumer function with additional functionality.\n\n        Args:\n            func: The consumer function to be wrapped.\n\n        Returns:\n            The wrapped consumer function.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            _process_kwargs={\n                \"reply_config\": reply_config,\n            },\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/rabbit/fastapi/Context/#faststream.broker.fastapi.context.Context","title":"faststream.broker.fastapi.context.Context","text":"
Context(name: str) -> Any\n
Source code in faststream/broker/fastapi/context.py
def Context(name: str) -> Any:\n    return params.Depends(\n        lambda: context.resolve(name),\n        use_cache=True,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/","title":"RabbitRouter","text":"","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter","title":"faststream.rabbit.fastapi.RabbitRouter","text":"
RabbitRouter(\n    url: Union[\n        str, URL, None\n    ] = \"amqp://guest:guest@localhost:5672/\",\n    *,\n    host: str = \"localhost\",\n    port: int = 5672,\n    login: str = \"guest\",\n    password: str = \"guest\",\n    virtualhost: str = \"/\",\n    ssl_options: Optional[aio_pika.abc.SSLOptions] = None,\n    timeout: aio_pika.abc.TimeoutType = None,\n    client_properties: Optional[FieldTable] = None,\n    security: Optional[BaseSecurity] = None,\n    max_consumers: Optional[int] = None,\n    graceful_timeout: Optional[float] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    asyncapi_url: Optional[str] = None,\n    protocol: str = \"amqp\",\n    protocol_version: Optional[str] = \"0.9.1\",\n    description: Optional[str] = None,\n    asyncapi_tags: Optional[Sequence[asyncapi.Tag]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    setup_state: bool = True,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n)\n

Bases: StreamRouter[IncomingMessage]

A class to represent a RabbitMQ router for incoming messages.

METHOD DESCRIPTION _setup_log_context

sets up the log context for the main broker and the including broker

Source code in faststream/rabbit/fastapi.py
main_broker._setup_log_context(h.queue, h.exchange)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.broker","title":"broker instance-attribute","text":"
broker: RabbitBroker\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.broker_class","title":"broker_class class-attribute instance-attribute","text":"
broker_class: Type[RabbitBroker] = RB\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    queue: Union[str, RabbitQueue],\n    *,\n    endpoint: Callable[..., T_HandlerReturn],\n    exchange: Union[str, RabbitExchange, None] = None,\n    consume_args: Optional[AnyDict] = None,\n    dependencies: Sequence[params.Depends] = (),\n    filter: Filter[RabbitMessage] = default_filter,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    retry: Union[bool, int] = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    **__service_kwargs: Any\n) -> Callable[\n    [IncomingMessage, bool], Awaitable[T_HandlerReturn]\n]\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.publisher","title":"publisher","text":"
publisher(\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    headers: Optional[aio_pika.abc.HeadersType] = None,\n    content_type: Optional[str] = None,\n    content_encoding: Optional[str] = None,\n    priority: Optional[int] = None,\n    correlation_id: Optional[str] = None,\n    expiration: Optional[aio_pika.abc.DateType] = None,\n    message_id: Optional[str] = None,\n    timestamp: Optional[aio_pika.abc.DateType] = None,\n    type: Optional[str] = None,\n    user_id: Optional[str] = None,\n    app_id: Optional[str] = None\n) -> Publisher\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    dependencies: Sequence[params.Depends] = (),\n    filter: Filter[RabbitMessage] = default_filter,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    retry: Union[bool, int] = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/","title":"LogicHandler","text":"","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler","title":"faststream.rabbit.handler.LogicHandler","text":"
LogicHandler(\n    queue: RabbitQueue,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    exchange: Optional[RabbitExchange] = None,\n    consume_args: Optional[AnyDict] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    virtual_host: str = \"/\",\n)\n

Bases: AsyncHandler[IncomingMessage], BaseRMQInformation

A class to handle logic for RabbitMQ message consumption.

METHOD DESCRIPTION __init__

Initializes the LogicHandler object

add_call

Adds a call to be handled by the LogicHandler

start

Starts consuming messages from the queue

close

Closes the consumer and cancels message consumption

Initialize a RabbitMQ consumer.

PARAMETER DESCRIPTION queue

RabbitQueue object representing the queue to consume from

TYPE: RabbitQueue

exchange

RabbitExchange object representing the exchange to bind the queue to (optional)

TYPE: Optional[RabbitExchange] DEFAULT: None

consume_args

Additional arguments for consuming from the queue (optional)

TYPE: Optional[AnyDict] DEFAULT: None

description

Description of the consumer (optional)

TYPE: Optional[str] DEFAULT: None

title

Title of the consumer (optional)

TYPE: Optional[str] DEFAULT: None

Source code in faststream/rabbit/handler.py
def __init__(\n    self,\n    queue: RabbitQueue,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # RMQ information\n    exchange: Optional[RabbitExchange] = None,\n    consume_args: Optional[AnyDict] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    virtual_host: str = \"/\",\n) -> None:\n    \"\"\"Initialize a RabbitMQ consumer.\n\n    Args:\n        queue: RabbitQueue object representing the queue to consume from\n        exchange: RabbitExchange object representing the exchange to bind the queue to (optional)\n        consume_args: Additional arguments for consuming from the queue (optional)\n        description: Description of the consumer (optional)\n        title: Title of the consumer (optional)\n\n    \"\"\"\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.queue = queue\n    self.exchange = exchange\n    self.virtual_host = virtual_host\n    self.consume_args = consume_args or {}\n\n    self._consumer_tag = None\n    self._queue_obj = None\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.consume_args","title":"consume_args instance-attribute","text":"
consume_args: AnyDict = consume_args or {}\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.exchange","title":"exchange instance-attribute","text":"
exchange: Optional[RabbitExchange] = exchange\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.queue","title":"queue instance-attribute","text":"
queue: RabbitQueue = queue\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.virtual_host","title":"virtual_host instance-attribute","text":"
virtual_host = virtual_host\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ],\n    decoder: Optional[CustomDecoder[RabbitMessage]],\n    filter: Filter[RabbitMessage],\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ]\n) -> None\n

Add a call to the handler.

PARAMETER DESCRIPTION handler

The handler for the call.

TYPE: HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn]

dependant

The dependant for the call.

TYPE: CallModel[P_HandlerParams, T_HandlerReturn]

parser

Optional custom parser for the call.

TYPE: Optional[CustomParser[IncomingMessage, RabbitMessage]]

decoder

Optional custom decoder for the call.

TYPE: Optional[CustomDecoder[RabbitMessage]]

filter

The filter for the call.

TYPE: Filter[RabbitMessage]

middlewares

Optional sequence of middlewares for the call.

TYPE: Optional[Sequence[Callable[[IncomingMessage], BaseMiddleware]]]

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[\n        aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[aio_pika.IncomingMessage, RabbitMessage]],\n    decoder: Optional[CustomDecoder[RabbitMessage]],\n    filter: Filter[RabbitMessage],\n    middlewares: Optional[\n        Sequence[Callable[[aio_pika.IncomingMessage], BaseMiddleware]]\n    ],\n) -> None:\n    \"\"\"Add a call to the handler.\n\n    Args:\n        handler: The handler for the call.\n        dependant: The dependant for the call.\n        parser: Optional custom parser for the call.\n        decoder: Optional custom decoder for the call.\n        filter: The filter for the call.\n        middlewares: Optional sequence of middlewares for the call.\n\n    Returns:\n        None\n\n    \"\"\"\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, AioPikaParser.parse_message),\n        decoder=resolve_custom_func(decoder, AioPikaParser.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/rabbit/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self._queue_obj is not None:\n        if self._consumer_tag is not None:  # pragma: no branch\n            await self._queue_obj.cancel(self._consumer_tag)\n            self._consumer_tag = None\n        self._queue_obj = None\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.start","title":"start async","text":"
start(declarer: RabbitDeclarer) -> None\n

Starts the consumer for the RabbitMQ queue.

PARAMETER DESCRIPTION declarer

RabbitDeclarer object used to declare the queue and exchange

TYPE: RabbitDeclarer

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/handler.py
@override\nasync def start(self, declarer: RabbitDeclarer) -> None:  # type: ignore[override]\n    \"\"\"Starts the consumer for the RabbitMQ queue.\n\n    Args:\n        declarer: RabbitDeclarer object used to declare the queue and exchange\n\n    Returns:\n        None\n\n    \"\"\"\n    self._queue_obj = queue = await declarer.declare_queue(self.queue)\n\n    if self.exchange is not None:\n        exchange = await declarer.declare_exchange(self.exchange)\n        await queue.bind(\n            exchange,\n            routing_key=self.queue.routing,\n            arguments=self.queue.bind_arguments,\n        )\n\n    self._consumer_tag = await queue.consume(\n        # NOTE: aio-pika expects AbstractIncomingMessage, not IncomingMessage\n        self.consume,  # type: ignore[arg-type]\n        arguments=self.consume_args,\n    )\n\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/","title":"RabbitDeclarer","text":"","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer","title":"faststream.rabbit.helpers.RabbitDeclarer","text":"
RabbitDeclarer(channel: aio_pika.RobustChannel)\n

Bases: Singleton

A class to declare RabbitMQ queues and exchanges.

METHOD DESCRIPTION declare_queue

RabbitQueue) -> aio_pika.RobustQueue Declares a queue and returns the declared queue object.

declare_exchange

RabbitExchange) -> aio_pika.RobustExchange Declares an exchange and returns the declared exchange object.

Initialize the class.

PARAMETER DESCRIPTION channel

Aio_pika RobustChannel object

TYPE: RobustChannel

Source code in faststream/rabbit/helpers.py
def __init__(self, channel: aio_pika.RobustChannel) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        channel: Aio_pika RobustChannel object\n\n    Attributes:\n        channel: Aio_pika RobustChannel object\n        queues: A dictionary to store queues\n        exchanges: A dictionary to store exchanges\n\n    \"\"\"\n    self.channel = channel\n    self.queues = {}\n    self.exchanges = {}\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer.channel","title":"channel instance-attribute","text":"
channel: aio_pika.RobustChannel = channel\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer.exchanges","title":"exchanges instance-attribute","text":"
exchanges: Dict[\n    Union[RabbitExchange, str], aio_pika.RobustExchange\n] = {}\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer.queues","title":"queues instance-attribute","text":"
queues: Dict[\n    Union[RabbitQueue, str], aio_pika.RobustQueue\n] = {}\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer.declare_exchange","title":"declare_exchange async","text":"
declare_exchange(\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange\n

Declare an exchange.

PARAMETER DESCRIPTION exchange

RabbitExchange object representing the exchange to be declared.

TYPE: RabbitExchange

RETURNS DESCRIPTION RobustExchange

aio_pika.RobustExchange: The declared exchange.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/rabbit/helpers.py
async def declare_exchange(\n    self,\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange:\n    \"\"\"Declare an exchange.\n\n    Args:\n        exchange: RabbitExchange object representing the exchange to be declared.\n\n    Returns:\n        aio_pika.RobustExchange: The declared exchange.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    exch = self.exchanges.get(exchange)\n\n    if exch is None:\n        exch = cast(\n            aio_pika.RobustExchange,\n            await self.channel.declare_exchange(\n                **model_to_dict(\n                    exchange,\n                    exclude={\n                        \"routing_key\",\n                        \"bind_arguments\",\n                        \"bind_to\",\n                    },\n                )\n            ),\n        )\n        self.exchanges[exchange] = exch\n\n    if exchange.bind_to is not None:\n        parent = await self.declare_exchange(exchange.bind_to)\n        await exch.bind(\n            exchange=parent,\n            routing_key=exchange.routing_key,\n            arguments=exchange.arguments,\n        )\n\n    return exch\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer.declare_queue","title":"declare_queue async","text":"
declare_queue(queue: RabbitQueue) -> aio_pika.RobustQueue\n

Declare a queue.

PARAMETER DESCRIPTION queue

RabbitQueue object representing the queue to be declared.

TYPE: RabbitQueue

RETURNS DESCRIPTION RobustQueue

aio_pika.RobustQueue: The declared queue.

Source code in faststream/rabbit/helpers.py
async def declare_queue(\n    self,\n    queue: RabbitQueue,\n) -> aio_pika.RobustQueue:\n    \"\"\"Declare a queue.\n\n    Args:\n        queue: RabbitQueue object representing the queue to be declared.\n\n    Returns:\n        aio_pika.RobustQueue: The declared queue.\n\n    \"\"\"\n    q = self.queues.get(queue)\n    if q is None:\n        q = cast(\n            aio_pika.RobustQueue,\n            await self.channel.declare_queue(\n                **model_to_dict(\n                    queue,\n                    exclude={\n                        \"routing_key\",\n                        \"path_regex\",\n                        \"bind_arguments\",\n                    },\n                )\n            ),\n        )\n        self.queues[queue] = q\n    return q\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/","title":"RabbitMessage","text":"","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage","title":"faststream.rabbit.message.RabbitMessage","text":"

Bases: StreamMessage[IncomingMessage]

A message class for working with RabbitMQ messages.

This class extends StreamMessage to provide additional functionality for acknowledging, rejecting, or nack-ing RabbitMQ messages.

METHOD DESCRIPTION ack

Acknowledge the RabbitMQ message.

nack

Negative Acknowledgment of the RabbitMQ message.

reject

Reject the RabbitMQ message.

","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.ack","title":"ack async","text":"
ack(**kwargs: Any) -> None\n

Acknowledge the RabbitMQ message.

Acknowledgment indicates that the message has been successfully processed.

PARAMETER DESCRIPTION **kwargs

Additional keyword arguments (not used).

TYPE: Any DEFAULT: {}

Source code in faststream/rabbit/message.py
async def ack(self, **kwargs: Any) -> None:\n    \"\"\"\n    Acknowledge the RabbitMQ message.\n\n    Acknowledgment indicates that the message has been successfully processed.\n\n    Args:\n        **kwargs (Any): Additional keyword arguments (not used).\n\n    \"\"\"\n    pika_message = self.raw_message\n    await super().ack()\n    if (\n        pika_message._IncomingMessage__processed  # type: ignore[attr-defined]\n        or pika_message._IncomingMessage__no_ack  # type: ignore[attr-defined]\n    ):\n        return\n    await pika_message.ack()\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.nack","title":"nack async","text":"
nack(**kwargs: Any) -> None\n

Negative Acknowledgment of the RabbitMQ message.

Nack-ing a message indicates that the message processing has failed and should be requeued.

PARAMETER DESCRIPTION **kwargs

Additional keyword arguments (not used).

TYPE: Any DEFAULT: {}

Source code in faststream/rabbit/message.py
async def nack(self, **kwargs: Any) -> None:\n    \"\"\"\n    Negative Acknowledgment of the RabbitMQ message.\n\n    Nack-ing a message indicates that the message processing has failed and should be requeued.\n\n    Args:\n        **kwargs (Any): Additional keyword arguments (not used).\n\n    \"\"\"\n    pika_message = self.raw_message\n    await super().nack()\n    if (\n        pika_message._IncomingMessage__processed  # type: ignore[attr-defined]\n        or pika_message._IncomingMessage__no_ack  # type: ignore[attr-defined]\n    ):\n        return\n    await pika_message.nack()\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.reject","title":"reject async","text":"
reject(**kwargs: Any) -> None\n

Reject the RabbitMQ message.

Rejecting a message indicates that the message processing has failed, and it should not be requeued.

PARAMETER DESCRIPTION **kwargs

Additional keyword arguments (not used).

TYPE: Any DEFAULT: {}

Source code in faststream/rabbit/message.py
async def reject(self, **kwargs: Any) -> None:\n    \"\"\"\n    Reject the RabbitMQ message.\n\n    Rejecting a message indicates that the message processing has failed, and it should not be requeued.\n\n    Args:\n        **kwargs (Any): Additional keyword arguments (not used).\n\n    \"\"\"\n    pika_message = self.raw_message\n    await super().reject()\n    if (\n        pika_message._IncomingMessage__processed  # type: ignore[attr-defined]\n        or pika_message._IncomingMessage__no_ack  # type: ignore[attr-defined]\n    ):\n        return\n    await pika_message.reject()\n
","boost":0.5},{"location":"api/faststream/rabbit/parser/AioPikaParser/","title":"AioPikaParser","text":"","boost":0.5},{"location":"api/faststream/rabbit/parser/AioPikaParser/#faststream.rabbit.parser.AioPikaParser","title":"faststream.rabbit.parser.AioPikaParser","text":"

A class for parsing, encoding, and decoding messages using aio-pika.

METHOD DESCRIPTION parse_message

aio_pika.IncomingMessage) -> StreamMessage[aio_pika.IncomingMessage]: Parses an incoming message and returns a StreamMessage object.

decode_message

StreamMessage[aio_pika.IncomingMessage]) -> DecodedMessage: Decodes a StreamMessage object and returns a DecodedMessage object.

encode_message

AioPikaSendableMessage, persist: bool = False, callback_queue: Optional[aio_pika.abc.AbstractRobustQueue] = None, reply_to: Optional[str] = None, **message_kwargs: Any) -> aio_pika.Message: Encodes a message into an aio_pika.Message object.

","boost":0.5},{"location":"api/faststream/rabbit/parser/AioPikaParser/#faststream.rabbit.parser.AioPikaParser.decode_message","title":"decode_message async staticmethod","text":"
decode_message(\n    msg: StreamMessage[aio_pika.IncomingMessage],\n) -> DecodedMessage\n

Decode a message.

PARAMETER DESCRIPTION msg

The message to decode.

TYPE: StreamMessage[IncomingMessage]

RETURNS DESCRIPTION DecodedMessage

The decoded message.

Source code in faststream/rabbit/parser.py
@staticmethod\nasync def decode_message(\n    msg: StreamMessage[aio_pika.IncomingMessage],\n) -> DecodedMessage:\n    \"\"\"Decode a message.\n\n    Args:\n        msg: The message to decode.\n\n    Returns:\n        The decoded message.\n\n    \"\"\"\n    return decode_message(msg)\n
","boost":0.5},{"location":"api/faststream/rabbit/parser/AioPikaParser/#faststream.rabbit.parser.AioPikaParser.encode_message","title":"encode_message staticmethod","text":"
encode_message(\n    message: AioPikaSendableMessage,\n    persist: bool = False,\n    callback_queue: Optional[\n        aio_pika.abc.AbstractRobustQueue\n    ] = None,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any\n) -> aio_pika.Message\n

Encodes a message for sending using AioPika.

PARAMETER DESCRIPTION message

The message to encode.

TYPE: AioPikaSendableMessage

persist

Whether to persist the message. Defaults to False.

TYPE: bool DEFAULT: False

callback_queue

The callback queue to use for replies. Defaults to None.

TYPE: AbstractRobustQueue DEFAULT: None

reply_to

The reply-to queue to use for replies. Defaults to None.

TYPE: str DEFAULT: None

**message_kwargs

Additional keyword arguments to include in the encoded message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Message

aio_pika.Message: The encoded message.

RAISES DESCRIPTION NotImplementedError

If the message is not an instance of aio_pika.Message.

Source code in faststream/rabbit/parser.py
@staticmethod\ndef encode_message(\n    message: AioPikaSendableMessage,\n    persist: bool = False,\n    callback_queue: Optional[aio_pika.abc.AbstractRobustQueue] = None,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any,\n) -> aio_pika.Message:\n    \"\"\"Encodes a message for sending using AioPika.\n\n    Args:\n        message (AioPikaSendableMessage): The message to encode.\n        persist (bool, optional): Whether to persist the message. Defaults to False.\n        callback_queue (aio_pika.abc.AbstractRobustQueue, optional): The callback queue to use for replies. Defaults to None.\n        reply_to (str, optional): The reply-to queue to use for replies. Defaults to None.\n        **message_kwargs (Any): Additional keyword arguments to include in the encoded message.\n\n    Returns:\n        aio_pika.Message: The encoded message.\n\n    Raises:\n        NotImplementedError: If the message is not an instance of aio_pika.Message.\n\n    \"\"\"\n    if isinstance(message, aio_pika.Message):\n        return message\n\n    else:\n        message, content_type = encode_message(message)\n\n        delivery_mode = (\n            DeliveryMode.PERSISTENT if persist else DeliveryMode.NOT_PERSISTENT\n        )\n\n        return aio_pika.Message(\n            message,\n            **{\n                \"delivery_mode\": delivery_mode,\n                \"content_type\": content_type,\n                \"reply_to\": callback_queue or reply_to,\n                \"correlation_id\": str(uuid4()),\n                **message_kwargs,\n            },\n        )\n
","boost":0.5},{"location":"api/faststream/rabbit/parser/AioPikaParser/#faststream.rabbit.parser.AioPikaParser.parse_message","title":"parse_message async staticmethod","text":"
parse_message(\n    message: aio_pika.IncomingMessage,\n) -> StreamMessage[aio_pika.IncomingMessage]\n

Parses an incoming message and returns a RabbitMessage object.

PARAMETER DESCRIPTION message

The incoming message to parse.

TYPE: IncomingMessage

RETURNS DESCRIPTION StreamMessage[IncomingMessage]

A StreamMessage object representing the parsed message.

Source code in faststream/rabbit/parser.py
@staticmethod\nasync def parse_message(\n    message: aio_pika.IncomingMessage,\n) -> StreamMessage[aio_pika.IncomingMessage]:\n    \"\"\"Parses an incoming message and returns a RabbitMessage object.\n\n    Args:\n        message: The incoming message to parse.\n\n    Returns:\n        A StreamMessage object representing the parsed message.\n\n    \"\"\"\n    handler = context.get_local(\"handler_\")\n    path: AnyDict = {}\n    path_re: Optional[Pattern[str]]\n    if (\n        handler\n        and (path_re := handler.queue.path_regex) is not None\n        and (match := path_re.match(message.routing_key or \"\")) is not None\n    ):\n        path = match.groupdict()\n\n    return RabbitMessage(\n        body=message.body,\n        headers=message.headers,\n        reply_to=message.reply_to or \"\",\n        content_type=message.content_type,\n        message_id=message.message_id or str(uuid4()),\n        correlation_id=message.correlation_id or str(uuid4()),\n        path=path,\n        raw_message=message,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/producer/AioPikaFastProducer/","title":"AioPikaFastProducer","text":"","boost":0.5},{"location":"api/faststream/rabbit/producer/AioPikaFastProducer/#faststream.rabbit.producer.AioPikaFastProducer","title":"faststream.rabbit.producer.AioPikaFastProducer","text":"
AioPikaFastProducer(\n    channel: aio_pika.RobustChannel,\n    declarer: RabbitDeclarer,\n    parser: Optional[\n        AsyncCustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ],\n    decoder: Optional[AsyncCustomDecoder[RabbitMessage]],\n)\n

A class for fast producing messages using aio-pika.

METHOD DESCRIPTION publish

Publishes a message to a queue or exchange.

_publish

Publishes a message to an exchange.

Note: This docstring is incomplete as it is difficult to understand the purpose and functionality of the class and its methods without more context.

Initialize a class instance.

PARAMETER DESCRIPTION channel

The aio_pika.RobustChannel object.

TYPE: RobustChannel

declarer

The RabbitDeclarer object.

TYPE: RabbitDeclarer

parser

An optional AsyncCustomParser object for parsing incoming messages.

TYPE: Optional[AsyncCustomParser[IncomingMessage, RabbitMessage]]

decoder

An optional AsyncCustomDecoder object for decoding incoming messages.

TYPE: Optional[AsyncCustomDecoder[RabbitMessage]]

Source code in faststream/rabbit/producer.py
def __init__(\n    self,\n    channel: aio_pika.RobustChannel,\n    declarer: RabbitDeclarer,\n    parser: Optional[AsyncCustomParser[aio_pika.IncomingMessage, RabbitMessage]],\n    decoder: Optional[AsyncCustomDecoder[RabbitMessage]],\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        channel: The aio_pika.RobustChannel object.\n        declarer: The RabbitDeclarer object.\n        parser: An optional AsyncCustomParser object for parsing incoming messages.\n        decoder: An optional AsyncCustomDecoder object for decoding incoming messages.\n\n    \"\"\"\n    self._channel = channel\n    self.declarer = declarer\n    self._parser = resolve_custom_func(parser, AioPikaParser.parse_message)\n    self._decoder = resolve_custom_func(decoder, AioPikaParser.decode_message)\n    self._rpc_lock = anyio.Lock()\n
","boost":0.5},{"location":"api/faststream/rabbit/producer/AioPikaFastProducer/#faststream.rabbit.producer.AioPikaFastProducer.declarer","title":"declarer instance-attribute","text":"
declarer: RabbitDeclarer = declarer\n
","boost":0.5},{"location":"api/faststream/rabbit/producer/AioPikaFastProducer/#faststream.rabbit.producer.AioPikaFastProducer.publish","title":"publish async","text":"
publish(\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any\n) -> Union[\n    aiormq.abc.ConfirmationFrameType, SendableMessage\n]\n

Publish a message to a RabbitMQ queue.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: AioPikaSendableMessage DEFAULT: ''

queue

The queue to publish the message to.

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The exchange to publish the message to.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key for the message.

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory.

TYPE: bool DEFAULT: True

immediate

Whether the message should be delivered immediately.

TYPE: bool DEFAULT: False

timeout

The timeout for the operation.

TYPE: TimeoutType DEFAULT: None

rpc

Whether the message is for RPC.

TYPE: bool DEFAULT: False

rpc_timeout

The timeout for RPC.

TYPE: Optional[float] DEFAULT: 30.0

raise_timeout

Whether to raise an exception on timeout.

TYPE: bool DEFAULT: False

persist

Whether the message should be persisted.

TYPE: bool DEFAULT: False

reply_to

The reply-to queue for RPC.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional keyword arguments for the message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Union[ConfirmationFrameType, SendableMessage]

Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The result of the publish operation.

RAISES DESCRIPTION WRONG_PUBLISH_ARGS

If reply_to is not None when rpc is True.

Source code in faststream/rabbit/producer.py
async def publish(\n    self,\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any,\n) -> Union[aiormq.abc.ConfirmationFrameType, SendableMessage]:\n    \"\"\"Publish a message to a RabbitMQ queue.\n\n    Args:\n        message (AioPikaSendableMessage): The message to be published.\n        queue (Union[RabbitQueue, str]): The queue to publish the message to.\n        exchange (Union[RabbitExchange, str, None]): The exchange to publish the message to.\n        routing_key (str): The routing key for the message.\n        mandatory (bool): Whether the message is mandatory.\n        immediate (bool): Whether the message should be delivered immediately.\n        timeout (TimeoutType): The timeout for the operation.\n        rpc (bool): Whether the message is for RPC.\n        rpc_timeout (Optional[float]): The timeout for RPC.\n        raise_timeout (bool): Whether to raise an exception on timeout.\n        persist (bool): Whether the message should be persisted.\n        reply_to (Optional[str]): The reply-to queue for RPC.\n        **message_kwargs (Any): Additional keyword arguments for the message.\n\n    Returns:\n        Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The result of the publish operation.\n\n    Raises:\n        WRONG_PUBLISH_ARGS: If reply_to is not None when rpc is True.\n\n    \"\"\"\n    p_queue = RabbitQueue.validate(queue)\n\n    context: AsyncContextManager[\n        Optional[MemoryObjectReceiveStream[aio_pika.IncomingMessage]]\n    ]\n    if rpc is True:\n        if reply_to is not None:\n            raise WRONG_PUBLISH_ARGS\n        else:\n            context = _RPCCallback(\n                self._rpc_lock,\n                self.declarer.queues[RABBIT_REPLY],\n            )\n    else:\n        context = fake_context()\n\n    async with context as response_queue:\n        r = await self._publish(\n            message=message,\n            exchange=exchange,\n            routing_key=routing_key or p_queue.routing or \"\",\n            mandatory=mandatory,\n            immediate=immediate,\n            timeout=timeout,\n            persist=persist,\n            reply_to=RABBIT_REPLY if response_queue else reply_to,\n            **message_kwargs,\n        )\n\n        if response_queue is None:\n            return r\n\n        else:\n            msg: Optional[aio_pika.IncomingMessage] = None\n            with timeout_scope(rpc_timeout, raise_timeout):\n                msg = await response_queue.receive()\n\n            if msg:  # pragma: no branch\n                return await self._decoder(await self._parser(msg))\n\n    return None\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/","title":"LogicPublisher","text":"","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher","title":"faststream.rabbit.publisher.LogicPublisher dataclass","text":"

Bases: ABCPublisher[IncomingMessage]

A class to publish messages for logic processing.

METHOD DESCRIPTION publish

Publishes a message for logic processing.

","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.exchange","title":"exchange class-attribute instance-attribute","text":"
exchange: Optional[RabbitExchange] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.immediate","title":"immediate class-attribute instance-attribute","text":"
immediate: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.message_kwargs","title":"message_kwargs class-attribute instance-attribute","text":"
message_kwargs: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.persist","title":"persist class-attribute instance-attribute","text":"
persist: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.priority","title":"priority class-attribute instance-attribute","text":"
priority: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.queue","title":"queue class-attribute instance-attribute","text":"
queue: RabbitQueue = field(default=RabbitQueue(''))\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.routing","title":"routing property","text":"
routing: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.virtual_host","title":"virtual_host class-attribute instance-attribute","text":"
virtual_host: str = '/'\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/rabbit/publisher.py
Methods:\n    publish : Publishes a message for logic processing.\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.publish","title":"publish async","text":"
publish(\n    message: AioPikaSendableMessage = \"\",\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    correlation_id: Optional[str] = None,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Union[\n    aiormq.abc.ConfirmationFrameType, SendableMessage\n]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: AioPikaSendableMessage DEFAULT: ''

rpc

Whether the message is for RPC (Remote Procedure Call).

TYPE: bool DEFAULT: False

rpc_timeout

Timeout for RPC.

TYPE: Optional[float] DEFAULT: 30.0

raise_timeout

Whether to raise an exception if timeout occurs.

TYPE: bool DEFAULT: False

correlation_id

Correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional keyword arguments for the message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Union[ConfirmationFrameType, SendableMessage]

ConfirmationFrameType or SendableMessage: The result of the publish operation.

RAISES DESCRIPTION AssertionError

If _producer is not set up.

Source code in faststream/rabbit/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: AioPikaSendableMessage = \"\",\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    correlation_id: Optional[str] = None,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Union[aiormq.abc.ConfirmationFrameType, SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        rpc: Whether the message is for RPC (Remote Procedure Call).\n        rpc_timeout: Timeout for RPC.\n        raise_timeout: Whether to raise an exception if timeout occurs.\n        correlation_id: Correlation ID for the message.\n        **message_kwargs: Additional keyword arguments for the message.\n\n    Returns:\n        ConfirmationFrameType or SendableMessage: The result of the publish operation.\n\n    Raises:\n        AssertionError: If `_producer` is not set up.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(\n        message=message,\n        exchange=self.exchange,\n        routing_key=self.routing,\n        mandatory=self.mandatory,\n        immediate=self.immediate,\n        timeout=self.timeout,\n        rpc=rpc,\n        rpc_timeout=rpc_timeout,\n        raise_timeout=raise_timeout,\n        persist=self.persist,\n        reply_to=self.reply_to,\n        correlation_id=correlation_id,\n        priority=priority or self.priority,\n        **self.message_kwargs,\n        **message_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/","title":"RabbitRouter","text":"","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter","title":"faststream.rabbit.router.RabbitRouter","text":"
RabbitRouter(\n    prefix: str = \"\",\n    handlers: Sequence[RabbitRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: RabbitRouter

A class representing a RabbitMQ router for publishing messages.

METHOD DESCRIPTION _get_publisher_key

Returns the key for a given Publisher object

_update_publisher_prefix

Updates the prefix of a given Publisher object

publisher

Publishes a message to RabbitMQ

Source code in faststream/rabbit/router.py
_publishers: Dict[int, Publisher]\n\n@staticmethod\ndef _get_publisher_key(publisher: Publisher) -> int:\n    \"\"\"Get the publisher key.\n\n    Args:\n        publisher: The publisher object.\n\n    Returns:\n        The publisher key as an integer.\n\n    \"\"\"\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.publisher","title":"publisher","text":"
publisher(\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Publisher\n

Publishes a message to a RabbitMQ queue or exchange.

PARAMETER DESCRIPTION queue

The RabbitMQ queue to publish the message to. Can be either a RabbitQueue object or a string representing the queue name.

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The RabbitMQ exchange to publish the message to. Can be either a RabbitExchange object, a string representing the exchange name, or None.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key to use when publishing the message.

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory or not.

TYPE: bool DEFAULT: True

immediate

Whether the message should be delivered immediately or not.

TYPE: bool DEFAULT: False

timeout

The timeout for the publish operation.

TYPE: TimeoutType DEFAULT: None

persist

Whether the message should be persisted or not.

TYPE: bool DEFAULT: False

reply_to

The reply-to address for the message.

TYPE: Optional[str] DEFAULT: None

title

The title of the message (AsyncAPI information).

TYPE: Optional[str] DEFAULT: None

description

The description of the message (AsyncAPI information).

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional keyword arguments to include in the message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Publisher

The Publisher object used to publish the message.

Source code in faststream/rabbit/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Publisher:\n    \"\"\"Publishes a message to a RabbitMQ queue or exchange.\n\n    Args:\n        queue: The RabbitMQ queue to publish the message to. Can be either a RabbitQueue object or a string representing the queue name.\n        exchange: The RabbitMQ exchange to publish the message to. Can be either a RabbitExchange object, a string representing the exchange name, or None.\n        routing_key: The routing key to use when publishing the message.\n        mandatory: Whether the message is mandatory or not.\n        immediate: Whether the message should be delivered immediately or not.\n        timeout: The timeout for the publish operation.\n        persist: Whether the message should be persisted or not.\n        reply_to: The reply-to address for the message.\n        title: The title of the message (AsyncAPI information).\n        description: The description of the message (AsyncAPI information).\n        **message_kwargs: Additional keyword arguments to include in the message.\n\n    Returns:\n        The Publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            queue=RabbitQueue.validate(queue),\n            exchange=RabbitExchange.validate(exchange),\n            routing_key=routing_key,\n            mandatory=mandatory,\n            immediate=immediate,\n            timeout=timeout,\n            persist=persist,\n            reply_to=reply_to,\n            priority=priority,\n            message_kwargs=message_kwargs,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[key] = self._publishers.get(key, new_publisher)\n    return publisher\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    dependencies: Sequence[Depends] = (),\n    filter: Filter[RabbitMessage] = default_filter,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    retry: Union[bool, int] = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n
Source code in faststream/rabbit/router.py
    Returns:\n        Publisher: The updated publisher object.\n\n    Note:\n        This function is intended to be used as a decorator.\n\n    \"\"\"\n    publisher.queue = model_copy(\n        publisher.queue, update={\"name\": prefix + publisher.queue.name}\n    )\n    return publisher\n\n@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n
","boost":0.5},{"location":"api/faststream/rabbit/security/parse_security/","title":"parse_security","text":"","boost":0.5},{"location":"api/faststream/rabbit/security/parse_security/#faststream.rabbit.security.parse_security","title":"faststream.rabbit.security.parse_security","text":"
parse_security(security: Optional[BaseSecurity]) -> AnyDict\n
Source code in faststream/rabbit/security.py
def parse_security(security: Optional[BaseSecurity]) -> AnyDict:\n    if security is None:\n        return {}\n    elif isinstance(security, SASLPlaintext):\n        return _parse_sasl_plaintext(security)\n    elif isinstance(security, BaseSecurity):\n        return _parse_base_security(security)\n    else:\n        raise NotImplementedError(f\"RabbitBroker does not support {type(security)}\")\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/","title":"ExchangeType","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType","title":"faststream.rabbit.shared.constants.ExchangeType","text":"

Bases: str, Enum

A class to represent the exchange type.

","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.DIRECT","title":"DIRECT class-attribute instance-attribute","text":"
DIRECT = 'direct'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.FANOUT","title":"FANOUT class-attribute instance-attribute","text":"
FANOUT = 'fanout'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.HEADERS","title":"HEADERS class-attribute instance-attribute","text":"
HEADERS = 'headers'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.TOPIC","title":"TOPIC class-attribute instance-attribute","text":"
TOPIC = 'topic'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.X_CONSISTENT_HASH","title":"X_CONSISTENT_HASH class-attribute instance-attribute","text":"
X_CONSISTENT_HASH = 'x-consistent-hash'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.X_DELAYED_MESSAGE","title":"X_DELAYED_MESSAGE class-attribute instance-attribute","text":"
X_DELAYED_MESSAGE = 'x-delayed-message'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.X_MODULUS_HASH","title":"X_MODULUS_HASH class-attribute instance-attribute","text":"
X_MODULUS_HASH = 'x-modulus-hash'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/logging/RabbitLoggingMixin/","title":"RabbitLoggingMixin","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/logging/RabbitLoggingMixin/#faststream.rabbit.shared.logging.RabbitLoggingMixin","title":"faststream.rabbit.shared.logging.RabbitLoggingMixin","text":"
RabbitLoggingMixin(\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any\n)\n

Bases: LoggingMixin

A class that extends the LoggingMixin class and adds additional functionality for logging RabbitMQ related information.

METHOD DESCRIPTION __init__

Initializes the RabbitLoggingMixin object.

_get_log_context

Overrides the _get_log_context method of the LoggingMixin class to include RabbitMQ related context information.

fmt

Returns the log format string.

_setup_log_context

Sets up the log context by updating the maximum lengths of the queue and exchange names.

Initialize the class.

PARAMETER DESCRIPTION *args

Variable length argument list

TYPE: Any DEFAULT: ()

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: access_logger

log_level

Logging level

TYPE: int DEFAULT: INFO

log_fmt

Optional log format

TYPE: Optional[str] DEFAULT: None

**kwargs

Arbitrary keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/shared/logging.py
def __init__(\n    self,\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        *args: Variable length argument list\n        logger: Optional logger object\n        log_level: Logging level\n        log_fmt: Optional log format\n        **kwargs: Arbitrary keyword arguments\n\n    Returns:\n        None\n\n    \"\"\"\n    super().__init__(\n        *args,\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n        **kwargs,\n    )\n    self._max_queue_len = 4\n    self._max_exchange_len = 4\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/logging/RabbitLoggingMixin/#faststream.rabbit.shared.logging.RabbitLoggingMixin.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/logging/RabbitLoggingMixin/#faststream.rabbit.shared.logging.RabbitLoggingMixin.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/logging/RabbitLoggingMixin/#faststream.rabbit.shared.logging.RabbitLoggingMixin.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/","title":"ABCPublisher","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher","title":"faststream.rabbit.shared.publisher.ABCPublisher dataclass","text":"

Bases: ABC, BasePublisher[MsgType], BaseRMQInformation

A class representing an ABCPublisher.

","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.exchange","title":"exchange class-attribute instance-attribute","text":"
exchange: Optional[RabbitExchange] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.immediate","title":"immediate class-attribute instance-attribute","text":"
immediate: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.message_kwargs","title":"message_kwargs class-attribute instance-attribute","text":"
message_kwargs: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.persist","title":"persist class-attribute instance-attribute","text":"
persist: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.priority","title":"priority class-attribute instance-attribute","text":"
priority: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.queue","title":"queue class-attribute instance-attribute","text":"
queue: RabbitQueue = field(default=RabbitQueue(''))\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.virtual_host","title":"virtual_host class-attribute instance-attribute","text":"
virtual_host: str = '/'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.publish","title":"publish abstractmethod async","text":"
publish(\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

correlation_id

Optional correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/publisher.py
@abstractmethod\nasync def publish(\n    self,\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        correlation_id: Optional correlation ID for the message.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRoute/","title":"RabbitRoute","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/","title":"RabbitRouter","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter","title":"faststream.rabbit.shared.router.RabbitRouter","text":"
RabbitRouter(\n    prefix: str = \"\",\n    handlers: Sequence[\n        RabbitRoute[IncomingMessage, SendableMessage]\n    ] = (),\n    **kwargs: Any\n)\n

Bases: BrokerRouter[int, IncomingMessage]

A class representing a RabbitMQ router for handling incoming messages.

METHOD DESCRIPTION __init__

initializes the RabbitRouter object

subscriber

decorator for subscribing to a queue and registering a handler function

Override the __init__ method of the parent class.

PARAMETER DESCRIPTION prefix

A prefix string

TYPE: str DEFAULT: ''

handlers

A sequence of RabbitRoute objects

TYPE: Sequence[BrokerRoute[IncomingMessage, SendableMessage]] DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported

Source code in faststream/rabbit/shared/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[RabbitRoute[IncomingMessage, SendableMessage]] = (),\n    **kwargs: Any,\n) -> None:\n    \"\"\"Override the `__init__` method of the parent class.\n\n    Args:\n        prefix: A prefix string\n        handlers: A sequence of RabbitRoute objects\n        **kwargs: Additional keyword arguments\n\n    Raises:\n        NotImplementedError: If silent animals are not supported\n\n    \"\"\"\n    for h in handlers:\n        if (q := h.kwargs.pop(\"queue\", None)) is None:\n            q, h.args = h.args[0], h.args[1:]\n        queue = RabbitQueue.validate(q)\n        new_q = model_copy(queue, update={\"name\": prefix + queue.name})\n        h.args = (new_q, *h.args)\n\n    super().__init__(prefix, handlers, **kwargs)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    *broker_args: Any,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        IncomingMessage, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function to subscribe to a RabbitMQ queue.

PARAMETER DESCRIPTION self

the instance of the class

queue

the queue to subscribe to, can be a string or a RabbitQueue object

*broker_args

additional arguments for the broker

DEFAULT: ()

**broker_kwargs

additional keyword arguments for the broker

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn]]

A callable object that wraps the handler function for the incoming messages from the queue.

RAISES DESCRIPTION TypeError

If the queue is not a string or a RabbitQueue object

Source code in faststream/rabbit/shared/router.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    queue: Union[str, RabbitQueue],\n    *broker_args: Any,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function to subscribe to a RabbitMQ queue.\n\n    Args:\n        self : the instance of the class\n        queue : the queue to subscribe to, can be a string or a RabbitQueue object\n        *broker_args : additional arguments for the broker\n        **broker_kwargs : additional keyword arguments for the broker\n\n    Returns:\n        A callable object that wraps the handler function for the incoming messages from the queue.\n\n    Raises:\n        TypeError: If the queue is not a string or a RabbitQueue object\n\n    \"\"\"\n    q = RabbitQueue.validate(queue)\n    new_q = model_copy(q, update={\"name\": self.prefix + q.name})\n    return self._wrap_subscriber(new_q, *broker_args, **broker_kwargs)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/BaseRMQInformation/","title":"BaseRMQInformation","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/BaseRMQInformation/#faststream.rabbit.shared.schemas.BaseRMQInformation","title":"faststream.rabbit.shared.schemas.BaseRMQInformation dataclass","text":"

BaseRMQInformation.

","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/BaseRMQInformation/#faststream.rabbit.shared.schemas.BaseRMQInformation.exchange","title":"exchange class-attribute instance-attribute","text":"
exchange: Optional[RabbitExchange] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/BaseRMQInformation/#faststream.rabbit.shared.schemas.BaseRMQInformation.queue","title":"queue class-attribute instance-attribute","text":"
queue: RabbitQueue = field(default=RabbitQueue(''))\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/BaseRMQInformation/#faststream.rabbit.shared.schemas.BaseRMQInformation.virtual_host","title":"virtual_host class-attribute instance-attribute","text":"
virtual_host: str = '/'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/","title":"RabbitExchange","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange","title":"faststream.rabbit.shared.schemas.RabbitExchange","text":"
RabbitExchange(\n    name: str,\n    type: ExchangeType = ExchangeType.DIRECT,\n    durable: bool = False,\n    auto_delete: bool = False,\n    internal: bool = False,\n    passive: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_to: Optional[RabbitExchange] = None,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n)\n

Bases: NameRequired

A class to represent a RabbitMQ exchange.

METHOD DESCRIPTION __hash__

returns the hash value of the exchange

__init__

initializes the RabbitExchange object

Initialize a RabbitExchange object.

PARAMETER DESCRIPTION name

Name of the exchange.

TYPE: str

type

Type of the exchange. Defaults to ExchangeType.DIRECT.

TYPE: ExchangeType DEFAULT: DIRECT

durable

Whether the exchange should survive broker restarts. Defaults to False.

TYPE: bool DEFAULT: False

auto_delete

Whether the exchange should be deleted when no longer in use. Defaults to False.

TYPE: bool DEFAULT: False

internal

Whether the exchange is used for internal purposes and should not be published to directly. Defaults to False.

TYPE: bool DEFAULT: False

passive

Whether to check if the exchange exists before creating it. Defaults to False.

TYPE: bool DEFAULT: False

arguments

Additional arguments for the exchange. Defaults to None.

TYPE: Optional[AnyDict] DEFAULT: None

timeout

Timeout for the operation. Defaults to None.

TYPE: TimeoutType DEFAULT: None

robust

Whether to use robust mode for the exchange. Defaults to True.

TYPE: bool DEFAULT: True

bind_to

Exchange to bind to. Defaults to None.

TYPE: Optional[RabbitExchange] DEFAULT: None

bind_arguments

Arguments for the binding. Defaults to None.

TYPE: Optional[AnyDict] DEFAULT: None

routing_key

Routing key for the exchange. Defaults to \"\".

TYPE: str DEFAULT: ''

RAISES DESCRIPTION NotImplementedError Source code in faststream/rabbit/shared/schemas.py
def __init__(\n    self,\n    name: str,\n    type: ExchangeType = ExchangeType.DIRECT,\n    durable: bool = False,\n    auto_delete: bool = False,\n    internal: bool = False,\n    passive: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_to: Optional[\"RabbitExchange\"] = None,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n) -> None:\n    \"\"\"Initialize a RabbitExchange object.\n\n    Args:\n        name (str): Name of the exchange.\n        type (ExchangeType, optional): Type of the exchange. Defaults to ExchangeType.DIRECT.\n        durable (bool, optional): Whether the exchange should survive broker restarts. Defaults to False.\n        auto_delete (bool, optional): Whether the exchange should be deleted when no longer in use. Defaults to False.\n        internal (bool, optional): Whether the exchange is used for internal purposes and should not be published to directly. Defaults to False.\n        passive (bool, optional): Whether to check if the exchange exists before creating it. Defaults to False.\n        arguments (Optional[AnyDict], optional): Additional arguments for the exchange. Defaults to None.\n        timeout (TimeoutType, optional): Timeout for the operation. Defaults to None.\n        robust (bool, optional): Whether to use robust mode for the exchange. Defaults to True.\n        bind_to (Optional[\"RabbitExchange\"], optional): Exchange to bind to. Defaults to None.\n        bind_arguments (Optional[AnyDict], optional): Arguments for the binding. Defaults to None.\n        routing_key (str, optional): Routing key for the exchange. Defaults to \"\".\n\n    Raises:\n        NotImplementedError:\n\n    \"\"\"\n    if routing_key and bind_to is None:  # pragma: no cover\n        warnings.warn(\n            (\n                \"\\nRabbitExchange `routing_key` is using to bind exchange to another one\"\n                \"\\nIt can be used only with the `bind_to` argument, please setup it too\"\n            ),\n            category=RuntimeWarning,\n            stacklevel=1,\n        )\n\n    super().__init__(\n        name=name,\n        type=type.value,\n        durable=durable,\n        auto_delete=auto_delete,\n        routing_key=routing_key,\n        bind_to=bind_to,\n        bind_arguments=bind_arguments,\n        robust=robust,\n        internal=internal,\n        passive=passive,\n        timeout=timeout,\n        arguments=arguments,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.arguments","title":"arguments class-attribute instance-attribute","text":"
arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.auto_delete","title":"auto_delete class-attribute instance-attribute","text":"
auto_delete: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.bind_arguments","title":"bind_arguments class-attribute instance-attribute","text":"
bind_arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.bind_to","title":"bind_to class-attribute instance-attribute","text":"
bind_to: Optional[RabbitExchange] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.durable","title":"durable class-attribute instance-attribute","text":"
durable: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.internal","title":"internal class-attribute instance-attribute","text":"
internal: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.passive","title":"passive class-attribute instance-attribute","text":"
passive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.robust","title":"robust class-attribute instance-attribute","text":"
robust: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.type","title":"type class-attribute instance-attribute","text":"
type: str = ExchangeType.DIRECT.value\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/","title":"RabbitQueue","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue","title":"faststream.rabbit.shared.schemas.RabbitQueue","text":"
RabbitQueue(\n    name: str,\n    durable: bool = False,\n    exclusive: bool = False,\n    passive: bool = False,\n    auto_delete: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n)\n

Bases: NameRequired

A class to represent a RabbitMQ queue.

METHOD DESCRIPTION __hash__

returns the hash value of the queue

routing

returns the routing key of the queue

__init__

initializes the RabbitQueue object with the given parameters

Initialize a class object.

PARAMETER DESCRIPTION name

The name of the object.

TYPE: str

durable

Whether the object is durable. Defaults to False.

TYPE: bool DEFAULT: False

exclusive

Whether the object is exclusive. Defaults to False.

TYPE: bool DEFAULT: False

passive

Whether the object is passive. Defaults to False.

TYPE: bool DEFAULT: False

auto_delete

Whether the object is auto delete. Defaults to False.

TYPE: bool DEFAULT: False

arguments

Additional arguments for the object. Defaults to None.

TYPE: dict DEFAULT: None

timeout

Timeout for the object. Defaults to None.

TYPE: TimeoutType DEFAULT: None

robust

Whether the object is robust. Defaults to True.

TYPE: bool DEFAULT: True

bind_arguments

Bind arguments for the object. Defaults to None.

TYPE: dict DEFAULT: None

routing_key

Routing key for the object. Defaults to \"\".

TYPE: str DEFAULT: ''

Source code in faststream/rabbit/shared/schemas.py
def __init__(\n    self,\n    name: str,\n    durable: bool = False,\n    exclusive: bool = False,\n    passive: bool = False,\n    auto_delete: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n) -> None:\n    \"\"\"Initialize a class object.\n\n    Args:\n        name (str): The name of the object.\n        durable (bool, optional): Whether the object is durable. Defaults to False.\n        exclusive (bool, optional): Whether the object is exclusive. Defaults to False.\n        passive (bool, optional): Whether the object is passive. Defaults to False.\n        auto_delete (bool, optional): Whether the object is auto delete. Defaults to False.\n        arguments (dict, optional): Additional arguments for the object. Defaults to None.\n        timeout (TimeoutType, optional): Timeout for the object. Defaults to None.\n        robust (bool, optional): Whether the object is robust. Defaults to True.\n        bind_arguments (dict, optional): Bind arguments for the object. Defaults to None.\n        routing_key (str, optional): Routing key for the object. Defaults to \"\".\n\n    \"\"\"\n    re, routing_key = compile_path(routing_key, replace_symbol=\"*\")\n    super().__init__(\n        name=name,\n        path_regex=re,\n        durable=durable,\n        exclusive=exclusive,\n        bind_arguments=bind_arguments,\n        routing_key=routing_key,\n        robust=robust,\n        passive=passive,\n        auto_delete=auto_delete,\n        arguments=arguments,\n        timeout=timeout,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.arguments","title":"arguments class-attribute instance-attribute","text":"
arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.auto_delete","title":"auto_delete class-attribute instance-attribute","text":"
auto_delete: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.bind_arguments","title":"bind_arguments class-attribute instance-attribute","text":"
bind_arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.durable","title":"durable class-attribute instance-attribute","text":"
durable: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.exclusive","title":"exclusive class-attribute instance-attribute","text":"
exclusive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'arbitrary_types_allowed': True}\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.name","title":"name class-attribute instance-attribute","text":"
name: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.passive","title":"passive class-attribute instance-attribute","text":"
passive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.path_regex","title":"path_regex class-attribute instance-attribute","text":"
path_regex: Optional[Pattern[str]] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.robust","title":"robust class-attribute instance-attribute","text":"
robust: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.routing","title":"routing property","text":"
routing: str\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.Config.arbitrary_types_allowed","title":"arbitrary_types_allowed class-attribute instance-attribute","text":"
arbitrary_types_allowed = True\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/ReplyConfig/","title":"ReplyConfig","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/ReplyConfig/#faststream.rabbit.shared.schemas.ReplyConfig","title":"faststream.rabbit.shared.schemas.ReplyConfig","text":"

Bases: BaseModel

","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/ReplyConfig/#faststream.rabbit.shared.schemas.ReplyConfig.immediate","title":"immediate class-attribute instance-attribute","text":"
immediate: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/ReplyConfig/#faststream.rabbit.shared.schemas.ReplyConfig.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/ReplyConfig/#faststream.rabbit.shared.schemas.ReplyConfig.persist","title":"persist class-attribute instance-attribute","text":"
persist: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/get_routing_hash/","title":"get_routing_hash","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/get_routing_hash/#faststream.rabbit.shared.schemas.get_routing_hash","title":"faststream.rabbit.shared.schemas.get_routing_hash","text":"
get_routing_hash(\n    queue: RabbitQueue,\n    exchange: Optional[RabbitExchange] = None,\n) -> int\n

Calculate the routing hash for a RabbitMQ queue and exchange.

PARAMETER DESCRIPTION queue

The RabbitMQ queue.

TYPE: RabbitQueue

exchange

The RabbitMQ exchange (optional).

TYPE: Optional[RabbitExchange] DEFAULT: None

RETURNS DESCRIPTION int

The routing hash as an integer.

Source code in faststream/rabbit/shared/schemas.py
def get_routing_hash(\n    queue: RabbitQueue,\n    exchange: Optional[RabbitExchange] = None,\n) -> int:\n    \"\"\"Calculate the routing hash for a RabbitMQ queue and exchange.\n\n    Args:\n        queue: The RabbitMQ queue.\n        exchange: The RabbitMQ exchange (optional).\n\n    Returns:\n        The routing hash as an integer.\n\n    \"\"\"\n    return hash(queue) + hash(exchange or \"\")\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/utils/build_url/","title":"build_url","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/utils/build_url/#faststream.rabbit.shared.utils.build_url","title":"faststream.rabbit.shared.utils.build_url","text":"
build_url(\n    url: Union[str, URL, None] = None,\n    *,\n    host: Optional[str] = None,\n    port: Optional[int] = None,\n    login: Optional[str] = None,\n    password: Optional[str] = None,\n    virtualhost: Optional[str] = None,\n    ssl: Optional[bool] = None,\n    ssl_options: Optional[SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    **kwargs: Any\n) -> URL\n
Source code in faststream/rabbit/shared/utils.py
def build_url(\n    url: Union[str, URL, None] = None,\n    *,\n    host: Optional[str] = None,\n    port: Optional[int] = None,\n    login: Optional[str] = None,\n    password: Optional[str] = None,\n    virtualhost: Optional[str] = None,\n    ssl: Optional[bool] = None,\n    ssl_options: Optional[SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    **kwargs: Any,\n) -> URL:\n    original_url = make_url(url)\n\n    return make_url(\n        host=host or original_url.host or \"localhost\",\n        port=port or original_url.port or 5672,\n        login=login or original_url.user or \"guest\",\n        password=password or original_url.password or \"guest\",\n        virtualhost=virtualhost or removeprefix(original_url.path, \"/\"),\n        ssl=ssl or original_url.scheme == \"amqps\",\n        ssl_options=ssl_options,\n        client_properties=client_properties,\n        **{\n            **kwargs,\n            **dict(original_url.query),\n        },\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/utils/removeprefix/","title":"removeprefix","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/utils/removeprefix/#faststream.rabbit.shared.utils.removeprefix","title":"faststream.rabbit.shared.utils.removeprefix","text":"
removeprefix(string: str, prefix: str) -> str\n
Source code in faststream/rabbit/shared/utils.py
def removeprefix(string: str, prefix: str) -> str:\n    if string.startswith(prefix):\n        return string[len(prefix) :]\n    return string\n
","boost":0.5},{"location":"api/faststream/rabbit/test/FakeProducer/","title":"FakeProducer","text":"","boost":0.5},{"location":"api/faststream/rabbit/test/FakeProducer/#faststream.rabbit.test.FakeProducer","title":"faststream.rabbit.test.FakeProducer","text":"
FakeProducer(broker: RabbitBroker)\n

Bases: AioPikaFastProducer

A fake RabbitMQ producer for testing purposes.

This class extends AioPikaFastProducer and is used to simulate RabbitMQ message publishing during tests.

Initialize a FakeProducer instance.

PARAMETER DESCRIPTION broker

The RabbitBroker instance to be used for message publishing.

TYPE: RabbitBroker

Source code in faststream/rabbit/test.py
def __init__(self, broker: RabbitBroker) -> None:\n    \"\"\"\n    Initialize a FakeProducer instance.\n\n    Args:\n        broker (RabbitBroker): The RabbitBroker instance to be used for message publishing.\n    \"\"\"\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/rabbit/test/FakeProducer/#faststream.rabbit.test.FakeProducer.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/rabbit/test/FakeProducer/#faststream.rabbit.test.FakeProducer.declarer","title":"declarer instance-attribute","text":"
declarer: RabbitDeclarer = declarer\n
","boost":0.5},{"location":"api/faststream/rabbit/test/FakeProducer/#faststream.rabbit.test.FakeProducer.publish","title":"publish async","text":"
publish(\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message to a RabbitMQ queue or exchange.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: AioPikaSendableMessage DEFAULT: ''

queue

The target queue for the message.

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The target exchange for the message.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key for the message.

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory.

TYPE: bool DEFAULT: True

immediate

Whether the message should be sent immediately.

TYPE: bool DEFAULT: False

timeout

The timeout for the message.

TYPE: TimeoutType DEFAULT: None

rpc

Whether the message is for RPC.

TYPE: bool DEFAULT: False

rpc_timeout

The RPC timeout.

TYPE: float DEFAULT: 30.0

raise_timeout

Whether to raise a timeout exception.

TYPE: bool DEFAULT: False

persist

Whether to persist the message.

TYPE: bool DEFAULT: False

reply_to

The reply-to address for RPC messages.

TYPE: str DEFAULT: None

**message_kwargs

Additional message properties and content.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

Optional[SendableMessage]: The published message if successful, or None if not.

Source code in faststream/rabbit/test.py
async def publish(\n    self,\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"\n    Publish a message to a RabbitMQ queue or exchange.\n\n    Args:\n        message (AioPikaSendableMessage, optional): The message to be published.\n        queue (Union[RabbitQueue, str], optional): The target queue for the message.\n        exchange (Union[RabbitExchange, str, None], optional): The target exchange for the message.\n        routing_key (str, optional): The routing key for the message.\n        mandatory (bool, optional): Whether the message is mandatory.\n        immediate (bool, optional): Whether the message should be sent immediately.\n        timeout (TimeoutType, optional): The timeout for the message.\n        rpc (bool, optional): Whether the message is for RPC.\n        rpc_timeout (float, optional): The RPC timeout.\n        raise_timeout (bool, optional): Whether to raise a timeout exception.\n        persist (bool, optional): Whether to persist the message.\n        reply_to (str, optional): The reply-to address for RPC messages.\n        **message_kwargs (Any): Additional message properties and content.\n\n    Returns:\n        Optional[SendableMessage]: The published message if successful, or None if not.\n    \"\"\"\n    exch = RabbitExchange.validate(exchange)\n\n    incoming = build_message(\n        message=message,\n        queue=queue,\n        exchange=exch,\n        routing_key=routing_key,\n        reply_to=reply_to,\n        **message_kwargs,\n    )\n\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        if handler.exchange == exch:\n            call: bool = False\n\n            if (\n                handler.exchange is None\n                or handler.exchange.type == ExchangeType.DIRECT\n            ):\n                call = handler.queue.name == incoming.routing_key\n\n            elif handler.exchange.type == ExchangeType.FANOUT:\n                call = True\n\n            elif handler.exchange.type == ExchangeType.TOPIC:\n                call = bool(\n                    re.match(\n                        handler.queue.routing_key.replace(\".\", r\"\\.\").replace(\n                            \"*\", \".*\"\n                        ),\n                        incoming.routing_key or \"\",\n                    )\n                )\n\n            elif handler.exchange.type == ExchangeType.HEADERS:  # pramga: no branch\n                queue_headers = (handler.queue.bind_arguments or {}).copy()\n                msg_headers = incoming.headers\n\n                if not queue_headers:\n                    call = True\n\n                else:\n                    matcher = queue_headers.pop(\"x-match\", \"all\")\n\n                    full = True\n                    none = True\n                    for k, v in queue_headers.items():\n                        if msg_headers.get(k) != v:\n                            full = False\n                        else:\n                            none = False\n\n                    if not none:\n                        call = (matcher == \"any\") or full\n\n            else:  # pragma: no cover\n                raise AssertionError(\"unreachable\")\n\n            if call:\n                r = await call_handler(\n                    handler=handler,\n                    message=incoming,\n                    rpc=rpc,\n                    rpc_timeout=rpc_timeout,\n                    raise_timeout=raise_timeout,\n                )\n\n                if rpc:  # pragma: no branch\n                    return r\n\n    return None\n
","boost":0.5},{"location":"api/faststream/rabbit/test/PatchedMessage/","title":"PatchedMessage","text":"","boost":0.5},{"location":"api/faststream/rabbit/test/PatchedMessage/#faststream.rabbit.test.PatchedMessage","title":"faststream.rabbit.test.PatchedMessage","text":"

Bases: IncomingMessage

Patched message class for testing purposes.

This class extends aio_pika's IncomingMessage class and is used to simulate RabbitMQ message handling during tests.

","boost":0.5},{"location":"api/faststream/rabbit/test/PatchedMessage/#faststream.rabbit.test.PatchedMessage.ack","title":"ack async","text":"
ack(multiple: bool = False) -> None\n

Asynchronously acknowledge a message.

PARAMETER DESCRIPTION multiple

Whether to acknowledge multiple messages at once. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/test.py
async def ack(self, multiple: bool = False) -> None:\n    \"\"\"Asynchronously acknowledge a message.\n\n    Args:\n        multiple (bool, optional): Whether to acknowledge multiple messages at once. Defaults to False.\n\n    Returns:\n        None\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/rabbit/test/PatchedMessage/#faststream.rabbit.test.PatchedMessage.nack","title":"nack async","text":"
nack(multiple: bool = False, requeue: bool = True) -> None\n

Nack the message.

PARAMETER DESCRIPTION multiple

Whether to nack multiple messages. Default is False.

TYPE: bool DEFAULT: False

requeue

Whether to requeue the message. Default is True.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/test.py
async def nack(self, multiple: bool = False, requeue: bool = True) -> None:\n    \"\"\"Nack the message.\n\n    Args:\n        multiple: Whether to nack multiple messages. Default is False.\n        requeue: Whether to requeue the message. Default is True.\n\n    Returns:\n        None\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/rabbit/test/PatchedMessage/#faststream.rabbit.test.PatchedMessage.reject","title":"reject async","text":"
reject(requeue: bool = False) -> None\n

Rejects a task.

PARAMETER DESCRIPTION requeue

Whether to requeue the task if it fails (default: False)

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/test.py
async def reject(self, requeue: bool = False) -> None:\n    \"\"\"Rejects a task.\n\n    Args:\n        requeue: Whether to requeue the task if it fails (default: False)\n\n    Returns:\n        None\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/","title":"TestRabbitBroker","text":"","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker","title":"faststream.rabbit.test.TestRabbitBroker","text":"
TestRabbitBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[RabbitBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: RabbitBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: RabbitBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(\n        queue=publisher.queue,\n        exchange=publisher.exchange,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: RabbitBroker, publisher: Any\n) -> None\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef patch_publisher(broker: RabbitBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: RabbitBroker, publisher: Publisher\n) -> None\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: RabbitBroker,\n    publisher: Publisher,\n) -> None:\n    broker.handlers.pop(\n        publisher._get_routing_hash(),\n        None,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/test/build_message/","title":"build_message","text":"","boost":0.5},{"location":"api/faststream/rabbit/test/build_message/#faststream.rabbit.test.build_message","title":"faststream.rabbit.test.build_message","text":"
build_message(\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any\n) -> PatchedMessage\n

Build a patched RabbitMQ message for testing.

PARAMETER DESCRIPTION message

The message content.

TYPE: AioPikaSendableMessage DEFAULT: ''

queue

The message queue.

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The message exchange.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The message routing key.

TYPE: str DEFAULT: ''

reply_to

The reply-to queue.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional message arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION PatchedMessage

A patched RabbitMQ message.

TYPE: PatchedMessage

Source code in faststream/rabbit/test.py
def build_message(\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any,\n) -> PatchedMessage:\n    \"\"\"\n    Build a patched RabbitMQ message for testing.\n\n    Args:\n        message (AioPikaSendableMessage): The message content.\n        queue (Union[RabbitQueue, str]): The message queue.\n        exchange (Union[RabbitExchange, str, None]): The message exchange.\n        routing_key (str): The message routing key.\n        reply_to (Optional[str]): The reply-to queue.\n        **message_kwargs (Any): Additional message arguments.\n\n    Returns:\n        PatchedMessage: A patched RabbitMQ message.\n    \"\"\"\n    que = RabbitQueue.validate(queue)\n    exch = RabbitExchange.validate(exchange)\n    msg = AioPikaParser.encode_message(\n        message=message,\n        persist=False,\n        reply_to=reply_to,\n        callback_queue=None,\n        **message_kwargs,\n    )\n\n    routing = routing_key or (getattr(que, \"name\", \"\"))\n\n    return PatchedMessage(\n        aiormq.abc.DeliveredMessage(\n            delivery=spec.Basic.Deliver(\n                exchange=getattr(exch, \"name\", \"\"),\n                routing_key=routing,\n            ),\n            header=ContentHeader(\n                properties=spec.Basic.Properties(\n                    content_type=msg.content_type,\n                    message_id=str(uuid4()),\n                    headers=msg.headers,\n                    reply_to=reply_to,\n                )\n            ),\n            body=msg.body,\n            channel=AsyncMock(),\n        )\n    )\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/","title":"ListSub","text":"","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub","title":"faststream.redis.ListSub","text":"
ListSub(\n    channel: str,\n    batch: bool = False,\n    max_records: PositiveInt = 10,\n    polling_interval: PositiveFloat = 0.1,\n)\n

Bases: NameRequired

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    channel: str,\n    batch: bool = False,\n    max_records: PositiveInt = 10,\n    polling_interval: PositiveFloat = 0.1,\n) -> None:\n    super().__init__(\n        name=channel,\n        batch=batch,\n        max_records=max_records,\n        polling_interval=polling_interval,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.max_records","title":"max_records class-attribute instance-attribute","text":"
max_records: PositiveInt = 10\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: PositiveFloat = 0.1\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.records","title":"records property","text":"
records: Optional[PositiveInt]\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/","title":"PubSub","text":"","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub","title":"faststream.redis.PubSub","text":"
PubSub(\n    channel: str,\n    pattern: bool = False,\n    polling_interval: PositiveFloat = 1.0,\n)\n

Bases: NameRequired

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    channel: str,\n    pattern: bool = False,\n    polling_interval: PositiveFloat = 1.0,\n) -> None:\n    reg, path = compile_path(channel, replace_symbol=\"*\")\n\n    if reg is not None:\n        pattern = True\n\n    super().__init__(\n        name=path,\n        path_regex=reg,\n        pattern=pattern,\n        polling_interval=polling_interval,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.last_id","title":"last_id class-attribute instance-attribute","text":"
last_id: str = '$'\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'arbitrary_types_allowed': True}\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.path_regex","title":"path_regex class-attribute instance-attribute","text":"
path_regex: Optional[Pattern[str]] = None\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.pattern","title":"pattern class-attribute instance-attribute","text":"
pattern: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: PositiveFloat = 1.0\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.Config.arbitrary_types_allowed","title":"arbitrary_types_allowed class-attribute instance-attribute","text":"
arbitrary_types_allowed = True\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/","title":"RedisBroker","text":"","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker","title":"faststream.redis.RedisBroker","text":"
RedisBroker(\n    url: str = \"redis://localhost:6379\",\n    polling_interval: Optional[float] = None,\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"custom\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: RedisLoggingMixin, BrokerAsyncUsecase[AnyRedisDict, 'Redis[bytes]']

Source code in faststream/redis/broker.py
def __init__(\n    self,\n    url: str = \"redis://localhost:6379\",\n    polling_interval: Optional[float] = None,\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"custom\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    self.global_polling_interval = polling_interval\n    self._producer = None\n\n    super().__init__(\n        url=url,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n    )\n\n    url_kwargs = urlparse(self.url)\n    self.protocol = protocol or url_kwargs.scheme\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.global_polling_interval","title":"global_polling_interval instance-attribute","text":"
global_polling_interval = polling_interval\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[int, Handler]\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol or url_kwargs.scheme\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.connect","title":"connect async","text":"
connect(*args: Any, **kwargs: Any) -> Redis[bytes]\n
Source code in faststream/redis/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> \"Redis[bytes]\":\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, **kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.publish_batch","title":"publish_batch async","text":"
publish_batch(*args: Any, **kwargs: Any) -> None\n
Source code in faststream/redis/broker.py
async def publish_batch(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish_batch(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.publisher","title":"publisher","text":"
publisher(\n    channel: Union[Channel, PubSub, None] = None,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/redis/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    channel: Union[Channel, PubSub, None] = None,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    channel = PubSub.validate(channel)\n    list = ListSub.validate(list)\n    stream = StreamSub.validate(stream)\n\n    any_of = channel or list or stream\n    if any_of is None:\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    key = Handler.get_routing_hash(any_of)\n    publisher = self._publishers.get(\n        key,\n        Publisher(\n            channel=channel,\n            list=list,\n            stream=stream,\n            headers=headers,\n            reply_to=reply_to,\n            # AsyncAPI\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(key, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.start","title":"start async","text":"
start() -> None\n
Source code in faststream/redis/broker.py
async def start(self) -> None:\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n    assert self._connection, NOT_CONNECTED_YET  # nosec B101\n\n    for handler in self.handlers.values():\n        if (stream := handler.stream_sub) is not None and stream.group:\n            try:\n                await self._connection.xgroup_create(\n                    name=stream.name,\n                    groupname=stream.group,\n                    mkstream=True,\n                )\n            except ResponseError as e:\n                if \"already exists\" not in str(e):\n                    raise e\n\n        c = self._get_log_context(None, handler.channel_name)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self._connection)\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Any, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[AnyRedisDict, RedisMessage]] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[Any, P_HandlerParams, T_HandlerReturn],\n]:\n    channel = PubSub.validate(channel)\n    list = ListSub.validate(list)\n    stream = StreamSub.validate(stream)\n\n    if (any_of := channel or list or stream) is None:\n        raise ValueError(\n            \"You should specify `channel`, `list`, `stream` subscriber type\"\n        )\n\n    if all((channel, list)):\n        raise ValueError(\"You can't use `PubSub` and `ListSub` both\")\n    elif all((channel, stream)):\n        raise ValueError(\"You can't use `PubSub` and `StreamSub` both\")\n    elif all((list, stream)):\n        raise ValueError(\"You can't use `ListSub` and `StreamSub` both\")\n\n    self._setup_log_context(channel=any_of.name)\n    super().subscriber()\n\n    key = Handler.get_routing_hash(any_of)\n    handler = self.handlers[key] = self.handlers.get(\n        key,\n        Handler(  # type: ignore[abstract]\n            log_context_builder=partial(\n                self._get_log_context,\n                channel=any_of.name,\n            ),\n            graceful_timeout=self.graceful_timeout,\n            # Redis\n            channel=channel,\n            list=list,\n            stream=stream,\n            # AsyncAPI\n            title=title,\n            description=description,\n            include_in_schema=include_in_schema,\n        ),\n    )\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[AnyRedisDict, P_HandlerParams, T_HandlerReturn,]:\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,  # type: ignore[arg-type]\n            decoder=decoder or self._global_decoder,  # type: ignore[arg-type]\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/redis/RedisRoute/","title":"RedisRoute","text":"","boost":0.5},{"location":"api/faststream/redis/RedisRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/redis/RedisRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/redis/RedisRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/redis/RedisRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/","title":"RedisRouter","text":"","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter","title":"faststream.redis.RedisRouter","text":"
RedisRouter(\n    prefix: str = \"\",\n    handlers: Sequence[RedisRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    include_in_schema: bool = True\n)\n

Bases: RedisRouter

Source code in faststream/redis/router.py
            publisher.list, update={\"name\": prefix + publisher.list.name}\n        )\n    elif publisher.stream is not None:\n        publisher.stream = model_copy(\n            publisher.stream, update={\"name\": prefix + publisher.stream.name}\n        )\n    else:\n        raise AssertionError(\"unreachable\")\n    return publisher\n\n@override\ndef publisher(  # type: ignore[override]\n    self,\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.publisher","title":"publisher","text":"
publisher(\n    channel: Union[str, PubSub, None] = None,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/redis/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    channel: Union[str, PubSub, None] = None,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    if not any((stream, list, channel)):\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            channel=PubSub.validate(channel),\n            list=ListSub.validate(list),\n            stream=StreamSub.validate(stream),\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[str, PubSub, None] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Any, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/router.py
) -> Publisher:\n    if not any((stream, list, channel)):\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            channel=PubSub.validate(channel),\n            list=ListSub.validate(list),\n            stream=StreamSub.validate(stream),\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/","title":"StreamSub","text":"","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub","title":"faststream.redis.StreamSub","text":"
StreamSub(\n    stream: str,\n    polling_interval: Optional[PositiveInt] = 100,\n    group: Optional[str] = None,\n    consumer: Optional[str] = None,\n    batch: bool = False,\n    no_ack: bool = False,\n    last_id: Optional[str] = None,\n)\n

Bases: NameRequired

Redis Stream subscriber parameters

PARAMETER DESCRIPTION stream

(str): Redis Stream name.

TYPE: str

polling_interval

(int:ms | None): wait message block.

TYPE: Optional[PositiveInt] DEFAULT: 100

group

(str | None): consumer group name.

TYPE: Optional[str] DEFAULT: None

consumer

(str | None): consumer name.

TYPE: Optional[str] DEFAULT: None

batch

(bool): consume messages in batches.

TYPE: bool DEFAULT: False

no_ack

(bool): do not add message to PEL.

TYPE: bool DEFAULT: False

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    stream: str,\n    polling_interval: Optional[PositiveInt] = 100,\n    group: Optional[str] = None,\n    consumer: Optional[str] = None,\n    batch: bool = False,\n    no_ack: bool = False,\n    last_id: Optional[str] = None,\n) -> None:\n    \"\"\"\n    Redis Stream subscriber parameters\n\n    Args:\n        stream: (str): Redis Stream name.\n        polling_interval: (int:ms | None): wait message block.\n        group: (str | None): consumer group name.\n        consumer: (str | None): consumer name.\n        batch: (bool): consume messages in batches.\n        no_ack: (bool): do not add message to PEL.\n    \"\"\"\n    if (group and not consumer) or (not group and consumer):\n        raise ValueError(\"You should specify `group` and `consumer` both\")\n\n    if group and consumer:\n        msg: Optional[str] = None\n\n        if last_id:\n            msg = \"`last_id` has no effect with consumer group\"\n\n        if no_ack:\n            msg = \"`no_ack` has no effect with consumer group\"\n\n        if msg:\n            warnings.warn(\n                message=msg,\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n    super().__init__(\n        name=stream,\n        group=group,\n        consumer=consumer,\n        polling_interval=polling_interval,\n        batch=batch,\n        no_ack=no_ack,\n        last_id=last_id or \"$\",\n    )\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.consumer","title":"consumer class-attribute instance-attribute","text":"
consumer: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.group","title":"group class-attribute instance-attribute","text":"
group: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.last_id","title":"last_id class-attribute instance-attribute","text":"
last_id: str = '$'\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.no_ack","title":"no_ack class-attribute instance-attribute","text":"
no_ack: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: Optional[PositiveInt] = Field(\n    default=100, description=\"ms\"\n)\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/redis/TestApp/#faststream.broker.test.TestApp","title":"faststream.broker.test.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/redis/TestApp/#faststream.broker.test.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/","title":"TestRedisBroker","text":"","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker","title":"faststream.redis.TestRedisBroker","text":"
TestRedisBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[RedisBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: RedisBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/redis/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: RedisBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(\n        channel=publisher.channel,\n        list=publisher.list,\n        stream=publisher.stream,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: RedisBroker, publisher: Any\n) -> None\n
Source code in faststream/redis/test.py
@staticmethod\ndef patch_publisher(\n    broker: RedisBroker,\n    publisher: Any,\n) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: RedisBroker, publisher: Publisher\n) -> None\n
Source code in faststream/redis/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: RedisBroker,\n    publisher: Publisher,\n) -> None:\n    any_of = publisher.channel or publisher.list or publisher.stream\n    assert any_of  # nosec B101\n    broker.handlers.pop(Handler.get_routing_hash(any_of), None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/","title":"Handler","text":"","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler","title":"faststream.redis.asyncapi.Handler","text":"
Handler(\n    *,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    channel: Optional[PubSub] = None,\n    list: Optional[ListSub] = None,\n    stream: Optional[StreamSub] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True\n)\n

Bases: LogicRedisHandler

Source code in faststream/redis/handler.py
def __init__(\n    self,\n    *,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # Redis info\n    channel: Optional[PubSub] = None,\n    list: Optional[ListSub] = None,\n    stream: Optional[StreamSub] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    self.channel = channel\n    self.list_sub = list\n    self.stream_sub = stream\n\n    self.subscription = None\n    self.task = None\n\n    self.last_id = stream.last_id if stream else \"$\"\n\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.channel","title":"channel instance-attribute","text":"
channel = channel\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.channel_name","title":"channel_name property","text":"
channel_name: str\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.last_id","title":"last_id instance-attribute","text":"
last_id = stream.last_id if stream else '$'\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.list_sub","title":"list_sub instance-attribute","text":"
list_sub = list\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.name","title":"name property","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.stream_sub","title":"stream_sub instance-attribute","text":"
stream_sub = stream\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.subscription","title":"subscription instance-attribute","text":"
subscription: Optional[RPubSub] = None\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.task","title":"task instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        AnyDict, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[AnyDict, RedisMessage]],\n    decoder: Optional[CustomDecoder[RedisMessage]],\n    filter: Filter[RedisMessage],\n    middlewares: Optional[\n        Sequence[Callable[[AnyDict], BaseMiddleware]]\n    ]\n) -> None\n
Source code in faststream/redis/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[AnyDict, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[AnyDict, RedisMessage]],\n    decoder: Optional[CustomDecoder[RedisMessage]],\n    filter: Filter[RedisMessage],\n    middlewares: Optional[Sequence[Callable[[AnyDict], BaseMiddleware]]],\n) -> None:\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, RedisParser.parse_message),\n        decoder=resolve_custom_func(decoder, RedisParser.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/redis/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.task is not None:\n        if not self.task.done():\n            self.task.cancel()\n        self.task = None\n\n    if self.subscription is not None:\n        await self.subscription.unsubscribe()\n        await self.subscription.aclose()  # type: ignore[attr-defined]\n        self.subscription = None\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(channel: Hashable) -> int\n
Source code in faststream/redis/handler.py
@staticmethod\ndef get_routing_hash(channel: Hashable) -> int:\n    return hash(channel)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/redis/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    method = None\n    if self.list_sub is not None:\n        method = \"lpop\"\n\n    elif (ch := self.channel) is not None:\n        if ch.pattern:\n            method = \"psubscribe\"\n        else:\n            method = \"subscribe\"\n\n    elif (stream := self.stream_sub) is not None:\n        if stream.group:\n            method = \"xreadgroup\"\n        else:\n            method = \"xread\"\n\n    else:\n        raise AssertionError(\"unreachable\")\n\n    return {\n        self.name: Channel(\n            description=self.description,\n            subscribe=Operation(\n                message=Message(\n                    title=f\"{self.name}:Message\",\n                    payload=resolve_payloads(payloads),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                redis=redis.ChannelBinding(\n                    channel=self.channel_name,\n                    group_name=getattr(self.stream_sub, \"group\", None),\n                    consumer_name=getattr(self.stream_sub, \"consumer\", None),\n                    method=method,\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.start","title":"start async","text":"
start(client: Redis[bytes]) -> None\n
Source code in faststream/redis/handler.py
@override\nasync def start(self, client: \"Redis[bytes]\") -> None:  # type: ignore[override]\n    self.started = anyio.Event()\n\n    consume: Union[\n        Callable[[], Awaitable[Optional[AnyRedisDict]]],\n        Callable[[], Awaitable[Optional[Sequence[AnyRedisDict]]]],\n    ]\n    sleep: float\n\n    if (list_sub := self.list_sub) is not None:\n        sleep = list_sub.polling_interval\n        consume = partial(\n            self._consume_list_msg,\n            client=client,\n        )\n        self.started.set()\n\n    elif (channel := self.channel) is not None:\n        self.subscription = psub = client.pubsub()\n\n        if channel.pattern:\n            await psub.psubscribe(channel.name)\n        else:\n            await psub.subscribe(channel.name)\n\n        consume = partial(\n            psub.get_message,\n            ignore_subscribe_messages=True,\n            timeout=channel.polling_interval,\n        )\n        sleep = 0.01\n        self.started.set()\n\n    elif self.stream_sub is not None:\n        consume = partial(  # type: ignore[assignment]\n            self._consume_stream_msg,\n            client=client,\n        )\n        sleep = 0.01\n\n    else:\n        raise AssertionError(\"unreachable\")\n\n    await super().start()\n    self.task = asyncio.create_task(self._consume(consume, sleep))\n    # wait until Stream starts to consume\n    await anyio.sleep(0.01)\n    await self.started.wait()\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/","title":"Publisher","text":"","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher","title":"faststream.redis.asyncapi.Publisher","text":"

Bases: LogicPublisher

","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.channel","title":"channel class-attribute instance-attribute","text":"
channel: Optional[PubSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.channel_name","title":"channel_name property","text":"
channel_name: str\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[AnyDict] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.list","title":"list class-attribute instance-attribute","text":"
list: Optional[ListSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.name","title":"name property","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.stream","title":"stream class-attribute instance-attribute","text":"
stream: Optional[StreamSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    channel: Union[str, PubSub, None] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage,\n    channel: Union[str, PubSub, None] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n\n    channel = PubSub.validate(channel or self.channel)\n    list = ListSub.validate(list or self.list)\n    stream = StreamSub.validate(stream or self.stream)\n\n    assert any(\n        (channel, list, stream)\n    ), \"You have to specify outgoing channel\"  # nosec B101\n\n    headers_to_send = (self.headers or {}).copy()\n    if headers is not None:\n        headers_to_send.update(headers)\n\n    if getattr(list, \"batch\", False):\n        await self._producer.publish_batch(\n            *message,\n            list=list.name,  # type: ignore[union-attr]\n        )\n        return None\n\n    else:\n        return await self._producer.publish(\n            message=message,\n            channel=getattr(channel, \"name\", None),\n            list=getattr(list, \"name\", None),\n            stream=getattr(stream, \"name\", None),\n            reply_to=reply_to or self.reply_to,\n            correlation_id=correlation_id,\n            headers=headers_to_send,\n            rpc=rpc,\n            rpc_timeout=rpc_timeout,\n            raise_timeout=raise_timeout,\n        )\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/redis/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    method = None\n    if self.list is not None:\n        method = \"rpush\"\n    elif self.channel is not None:\n        method = \"publish\"\n    elif self.stream is not None:\n        method = \"xadd\"\n    else:\n        raise AssertionError(\"unreachable\")\n\n    return {\n        self.name: Channel(\n            description=self.description,\n            publish=Operation(\n                message=Message(\n                    title=f\"{self.name}:Message\",\n                    payload=resolve_payloads(payloads, \"Publisher\"),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                redis=redis.ChannelBinding(\n                    channel=self.channel_name,\n                    method=method,\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/","title":"RedisBroker","text":"","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker","title":"faststream.redis.broker.RedisBroker","text":"
RedisBroker(\n    url: str = \"redis://localhost:6379\",\n    polling_interval: Optional[float] = None,\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"custom\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: RedisLoggingMixin, BrokerAsyncUsecase[AnyRedisDict, 'Redis[bytes]']

Source code in faststream/redis/broker.py
def __init__(\n    self,\n    url: str = \"redis://localhost:6379\",\n    polling_interval: Optional[float] = None,\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"custom\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    self.global_polling_interval = polling_interval\n    self._producer = None\n\n    super().__init__(\n        url=url,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n    )\n\n    url_kwargs = urlparse(self.url)\n    self.protocol = protocol or url_kwargs.scheme\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.global_polling_interval","title":"global_polling_interval instance-attribute","text":"
global_polling_interval = polling_interval\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[int, Handler]\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol or url_kwargs.scheme\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.connect","title":"connect async","text":"
connect(*args: Any, **kwargs: Any) -> Redis[bytes]\n
Source code in faststream/redis/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> \"Redis[bytes]\":\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, **kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.publish_batch","title":"publish_batch async","text":"
publish_batch(*args: Any, **kwargs: Any) -> None\n
Source code in faststream/redis/broker.py
async def publish_batch(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish_batch(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.publisher","title":"publisher","text":"
publisher(\n    channel: Union[Channel, PubSub, None] = None,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/redis/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    channel: Union[Channel, PubSub, None] = None,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    channel = PubSub.validate(channel)\n    list = ListSub.validate(list)\n    stream = StreamSub.validate(stream)\n\n    any_of = channel or list or stream\n    if any_of is None:\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    key = Handler.get_routing_hash(any_of)\n    publisher = self._publishers.get(\n        key,\n        Publisher(\n            channel=channel,\n            list=list,\n            stream=stream,\n            headers=headers,\n            reply_to=reply_to,\n            # AsyncAPI\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(key, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.start","title":"start async","text":"
start() -> None\n
Source code in faststream/redis/broker.py
async def start(self) -> None:\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n    assert self._connection, NOT_CONNECTED_YET  # nosec B101\n\n    for handler in self.handlers.values():\n        if (stream := handler.stream_sub) is not None and stream.group:\n            try:\n                await self._connection.xgroup_create(\n                    name=stream.name,\n                    groupname=stream.group,\n                    mkstream=True,\n                )\n            except ResponseError as e:\n                if \"already exists\" not in str(e):\n                    raise e\n\n        c = self._get_log_context(None, handler.channel_name)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self._connection)\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Any, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[AnyRedisDict, RedisMessage]] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[Any, P_HandlerParams, T_HandlerReturn],\n]:\n    channel = PubSub.validate(channel)\n    list = ListSub.validate(list)\n    stream = StreamSub.validate(stream)\n\n    if (any_of := channel or list or stream) is None:\n        raise ValueError(\n            \"You should specify `channel`, `list`, `stream` subscriber type\"\n        )\n\n    if all((channel, list)):\n        raise ValueError(\"You can't use `PubSub` and `ListSub` both\")\n    elif all((channel, stream)):\n        raise ValueError(\"You can't use `PubSub` and `StreamSub` both\")\n    elif all((list, stream)):\n        raise ValueError(\"You can't use `ListSub` and `StreamSub` both\")\n\n    self._setup_log_context(channel=any_of.name)\n    super().subscriber()\n\n    key = Handler.get_routing_hash(any_of)\n    handler = self.handlers[key] = self.handlers.get(\n        key,\n        Handler(  # type: ignore[abstract]\n            log_context_builder=partial(\n                self._get_log_context,\n                channel=any_of.name,\n            ),\n            graceful_timeout=self.graceful_timeout,\n            # Redis\n            channel=channel,\n            list=list,\n            stream=stream,\n            # AsyncAPI\n            title=title,\n            description=description,\n            include_in_schema=include_in_schema,\n        ),\n    )\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[AnyRedisDict, P_HandlerParams, T_HandlerReturn,]:\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,  # type: ignore[arg-type]\n            decoder=decoder or self._global_decoder,  # type: ignore[arg-type]\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/redis/fastapi/Context/#faststream.broker.fastapi.context.Context","title":"faststream.broker.fastapi.context.Context","text":"
Context(name: str) -> Any\n
Source code in faststream/broker/fastapi/context.py
def Context(name: str) -> Any:\n    return params.Depends(\n        lambda: context.resolve(name),\n        use_cache=True,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/","title":"RedisRouter","text":"","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter","title":"faststream.redis.fastapi.RedisRouter","text":"
RedisRouter(\n    url: str = \"redis://localhost:6379\",\n    polling_interval: Optional[float] = None,\n    *,\n    host: str = \"localhost\",\n    port: Union[str, int] = 6379,\n    db: Union[str, int] = 0,\n    client_name: Optional[str] = None,\n    health_check_interval: float = 0,\n    max_connections: Optional[int] = None,\n    socket_timeout: Optional[float] = None,\n    socket_connect_timeout: Optional[float] = None,\n    socket_read_size: int = 65536,\n    socket_keepalive: bool = False,\n    socket_keepalive_options: Optional[\n        Mapping[int, Union[int, bytes]]\n    ] = None,\n    socket_type: int = 0,\n    retry_on_timeout: bool = False,\n    encoding: str = \"utf-8\",\n    encoding_errors: str = \"strict\",\n    decode_responses: bool = False,\n    parser_class: Type[BaseParser] = DefaultParser,\n    connection_class: Type[Connection] = Connection,\n    encoder_class: Type[Encoder] = Encoder,\n    security: Optional[BaseSecurity] = None,\n    graceful_timeout: Optional[float] = None,\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    asyncapi_url: Optional[str] = None,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"custom\",\n    description: Optional[str] = None,\n    asyncapi_tags: Optional[Sequence[asyncapi.Tag]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    setup_state: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n)\n

Bases: StreamRouter[AnyRedisDict]

Source code in faststream/redis/fastapi.py
@staticmethod\ndef _setup_log_context(  # type: ignore[override]\n    main_broker: RB,\n    including_broker: RB,\n) -> None:\n    for h in including_broker.handlers.values():\n        main_broker._setup_log_context(h.channel_name)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.broker","title":"broker instance-attribute","text":"
broker: BrokerAsyncUsecase[\n    MsgType, Any\n] = self.broker_class(\n    *connection_args,\n    apply_types=False,\n    tags=asyncapi_tags,\n    **connection_kwars\n)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.broker_class","title":"broker_class class-attribute instance-attribute","text":"
broker_class = RB\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any\n) -> HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n]\n

Add an API message queue route.

PARAMETER DESCRIPTION path

The path of the route.

TYPE: Union[NameRequired, str]

*extra

Additional path segments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint function to be called for this route.

TYPE: Callable[P_HandlerParams, T_HandlerReturn]

dependencies

The dependencies required by the endpoint function.

TYPE: Sequence[Depends]

**broker_kwargs

Additional keyword arguments to be passed to the broker.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]

The handler call wrapper for the route.

Source code in faststream/broker/fastapi/router.py
def add_api_mq_route(\n    self,\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any,\n) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n    \"\"\"Add an API message queue route.\n\n    Args:\n        path: The path of the route.\n        *extra: Additional path segments.\n        endpoint: The endpoint function to be called for this route.\n        dependencies: The dependencies required by the endpoint function.\n        **broker_kwargs: Additional keyword arguments to be passed to the broker.\n\n    Returns:\n        The handler call wrapper for the route.\n\n    \"\"\"\n    route: StreamRoute[MsgType, P_HandlerParams, T_HandlerReturn] = StreamRoute(\n        path,\n        *extra,\n        endpoint=endpoint,\n        dependencies=dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        broker=self.broker,\n        **broker_kwargs,\n    )\n    self.routes.append(route)\n    return route.handler\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.publisher","title":"publisher","text":"
publisher(\n    channel: Union[Channel, PubSub, None] = None,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    dependencies: Sequence[Depends] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Any, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/fastapi.py
def subscriber(\n    self,\n    channel: Union[str, PubSub, None] = None,\n    *,\n    dependencies: Optional[Sequence[Depends]] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[AnyRedisDict, P_HandlerParams, T_HandlerReturn],\n]:\n    return super().subscriber(\n        path=channel,\n        dependencies=dependencies,\n        **broker_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/","title":"LogicRedisHandler","text":"","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler","title":"faststream.redis.handler.LogicRedisHandler","text":"
LogicRedisHandler(\n    *,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    channel: Optional[PubSub] = None,\n    list: Optional[ListSub] = None,\n    stream: Optional[StreamSub] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True\n)\n

Bases: AsyncHandler[AnyRedisDict]

Source code in faststream/redis/handler.py
def __init__(\n    self,\n    *,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # Redis info\n    channel: Optional[PubSub] = None,\n    list: Optional[ListSub] = None,\n    stream: Optional[StreamSub] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    self.channel = channel\n    self.list_sub = list\n    self.stream_sub = stream\n\n    self.subscription = None\n    self.task = None\n\n    self.last_id = stream.last_id if stream else \"$\"\n\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.channel","title":"channel instance-attribute","text":"
channel = channel\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.channel_name","title":"channel_name property","text":"
channel_name: str\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.last_id","title":"last_id instance-attribute","text":"
last_id = stream.last_id if stream else '$'\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.list_sub","title":"list_sub instance-attribute","text":"
list_sub = list\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.stream_sub","title":"stream_sub instance-attribute","text":"
stream_sub = stream\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.subscription","title":"subscription instance-attribute","text":"
subscription: Optional[RPubSub] = None\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.task","title":"task instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        AnyDict, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[AnyDict, RedisMessage]],\n    decoder: Optional[CustomDecoder[RedisMessage]],\n    filter: Filter[RedisMessage],\n    middlewares: Optional[\n        Sequence[Callable[[AnyDict], BaseMiddleware]]\n    ]\n) -> None\n
Source code in faststream/redis/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[AnyDict, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[AnyDict, RedisMessage]],\n    decoder: Optional[CustomDecoder[RedisMessage]],\n    filter: Filter[RedisMessage],\n    middlewares: Optional[Sequence[Callable[[AnyDict], BaseMiddleware]]],\n) -> None:\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, RedisParser.parse_message),\n        decoder=resolve_custom_func(decoder, RedisParser.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/redis/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.task is not None:\n        if not self.task.done():\n            self.task.cancel()\n        self.task = None\n\n    if self.subscription is not None:\n        await self.subscription.unsubscribe()\n        await self.subscription.aclose()  # type: ignore[attr-defined]\n        self.subscription = None\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(channel: Hashable) -> int\n
Source code in faststream/redis/handler.py
@staticmethod\ndef get_routing_hash(channel: Hashable) -> int:\n    return hash(channel)\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.start","title":"start async","text":"
start(client: Redis[bytes]) -> None\n
Source code in faststream/redis/handler.py
@override\nasync def start(self, client: \"Redis[bytes]\") -> None:  # type: ignore[override]\n    self.started = anyio.Event()\n\n    consume: Union[\n        Callable[[], Awaitable[Optional[AnyRedisDict]]],\n        Callable[[], Awaitable[Optional[Sequence[AnyRedisDict]]]],\n    ]\n    sleep: float\n\n    if (list_sub := self.list_sub) is not None:\n        sleep = list_sub.polling_interval\n        consume = partial(\n            self._consume_list_msg,\n            client=client,\n        )\n        self.started.set()\n\n    elif (channel := self.channel) is not None:\n        self.subscription = psub = client.pubsub()\n\n        if channel.pattern:\n            await psub.psubscribe(channel.name)\n        else:\n            await psub.subscribe(channel.name)\n\n        consume = partial(\n            psub.get_message,\n            ignore_subscribe_messages=True,\n            timeout=channel.polling_interval,\n        )\n        sleep = 0.01\n        self.started.set()\n\n    elif self.stream_sub is not None:\n        consume = partial(  # type: ignore[assignment]\n            self._consume_stream_msg,\n            client=client,\n        )\n        sleep = 0.01\n\n    else:\n        raise AssertionError(\"unreachable\")\n\n    await super().start()\n    self.task = asyncio.create_task(self._consume(consume, sleep))\n    # wait until Stream starts to consume\n    await anyio.sleep(0.01)\n    await self.started.wait()\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/","title":"AnyRedisDict","text":"","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict","title":"faststream.redis.message.AnyRedisDict","text":"

Bases: PubSubMessage

","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.channel","title":"channel instance-attribute","text":"
channel: bytes\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.data","title":"data instance-attribute","text":"
data: Union[bytes, List[bytes]]\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.message_id","title":"message_id instance-attribute","text":"
message_id: NotRequired[str]\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.message_ids","title":"message_ids instance-attribute","text":"
message_ids: NotRequired[List[str]]\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.pattern","title":"pattern instance-attribute","text":"
pattern: NotRequired[Optional[bytes]]\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.type","title":"type instance-attribute","text":"
type: Literal['stream', 'list', 'message', 'batch']\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/","title":"BatchMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage","title":"faststream.redis.message.BatchMessage","text":"

Bases: PubSubMessage

","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage.channel","title":"channel instance-attribute","text":"
channel: bytes\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage.data","title":"data instance-attribute","text":"
data: List[bytes]\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage.message_id","title":"message_id instance-attribute","text":"
message_id: NotRequired[str]\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage.message_ids","title":"message_ids instance-attribute","text":"
message_ids: NotRequired[List[str]]\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage.type","title":"type instance-attribute","text":"
type: Literal['batch']\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchRedisMessage/","title":"BatchRedisMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/BatchRedisMessage/#faststream.redis.message.BatchRedisMessage","title":"faststream.redis.message.BatchRedisMessage","text":"

Bases: RedisAckMixin[BatchMessage]

","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/","title":"OneMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage","title":"faststream.redis.message.OneMessage","text":"

Bases: PubSubMessage

","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.channel","title":"channel instance-attribute","text":"
channel: bytes\n
","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.data","title":"data instance-attribute","text":"
data: bytes\n
","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.message_id","title":"message_id instance-attribute","text":"
message_id: NotRequired[str]\n
","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.message_ids","title":"message_ids instance-attribute","text":"
message_ids: NotRequired[List[str]]\n
","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.pattern","title":"pattern instance-attribute","text":"
pattern: NotRequired[Optional[bytes]]\n
","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.type","title":"type instance-attribute","text":"
type: Literal['stream', 'list', 'message']\n
","boost":0.5},{"location":"api/faststream/redis/message/OneRedisMessage/","title":"OneRedisMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/OneRedisMessage/#faststream.redis.message.OneRedisMessage","title":"faststream.redis.message.OneRedisMessage","text":"

Bases: RedisAckMixin[OneMessage]

","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/","title":"PubSubMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage","title":"faststream.redis.message.PubSubMessage","text":"

Bases: TypedDict

","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage.channel","title":"channel instance-attribute","text":"
channel: bytes\n
","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage.data","title":"data instance-attribute","text":"
data: Union[bytes, List[bytes]]\n
","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage.message_id","title":"message_id instance-attribute","text":"
message_id: NotRequired[str]\n
","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage.message_ids","title":"message_ids instance-attribute","text":"
message_ids: NotRequired[List[str]]\n
","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage.type","title":"type instance-attribute","text":"
type: str\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/","title":"RedisAckMixin","text":"","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin","title":"faststream.redis.message.RedisAckMixin","text":"

Bases: StreamMessage[MsgType]

","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.ack","title":"ack async","text":"
ack(redis: Redis[bytes], **kwargs: Any) -> None\n
Source code in faststream/redis/message.py
@override\nasync def ack(  # type: ignore[override]\n    self,\n    redis: \"Redis[bytes]\",\n    **kwargs: Any,\n) -> None:\n    if (\n        not self.commited\n        and (ids := self.raw_message.get(\"message_ids\"))\n        and (handler := context.get_local(\"handler_\"))\n        and (stream := handler.stream_sub)\n        and (group := stream.group)\n    ):\n        await redis.xack(self.raw_message[\"channel\"], group, *ids)  # type: ignore[no-untyped-call]\n        await super().ack()\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.nack","title":"nack async","text":"
nack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def nack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.reject","title":"reject async","text":"
reject(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def reject(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisMessage/","title":"RedisMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/RedisMessage/#faststream.redis.message.RedisMessage","title":"faststream.redis.message.RedisMessage","text":"

Bases: RedisAckMixin[AnyRedisDict]

","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/","title":"RawMessage","text":"","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/#faststream.redis.parser.RawMessage","title":"faststream.redis.parser.RawMessage","text":"

Bases: BaseModel

","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/#faststream.redis.parser.RawMessage.data","title":"data instance-attribute","text":"
data: bytes\n
","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/#faststream.redis.parser.RawMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = Field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/#faststream.redis.parser.RawMessage.build","title":"build classmethod","text":"
build(\n    message: SendableMessage,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n) -> RawMessage\n
Source code in faststream/redis/parser.py
@classmethod\ndef build(\n    cls,\n    message: SendableMessage,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n) -> \"RawMessage\":\n    payload, content_type = encode_message(message)\n\n    headers_to_send = {\n        \"correlation_id\": correlation_id or str(uuid4()),\n    }\n\n    if content_type:\n        headers_to_send[\"content-type\"] = content_type\n\n    if reply_to:\n        headers_to_send[\"reply_to\"] = reply_to\n\n    if headers is not None:\n        headers_to_send.update(headers)\n\n    return cls(\n        data=payload,\n        headers=headers_to_send,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/#faststream.redis.parser.RawMessage.encode","title":"encode classmethod","text":"
encode(\n    message: SendableMessage,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n) -> str\n
Source code in faststream/redis/parser.py
@classmethod\ndef encode(\n    cls,\n    message: SendableMessage,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n) -> str:\n    return model_to_json(\n        cls.build(\n            message=message,\n            reply_to=reply_to,\n            headers=headers,\n            correlation_id=correlation_id,\n        )\n    )\n
","boost":0.5},{"location":"api/faststream/redis/parser/RedisParser/","title":"RedisParser","text":"","boost":0.5},{"location":"api/faststream/redis/parser/RedisParser/#faststream.redis.parser.RedisParser","title":"faststream.redis.parser.RedisParser","text":"","boost":0.5},{"location":"api/faststream/redis/parser/RedisParser/#faststream.redis.parser.RedisParser.decode_message","title":"decode_message async staticmethod","text":"
decode_message(msg: OneRedisMessage) -> DecodedMessage\n
Source code in faststream/redis/parser.py
@staticmethod\nasync def decode_message(\n    msg: OneRedisMessage,\n) -> DecodedMessage:\n    return decode_message(msg)\n
","boost":0.5},{"location":"api/faststream/redis/parser/RedisParser/#faststream.redis.parser.RedisParser.parse_message","title":"parse_message async classmethod","text":"
parse_message(\n    message: Union[OneMessage, BatchMessage]\n) -> Union[OneRedisMessage, BatchRedisMessage]\n
Source code in faststream/redis/parser.py
@classmethod\nasync def parse_message(\n    cls,\n    message: Union[OneMessage, BatchMessage],\n) -> Union[OneRedisMessage, BatchRedisMessage]:\n    id_ = str(uuid4())\n\n    if message[\"type\"] == \"batch\":\n        data = dump_json(\n            [cls.parse_one_msg(x)[0] for x in message[\"data\"]]\n        ).encode()\n\n        return BatchRedisMessage(\n            raw_message=message,\n            body=data,\n            content_type=\"application/json\",\n            message_id=id_,\n            correlation_id=id_,\n        )\n\n    else:\n        data, headers = cls.parse_one_msg(message[\"data\"])\n\n        channel = message.get(\"channel\", b\"\").decode()\n\n        handler = context.get_local(\"handler_\")\n        path_re: Optional[Pattern[str]]\n        path: AnyDict = {}\n        if (\n            handler\n            and handler.channel is not None\n            and (path_re := handler.channel.path_regex) is not None\n            and (match := path_re.match(channel)) is not None\n        ):\n            path = match.groupdict()\n\n        return OneRedisMessage(\n            raw_message=message,\n            body=data,\n            path=path,\n            headers=headers,\n            reply_to=headers.get(\"reply_to\", \"\"),\n            content_type=headers.get(\"content-type\", \"\"),\n            message_id=message.get(\"message_id\", id_),\n            correlation_id=headers.get(\"correlation_id\", id_),\n        )\n
","boost":0.5},{"location":"api/faststream/redis/parser/RedisParser/#faststream.redis.parser.RedisParser.parse_one_msg","title":"parse_one_msg staticmethod","text":"
parse_one_msg(raw_data: bytes) -> Tuple[bytes, AnyDict]\n
Source code in faststream/redis/parser.py
@staticmethod\ndef parse_one_msg(raw_data: bytes) -> Tuple[bytes, AnyDict]:\n    try:\n        obj = model_parse(RawMessage, raw_data)\n    except Exception:\n        # Raw Redis message format\n        data = raw_data\n        headers: AnyDict = {}\n    else:\n        # FastStream message format\n        data = obj.data\n        headers = obj.headers\n\n    return data, headers\n
","boost":0.5},{"location":"api/faststream/redis/producer/RedisFastProducer/","title":"RedisFastProducer","text":"","boost":0.5},{"location":"api/faststream/redis/producer/RedisFastProducer/#faststream.redis.producer.RedisFastProducer","title":"faststream.redis.producer.RedisFastProducer","text":"
RedisFastProducer(\n    connection: Redis[bytes],\n    parser: Union[\n        None,\n        AsyncCustomParser[OneMessage, OneRedisMessage],\n        AsyncCustomParser[BatchMessage, BatchRedisMessage],\n    ],\n    decoder: Union[\n        None,\n        AsyncCustomDecoder[OneRedisMessage],\n        AsyncCustomDecoder[BatchRedisMessage],\n    ],\n)\n
Source code in faststream/redis/producer.py
def __init__(\n    self,\n    connection: \"Redis[bytes]\",\n    parser: Union[\n        None,\n        AsyncCustomParser[OneMessage, OneRedisMessage],\n        AsyncCustomParser[BatchMessage, BatchRedisMessage],\n    ],\n    decoder: Union[\n        None,\n        AsyncCustomDecoder[OneRedisMessage],\n        AsyncCustomDecoder[BatchRedisMessage],\n    ],\n) -> None:\n    self._connection = connection\n    self._parser = resolve_custom_func(\n        parser,  # type: ignore[arg-type,assignment]\n        RedisParser.parse_message,\n    )\n    self._decoder = resolve_custom_func(decoder, RedisParser.decode_message)\n
","boost":0.5},{"location":"api/faststream/redis/producer/RedisFastProducer/#faststream.redis.producer.RedisFastProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    channel: Optional[str] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Optional[str] = None,\n    stream: Optional[str] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/producer.py
async def publish(\n    self,\n    message: SendableMessage,\n    channel: Optional[str] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Optional[str] = None,\n    stream: Optional[str] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    if not any((channel, list, stream)):\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    psub: Optional[PubSub] = None\n    if rpc is True:\n        if reply_to:\n            raise WRONG_PUBLISH_ARGS\n\n        reply_to = str(uuid4())\n        psub = self._connection.pubsub()\n        await psub.subscribe(reply_to)\n\n    msg = RawMessage.encode(\n        message=message,\n        reply_to=reply_to,\n        headers=headers,\n        correlation_id=correlation_id,\n    )\n\n    if channel is not None:\n        await self._connection.publish(channel, msg)\n    elif list is not None:\n        await self._connection.rpush(list, msg)\n    elif stream is not None:\n        await self._connection.xadd(stream, {DATA_KEY: msg})\n    else:\n        raise AssertionError(\"unreachable\")\n\n    if psub is None:\n        return None\n\n    else:\n        m = None\n        with timeout_scope(rpc_timeout, raise_timeout):\n            # skip subscribe message\n            await psub.get_message(\n                ignore_subscribe_messages=True,\n                timeout=rpc_timeout or 0.0,\n            )\n\n            # get real response\n            m = await psub.get_message(\n                ignore_subscribe_messages=True,\n                timeout=rpc_timeout or 0.0,\n            )\n\n        await psub.unsubscribe()\n        await psub.aclose()  # type: ignore[attr-defined]\n\n        if m is None:\n            if raise_timeout:\n                raise TimeoutError()\n            else:\n                return None\n        else:\n            return await self._decoder(await self._parser(m))\n
","boost":0.5},{"location":"api/faststream/redis/producer/RedisFastProducer/#faststream.redis.producer.RedisFastProducer.publish_batch","title":"publish_batch async","text":"
publish_batch(*msgs: SendableMessage, list: str) -> None\n
Source code in faststream/redis/producer.py
async def publish_batch(\n    self,\n    *msgs: SendableMessage,\n    list: str,\n) -> None:\n    batch = (encode_message(msg)[0] for msg in msgs)\n    await self._connection.rpush(list, *batch)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/","title":"LogicPublisher","text":"","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher","title":"faststream.redis.publisher.LogicPublisher dataclass","text":"

Bases: BasePublisher[AnyRedisDict]

","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.channel","title":"channel class-attribute instance-attribute","text":"
channel: Optional[PubSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.channel_name","title":"channel_name property","text":"
channel_name: str\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[AnyDict] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.list","title":"list class-attribute instance-attribute","text":"
list: Optional[ListSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.stream","title":"stream class-attribute instance-attribute","text":"
stream: Optional[StreamSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    channel: Union[str, PubSub, None] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage,\n    channel: Union[str, PubSub, None] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n\n    channel = PubSub.validate(channel or self.channel)\n    list = ListSub.validate(list or self.list)\n    stream = StreamSub.validate(stream or self.stream)\n\n    assert any(\n        (channel, list, stream)\n    ), \"You have to specify outgoing channel\"  # nosec B101\n\n    headers_to_send = (self.headers or {}).copy()\n    if headers is not None:\n        headers_to_send.update(headers)\n\n    if getattr(list, \"batch\", False):\n        await self._producer.publish_batch(\n            *message,\n            list=list.name,  # type: ignore[union-attr]\n        )\n        return None\n\n    else:\n        return await self._producer.publish(\n            message=message,\n            channel=getattr(channel, \"name\", None),\n            list=getattr(list, \"name\", None),\n            stream=getattr(stream, \"name\", None),\n            reply_to=reply_to or self.reply_to,\n            correlation_id=correlation_id,\n            headers=headers_to_send,\n            rpc=rpc,\n            rpc_timeout=rpc_timeout,\n            raise_timeout=raise_timeout,\n        )\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/","title":"RedisRouter","text":"","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter","title":"faststream.redis.router.RedisRouter","text":"
RedisRouter(\n    prefix: str = \"\",\n    handlers: Sequence[RedisRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    include_in_schema: bool = True\n)\n

Bases: RedisRouter

Source code in faststream/redis/router.py
            publisher.list, update={\"name\": prefix + publisher.list.name}\n        )\n    elif publisher.stream is not None:\n        publisher.stream = model_copy(\n            publisher.stream, update={\"name\": prefix + publisher.stream.name}\n        )\n    else:\n        raise AssertionError(\"unreachable\")\n    return publisher\n\n@override\ndef publisher(  # type: ignore[override]\n    self,\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.publisher","title":"publisher","text":"
publisher(\n    channel: Union[str, PubSub, None] = None,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/redis/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    channel: Union[str, PubSub, None] = None,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    if not any((stream, list, channel)):\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            channel=PubSub.validate(channel),\n            list=ListSub.validate(list),\n            stream=StreamSub.validate(stream),\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[str, PubSub, None] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Any, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/router.py
) -> Publisher:\n    if not any((stream, list, channel)):\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            channel=PubSub.validate(channel),\n            list=ListSub.validate(list),\n            stream=StreamSub.validate(stream),\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/","title":"ListSub","text":"","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub","title":"faststream.redis.schemas.ListSub","text":"
ListSub(\n    channel: str,\n    batch: bool = False,\n    max_records: PositiveInt = 10,\n    polling_interval: PositiveFloat = 0.1,\n)\n

Bases: NameRequired

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    channel: str,\n    batch: bool = False,\n    max_records: PositiveInt = 10,\n    polling_interval: PositiveFloat = 0.1,\n) -> None:\n    super().__init__(\n        name=channel,\n        batch=batch,\n        max_records=max_records,\n        polling_interval=polling_interval,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.max_records","title":"max_records class-attribute instance-attribute","text":"
max_records: PositiveInt = 10\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: PositiveFloat = 0.1\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.records","title":"records property","text":"
records: Optional[PositiveInt]\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/","title":"PubSub","text":"","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub","title":"faststream.redis.schemas.PubSub","text":"
PubSub(\n    channel: str,\n    pattern: bool = False,\n    polling_interval: PositiveFloat = 1.0,\n)\n

Bases: NameRequired

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    channel: str,\n    pattern: bool = False,\n    polling_interval: PositiveFloat = 1.0,\n) -> None:\n    reg, path = compile_path(channel, replace_symbol=\"*\")\n\n    if reg is not None:\n        pattern = True\n\n    super().__init__(\n        name=path,\n        path_regex=reg,\n        pattern=pattern,\n        polling_interval=polling_interval,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.last_id","title":"last_id class-attribute instance-attribute","text":"
last_id: str = '$'\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'arbitrary_types_allowed': True}\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.path_regex","title":"path_regex class-attribute instance-attribute","text":"
path_regex: Optional[Pattern[str]] = None\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.pattern","title":"pattern class-attribute instance-attribute","text":"
pattern: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: PositiveFloat = 1.0\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.Config.arbitrary_types_allowed","title":"arbitrary_types_allowed class-attribute instance-attribute","text":"
arbitrary_types_allowed = True\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/","title":"StreamSub","text":"","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub","title":"faststream.redis.schemas.StreamSub","text":"
StreamSub(\n    stream: str,\n    polling_interval: Optional[PositiveInt] = 100,\n    group: Optional[str] = None,\n    consumer: Optional[str] = None,\n    batch: bool = False,\n    no_ack: bool = False,\n    last_id: Optional[str] = None,\n)\n

Bases: NameRequired

Redis Stream subscriber parameters

PARAMETER DESCRIPTION stream

(str): Redis Stream name.

TYPE: str

polling_interval

(int:ms | None): wait message block.

TYPE: Optional[PositiveInt] DEFAULT: 100

group

(str | None): consumer group name.

TYPE: Optional[str] DEFAULT: None

consumer

(str | None): consumer name.

TYPE: Optional[str] DEFAULT: None

batch

(bool): consume messages in batches.

TYPE: bool DEFAULT: False

no_ack

(bool): do not add message to PEL.

TYPE: bool DEFAULT: False

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    stream: str,\n    polling_interval: Optional[PositiveInt] = 100,\n    group: Optional[str] = None,\n    consumer: Optional[str] = None,\n    batch: bool = False,\n    no_ack: bool = False,\n    last_id: Optional[str] = None,\n) -> None:\n    \"\"\"\n    Redis Stream subscriber parameters\n\n    Args:\n        stream: (str): Redis Stream name.\n        polling_interval: (int:ms | None): wait message block.\n        group: (str | None): consumer group name.\n        consumer: (str | None): consumer name.\n        batch: (bool): consume messages in batches.\n        no_ack: (bool): do not add message to PEL.\n    \"\"\"\n    if (group and not consumer) or (not group and consumer):\n        raise ValueError(\"You should specify `group` and `consumer` both\")\n\n    if group and consumer:\n        msg: Optional[str] = None\n\n        if last_id:\n            msg = \"`last_id` has no effect with consumer group\"\n\n        if no_ack:\n            msg = \"`no_ack` has no effect with consumer group\"\n\n        if msg:\n            warnings.warn(\n                message=msg,\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n    super().__init__(\n        name=stream,\n        group=group,\n        consumer=consumer,\n        polling_interval=polling_interval,\n        batch=batch,\n        no_ack=no_ack,\n        last_id=last_id or \"$\",\n    )\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.consumer","title":"consumer class-attribute instance-attribute","text":"
consumer: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.group","title":"group class-attribute instance-attribute","text":"
group: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.last_id","title":"last_id class-attribute instance-attribute","text":"
last_id: str = '$'\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.no_ack","title":"no_ack class-attribute instance-attribute","text":"
no_ack: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: Optional[PositiveInt] = Field(\n    default=100, description=\"ms\"\n)\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/security/parse_security/","title":"parse_security","text":"","boost":0.5},{"location":"api/faststream/redis/security/parse_security/#faststream.redis.security.parse_security","title":"faststream.redis.security.parse_security","text":"
parse_security(security: Optional[BaseSecurity]) -> AnyDict\n
Source code in faststream/redis/security.py
def parse_security(security: Optional[BaseSecurity]) -> AnyDict:\n    if security is None:\n        return {}\n    elif isinstance(security, SASLPlaintext):\n        return _parse_sasl_plaintext(security)\n    elif isinstance(security, BaseSecurity):\n        return _parse_base_security(security)\n    else:\n        raise NotImplementedError(f\"RedisBroker does not support {type(security)}\")\n
","boost":0.5},{"location":"api/faststream/redis/shared/logging/RedisLoggingMixin/","title":"RedisLoggingMixin","text":"","boost":0.5},{"location":"api/faststream/redis/shared/logging/RedisLoggingMixin/#faststream.redis.shared.logging.RedisLoggingMixin","title":"faststream.redis.shared.logging.RedisLoggingMixin","text":"
RedisLoggingMixin(\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any\n)\n

Bases: LoggingMixin

Source code in faststream/redis/shared/logging.py
def __init__(\n    self,\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any,\n) -> None:\n    super().__init__(\n        *args,\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n        **kwargs,\n    )\n    self._message_id_ln = 15\n    self._max_channel_name = 4\n
","boost":0.5},{"location":"api/faststream/redis/shared/logging/RedisLoggingMixin/#faststream.redis.shared.logging.RedisLoggingMixin.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/redis/shared/logging/RedisLoggingMixin/#faststream.redis.shared.logging.RedisLoggingMixin.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/redis/shared/logging/RedisLoggingMixin/#faststream.redis.shared.logging.RedisLoggingMixin.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRoute/","title":"RedisRoute","text":"","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/","title":"RedisRouter","text":"","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter","title":"faststream.redis.shared.router.RedisRouter","text":"
RedisRouter(\n    prefix: str = \"\",\n    handlers: Sequence[\n        RedisRoute[AnyRedisDict, SendableMessage]\n    ] = (),\n    **kwargs: Any\n)\n

Bases: BrokerRouter[int, AnyRedisDict]

Source code in faststream/redis/shared/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[RedisRoute[AnyRedisDict, SendableMessage]] = (),\n    **kwargs: Any,\n) -> None:\n    for h in handlers:\n        if not (channel := h.kwargs.pop(\"channel\", None)):\n            if list := h.kwargs.pop(\"list\", None):\n                h.kwargs[\"list\"] = prefix + list\n                continue\n\n            elif stream := h.kwargs.pop(\"stream\", None):\n                h.kwargs[\"stream\"] = prefix + stream\n                continue\n\n            channel, h.args = h.args[0], h.args[1:]\n\n        h.args = (prefix + channel, *h.args)\n\n    super().__init__(prefix, handlers, **kwargs)\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        AnyRedisDict, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/shared/router.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[AnyRedisDict, P_HandlerParams, T_HandlerReturn],\n]:\n    channel = PubSub.validate(channel)\n    list = ListSub.validate(list)\n    stream = StreamSub.validate(stream)\n\n    return self._wrap_subscriber(\n        channel=model_copy(channel, update={\"name\": self.prefix + channel.name})\n        if channel\n        else None,\n        list=model_copy(list, update={\"name\": self.prefix + list.name})\n        if list\n        else None,\n        stream=model_copy(stream, update={\"name\": self.prefix + stream.name})\n        if stream\n        else None,\n        **broker_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/test/FakeProducer/","title":"FakeProducer","text":"","boost":0.5},{"location":"api/faststream/redis/test/FakeProducer/#faststream.redis.test.FakeProducer","title":"faststream.redis.test.FakeProducer","text":"
FakeProducer(broker: RedisBroker)\n

Bases: RedisFastProducer

Source code in faststream/redis/test.py
def __init__(self, broker: RedisBroker) -> None:\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/redis/test/FakeProducer/#faststream.redis.test.FakeProducer.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/redis/test/FakeProducer/#faststream.redis.test.FakeProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    channel: Optional[str] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Optional[str] = None,\n    stream: Optional[str] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/test.py
@override\nasync def publish(\n    self,\n    message: SendableMessage,\n    channel: Optional[str] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Optional[str] = None,\n    stream: Optional[str] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    any_of = channel or list or stream\n    if any_of is None:\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        call = False\n        batch = False\n\n        if channel and (ch := handler.channel) is not None:\n            call = bool(\n                (not ch.pattern and ch.name == channel)\n                or (\n                    ch.pattern\n                    and re.match(\n                        ch.name.replace(\".\", \"\\\\.\").replace(\"*\", \".*\"),\n                        channel,\n                    )\n                )\n            )\n\n        if list and (ls := handler.list_sub) is not None:\n            batch = ls.batch\n            call = list == ls.name\n\n        if stream and (st := handler.stream_sub) is not None:\n            batch = st.batch\n            call = stream == st.name\n\n        if call:\n            r = await call_handler(\n                handler=handler,\n                message=build_message(\n                    message=[message] if batch else message,\n                    channel=any_of,\n                    headers=headers,\n                    correlation_id=correlation_id,\n                    reply_to=reply_to,\n                ),\n                rpc=rpc,\n                rpc_timeout=rpc_timeout,\n                raise_timeout=raise_timeout,\n            )\n\n            if rpc:  # pragma: no branch\n                return r\n\n    return None\n
","boost":0.5},{"location":"api/faststream/redis/test/FakeProducer/#faststream.redis.test.FakeProducer.publish_batch","title":"publish_batch async","text":"
publish_batch(*msgs: SendableMessage, list: str) -> None\n
Source code in faststream/redis/test.py
async def publish_batch(\n    self,\n    *msgs: SendableMessage,\n    list: str,\n) -> None:\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        if handler.list_sub and handler.list_sub.name == list:\n            await call_handler(\n                handler=handler,\n                message=build_message(\n                    message=msgs,\n                    channel=list,\n                ),\n            )\n\n    return None\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/","title":"TestRedisBroker","text":"","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker","title":"faststream.redis.test.TestRedisBroker","text":"
TestRedisBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[RedisBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: RedisBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/redis/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: RedisBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(\n        channel=publisher.channel,\n        list=publisher.list,\n        stream=publisher.stream,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: RedisBroker, publisher: Any\n) -> None\n
Source code in faststream/redis/test.py
@staticmethod\ndef patch_publisher(\n    broker: RedisBroker,\n    publisher: Any,\n) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: RedisBroker, publisher: Publisher\n) -> None\n
Source code in faststream/redis/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: RedisBroker,\n    publisher: Publisher,\n) -> None:\n    any_of = publisher.channel or publisher.list or publisher.stream\n    assert any_of  # nosec B101\n    broker.handlers.pop(Handler.get_routing_hash(any_of), None)\n
","boost":0.5},{"location":"api/faststream/redis/test/build_message/","title":"build_message","text":"","boost":0.5},{"location":"api/faststream/redis/test/build_message/#faststream.redis.test.build_message","title":"faststream.redis.test.build_message","text":"
build_message(\n    message: SendableMessage,\n    channel: str,\n    *,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[AnyDict] = None\n) -> AnyRedisDict\n
Source code in faststream/redis/test.py
def build_message(\n    message: SendableMessage,\n    channel: str,\n    *,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[AnyDict] = None,\n) -> AnyRedisDict:\n    data = RawMessage.encode(\n        message=message,\n        reply_to=reply_to,\n        headers=headers,\n        correlation_id=correlation_id,\n    )\n    return AnyRedisDict(\n        channel=channel.encode(),\n        data=data.encode(),\n        type=\"message\",\n    )\n
","boost":0.5},{"location":"api/faststream/security/BaseSecurity/","title":"BaseSecurity","text":"","boost":0.5},{"location":"api/faststream/security/BaseSecurity/#faststream.security.BaseSecurity","title":"faststream.security.BaseSecurity","text":"
BaseSecurity(\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Base class for defining security configurations.

This class provides a base for defining security configurations for communication with a broker. It allows setting SSL encryption and provides methods to retrieve security requirements and schemas.

PARAMETER DESCRIPTION ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements in the form of a list of dictionaries.

get_schema

Get the security schema as a dictionary.

Source code in faststream/security.py
def __init__(\n    self,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    if ssl_context is not None:\n        use_ssl = True\n\n    self.use_ssl = use_ssl\n    self.ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/security/BaseSecurity/#faststream.security.BaseSecurity.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/security/BaseSecurity/#faststream.security.BaseSecurity.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/security/BaseSecurity/#faststream.security.BaseSecurity.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return []\n
","boost":0.5},{"location":"api/faststream/security/BaseSecurity/#faststream.security.BaseSecurity.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {}\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/","title":"SASLPlaintext","text":"","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext","title":"faststream.security.SASLPlaintext","text":"
SASLPlaintext(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/PLAINTEXT authentication.

This class defines security configuration for SASL/PLAINTEXT authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/PLAINTEXT authentication.

get_schema

Get the security schema for SASL/PLAINTEXT authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/PLAINTEXT authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/PLAINTEXT authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"user-password\": []}]\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/PLAINTEXT authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/PLAINTEXT authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"user-password\": {\"type\": \"userPassword\"}}\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/","title":"SASLScram256","text":"","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256","title":"faststream.security.SASLScram256","text":"
SASLScram256(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/SCRAM-SHA-256 authentication.

This class defines security configuration for SASL/SCRAM-SHA-256 authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/SCRAM-SHA-256 authentication.

get_schema

Get the security schema for SASL/SCRAM-SHA-256 authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/SCRAM-SHA-256 authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/SCRAM-SHA-256 authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"scram256\": []}]\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/SCRAM-SHA-256 authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/SCRAM-SHA-256 authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"scram256\": {\"type\": \"scramSha256\"}}\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/","title":"SASLScram512","text":"","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512","title":"faststream.security.SASLScram512","text":"
SASLScram512(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/SCRAM-SHA-512 authentication.

This class defines security configuration for SASL/SCRAM-SHA-512 authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/SCRAM-SHA-512 authentication.

get_schema

Get the security schema for SASL/SCRAM-SHA-512 authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/SCRAM-SHA-512 authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/SCRAM-SHA-512 authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"scram512\": []}]\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/SCRAM-SHA-512 authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/SCRAM-SHA-512 authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"scram512\": {\"type\": \"scramSha512\"}}\n
","boost":0.5},{"location":"api/faststream/utils/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/utils/Context/#faststream.utils.Context","title":"faststream.utils.Context","text":"
Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n    )\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/","title":"ContextRepo","text":"","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo","title":"faststream.utils.ContextRepo","text":"
ContextRepo()\n

Bases: Singleton

A class to represent a context repository.

METHOD DESCRIPTION __init__

initializes the ContextRepo object

set_global

sets a global context variable

reset_global

resets a global context variable

set_local

sets a local context variable

reset_local

resets a local context variable

get_local

gets the value of a local context variable

clear

clears the global and scope context

get

gets the value of a context variable

__getattr__

gets the value of a context variable using attribute access

context

gets the current context as a dictionary

scope

creates a context scope for a specific key and value

Initialize the class.

Source code in faststream/utils/context/main.py
def __init__(self) -> None:\n    \"\"\"Initialize the class.\n\n    Attributes:\n        _global_context : a dictionary representing the global context\n        _scope_context : a dictionary representing the scope context\n    \"\"\"\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.context","title":"context property","text":"
context: AnyDict\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.clear","title":"clear","text":"
clear() -> None\n
Source code in faststream/utils/context/main.py
def clear(self) -> None:\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.get","title":"get","text":"
get(key: str, default: Any = None) -> Any\n

Get the value associated with a key.

PARAMETER DESCRIPTION key

The key to retrieve the value for.

TYPE: str

RETURNS DESCRIPTION Any

The value associated with the key.

Source code in faststream/utils/context/main.py
def get(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value associated with a key.\n\n    Args:\n        key: The key to retrieve the value for.\n\n    Returns:\n        The value associated with the key.\n    \"\"\"\n    return self._global_context.get(key, self.get_local(key, default))\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.get_local","title":"get_local","text":"
get_local(key: str, default: Any = None) -> Any\n

Get the value of a local variable.

PARAMETER DESCRIPTION key

The key of the local variable to retrieve.

TYPE: str

RETURNS DESCRIPTION Any

The value of the local variable.

Source code in faststream/utils/context/main.py
def get_local(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value of a local variable.\n\n    Args:\n        key: The key of the local variable to retrieve.\n\n    Returns:\n        The value of the local variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is not None:  # pragma: no branch\n        return context_var.get()\n    else:\n        return default\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.reset_global","title":"reset_global","text":"
reset_global(key: str) -> None\n

Resets a key in the global context.

PARAMETER DESCRIPTION key

The key to reset in the global context.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_global(self, key: str) -> None:\n    \"\"\"Resets a key in the global context.\n\n    Args:\n        key (str): The key to reset in the global context.\n\n    Returns:\n        None\n    \"\"\"\n    self._global_context.pop(key, None)\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.reset_local","title":"reset_local","text":"
reset_local(key: str, tag: Token[Any]) -> None\n

Resets the local context for a given key.

PARAMETER DESCRIPTION key

The key to reset the local context for.

TYPE: str

tag

The tag associated with the local context.

TYPE: Token[Any]

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_local(self, key: str, tag: \"Token[Any]\") -> None:\n    \"\"\"Resets the local context for a given key.\n\n    Args:\n        key (str): The key to reset the local context for.\n        tag (Token[Any]): The tag associated with the local context.\n\n    Returns:\n        None\n    \"\"\"\n    self._scope_context[key].reset(tag)\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.resolve","title":"resolve","text":"
resolve(argument: str) -> Any\n

Resolve the context of an argument.

PARAMETER DESCRIPTION argument

A string representing the argument.

TYPE: str

RETURNS DESCRIPTION Any

The resolved context of the argument.

RAISES DESCRIPTION AttributeError

If the attribute does not exist in the context.

Source code in faststream/utils/context/main.py
def resolve(self, argument: str) -> Any:\n    \"\"\"Resolve the context of an argument.\n\n    Args:\n        argument: A string representing the argument.\n\n    Returns:\n        The resolved context of the argument.\n\n    Raises:\n        AttributeError: If the attribute does not exist in the context.\n    \"\"\"\n    first, *keys = argument.split(\".\")\n\n    if (v := self.get(first, _empty)) is _empty:\n        raise KeyError(f\"`{self.context}` does not contains `{first}` key\")\n\n    for i in keys:\n        if isinstance(v, Mapping):\n            v = v[i]\n        else:\n            v = getattr(v, i)\n    return v\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.scope","title":"scope","text":"
scope(key: str, value: Any) -> Iterator[None]\n

Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.

PARAMETER DESCRIPTION key

The key of the local variable

TYPE: str

value

The value to set the local variable to

TYPE: Any

YIELDS DESCRIPTION Iterator[None]

None

RETURNS DESCRIPTION Iterator[None]

An iterator that yields None

Source code in faststream/utils/context/main.py
@contextmanager\ndef scope(self, key: str, value: Any) -> Iterator[None]:\n    \"\"\"Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.\n\n    Args:\n        key: The key of the local variable\n        value: The value to set the local variable to\n\n    Yields:\n        None\n\n    Returns:\n        An iterator that yields None\n    \"\"\"\n    token = self.set_local(key, value)\n    try:\n        yield\n    finally:\n        self.reset_local(key, token)\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.set_global","title":"set_global","text":"
set_global(key: str, v: Any) -> None\n

Sets a value in the global context.

PARAMETER DESCRIPTION key

The key to set in the global context.

TYPE: str

v

The value to set.

TYPE: Any

RETURNS DESCRIPTION None

None.

Source code in faststream/utils/context/main.py
def set_global(self, key: str, v: Any) -> None:\n    \"\"\"Sets a value in the global context.\n\n    Args:\n        key: The key to set in the global context.\n        v: The value to set.\n\n    Returns:\n        None.\n    \"\"\"\n    self._global_context[key] = v\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.set_local","title":"set_local","text":"
set_local(key: str, value: T) -> Token[T]\n

Set a local context variable.

PARAMETER DESCRIPTION key

The key for the context variable.

TYPE: str

value

The value to set for the context variable.

TYPE: T

RETURNS DESCRIPTION Token[T]

Token[T]: A token representing the context variable.

Source code in faststream/utils/context/main.py
def set_local(self, key: str, value: T) -> \"Token[T]\":\n    \"\"\"Set a local context variable.\n\n    Args:\n        key (str): The key for the context variable.\n        value (T): The value to set for the context variable.\n\n    Returns:\n        Token[T]: A token representing the context variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is None:\n        context_var = ContextVar(key, default=None)\n        self._scope_context[key] = context_var\n    return context_var.set(value)\n
","boost":0.5},{"location":"api/faststream/utils/Depends/","title":"Depends","text":"","boost":0.5},{"location":"api/faststream/utils/Depends/#fast_depends.use.Depends","title":"fast_depends.use.Depends","text":"
Depends(\n    dependency: Callable[P, T],\n    *,\n    use_cache: bool = True,\n    cast: bool = True\n) -> Any\n
Source code in fast_depends/use.py
def Depends(\n    dependency: Callable[P, T],\n    *,\n    use_cache: bool = True,\n    cast: bool = True,\n) -> Any:\n    return model.Depends(\n        dependency=dependency,\n        use_cache=use_cache,\n        cast=cast,\n    )\n
","boost":0.5},{"location":"api/faststream/utils/Header/","title":"Header","text":"","boost":0.5},{"location":"api/faststream/utils/Header/#faststream.utils.Header","title":"faststream.utils.Header","text":"
Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.headers.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/","title":"NoCast","text":"","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast","title":"faststream.utils.NoCast","text":"
NoCast()\n

Bases: CustomField

A class that represents a custom field without casting.

METHOD DESCRIPTION __init__

Initializes the NoCast object.

use

Returns the provided keyword arguments as a dictionary.

Source code in faststream/utils/no_cast.py
def __init__(self) -> None:\n    super().__init__(cast=False)\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast.cast","title":"cast instance-attribute","text":"
cast: bool = cast\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast.param_name","title":"param_name instance-attribute","text":"
param_name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast.required","title":"required instance-attribute","text":"
required: bool = required\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast.set_param_name","title":"set_param_name","text":"
set_param_name(name: str) -> Cls\n
Source code in fast_depends/library/model.py
def set_param_name(self: Cls, name: str) -> Cls:\n    self.param_name = name\n    return self\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast.use","title":"use","text":"
use(**kwargs: Any) -> AnyDict\n

Return a dictionary containing the keyword arguments passed to the function.

PARAMETER DESCRIPTION **kwargs

Keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION AnyDict

Dictionary containing the keyword arguments

Source code in faststream/utils/no_cast.py
def use(self, **kwargs: Any) -> AnyDict:\n    \"\"\"Return a dictionary containing the keyword arguments passed to the function.\n\n    Args:\n        **kwargs: Keyword arguments\n\n    Returns:\n        Dictionary containing the keyword arguments\n    \"\"\"\n    return kwargs\n
","boost":0.5},{"location":"api/faststream/utils/Path/","title":"Path","text":"","boost":0.5},{"location":"api/faststream/utils/Path/#faststream.utils.Path","title":"faststream.utils.Path","text":"
Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.path.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/apply_types/","title":"apply_types","text":"","boost":0.5},{"location":"api/faststream/utils/apply_types/#fast_depends.use.inject","title":"fast_depends.use.inject","text":"
inject(\n    func: Optional[Callable[P, T]] = None,\n    *,\n    cast: bool = True,\n    extra_dependencies: Sequence[model.Depends] = (),\n    pydantic_config: Optional[ConfigDict] = None,\n    dependency_overrides_provider: Optional[\n        Any\n    ] = dependency_provider,\n    wrap_model: Callable[\n        [CallModel[P, T]], CallModel[P, T]\n    ] = lambda: x\n) -> Union[Callable[P, T], _InjectWrapper[P, T]]\n
Source code in fast_depends/use.py
def inject(\n    func: Optional[Callable[P, T]] = None,\n    *,\n    cast: bool = True,\n    extra_dependencies: Sequence[model.Depends] = (),\n    pydantic_config: Optional[ConfigDict] = None,\n    dependency_overrides_provider: Optional[Any] = dependency_provider,\n    wrap_model: Callable[[CallModel[P, T]], CallModel[P, T]] = lambda x: x,\n) -> Union[Callable[P, T], _InjectWrapper[P, T],]:\n    decorator = _wrap_inject(\n        dependency_overrides_provider=dependency_overrides_provider,\n        wrap_model=wrap_model,\n        extra_dependencies=extra_dependencies,\n        cast=cast,\n        pydantic_config=pydantic_config,\n    )\n\n    if func is None:\n        return decorator\n\n    else:\n        return decorator(func)\n
","boost":0.5},{"location":"api/faststream/utils/ast/find_ast_node/","title":"find_ast_node","text":"","boost":0.5},{"location":"api/faststream/utils/ast/find_ast_node/#faststream.utils.ast.find_ast_node","title":"faststream.utils.ast.find_ast_node","text":"
find_ast_node(\n    module: ast.Module, lineno: Optional[int]\n) -> Optional[ast.AST]\n
Source code in faststream/utils/ast.py
def find_ast_node(module: ast.Module, lineno: Optional[int]) -> Optional[ast.AST]:\n    if lineno is not None:  # pragma: no branch\n        for i in getattr(module, \"body\", ()):\n            if i.lineno == lineno:\n                return cast(ast.AST, i)\n\n            r = find_ast_node(i, lineno)\n            if r is not None:\n                return r\n\n    return None\n
","boost":0.5},{"location":"api/faststream/utils/ast/find_withitems/","title":"find_withitems","text":"","boost":0.5},{"location":"api/faststream/utils/ast/find_withitems/#faststream.utils.ast.find_withitems","title":"faststream.utils.ast.find_withitems","text":"
find_withitems(\n    node: Union[ast.With, ast.AsyncWith]\n) -> Iterator[ast.withitem]\n
Source code in faststream/utils/ast.py
def find_withitems(node: Union[ast.With, ast.AsyncWith]) -> Iterator[ast.withitem]:\n    if isinstance(node, (ast.With, ast.AsyncWith)):\n        yield from node.items\n\n    for i in getattr(node, \"body\", ()):\n        yield from find_withitems(i)\n
","boost":0.5},{"location":"api/faststream/utils/ast/get_withitem_calls/","title":"get_withitem_calls","text":"","boost":0.5},{"location":"api/faststream/utils/ast/get_withitem_calls/#faststream.utils.ast.get_withitem_calls","title":"faststream.utils.ast.get_withitem_calls","text":"
get_withitem_calls(\n    node: Union[ast.With, ast.AsyncWith]\n) -> List[str]\n
Source code in faststream/utils/ast.py
def get_withitem_calls(node: Union[ast.With, ast.AsyncWith]) -> List[str]:\n    return [\n        id\n        for i in find_withitems(node)\n        if (id := getattr(i.context_expr.func, \"id\", None))  # type: ignore[attr-defined]\n    ]\n
","boost":0.5},{"location":"api/faststream/utils/ast/is_contains_context_name/","title":"is_contains_context_name","text":"","boost":0.5},{"location":"api/faststream/utils/ast/is_contains_context_name/#faststream.utils.ast.is_contains_context_name","title":"faststream.utils.ast.is_contains_context_name","text":"
is_contains_context_name(scip_name: str, name: str) -> bool\n
Source code in faststream/utils/ast.py
def is_contains_context_name(scip_name: str, name: str) -> bool:\n    stack = traceback.extract_stack()[-3]\n    tree = read_source_ast(stack.filename)\n    node = cast(Union[ast.With, ast.AsyncWith], find_ast_node(tree, stack.lineno))\n    context_calls = get_withitem_calls(node)\n\n    try:\n        pos = context_calls.index(scip_name)\n    except ValueError:\n        pos = 1\n\n    return name in context_calls[pos:]\n
","boost":0.5},{"location":"api/faststream/utils/classes/Singleton/","title":"Singleton","text":"","boost":0.5},{"location":"api/faststream/utils/classes/Singleton/#faststream.utils.classes.Singleton","title":"faststream.utils.classes.Singleton","text":"

A class to implement the Singleton design pattern.

METHOD DESCRIPTION __new__

creates a new instance of the class if it doesn't exist, otherwise returns the existing instance

_drop

sets the instance to None, allowing a new instance to be created

","boost":0.5},{"location":"api/faststream/utils/context/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/utils/context/Context/#faststream.utils.context.Context","title":"faststream.utils.context.Context","text":"
Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/","title":"ContextRepo","text":"","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo","title":"faststream.utils.context.ContextRepo","text":"
ContextRepo()\n

Bases: Singleton

A class to represent a context repository.

METHOD DESCRIPTION __init__

initializes the ContextRepo object

set_global

sets a global context variable

reset_global

resets a global context variable

set_local

sets a local context variable

reset_local

resets a local context variable

get_local

gets the value of a local context variable

clear

clears the global and scope context

get

gets the value of a context variable

__getattr__

gets the value of a context variable using attribute access

context

gets the current context as a dictionary

scope

creates a context scope for a specific key and value

Initialize the class.

Source code in faststream/utils/context/main.py
def __init__(self) -> None:\n    \"\"\"Initialize the class.\n\n    Attributes:\n        _global_context : a dictionary representing the global context\n        _scope_context : a dictionary representing the scope context\n    \"\"\"\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.context","title":"context property","text":"
context: AnyDict\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.clear","title":"clear","text":"
clear() -> None\n
Source code in faststream/utils/context/main.py
def clear(self) -> None:\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.get","title":"get","text":"
get(key: str, default: Any = None) -> Any\n

Get the value associated with a key.

PARAMETER DESCRIPTION key

The key to retrieve the value for.

TYPE: str

RETURNS DESCRIPTION Any

The value associated with the key.

Source code in faststream/utils/context/main.py
def get(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value associated with a key.\n\n    Args:\n        key: The key to retrieve the value for.\n\n    Returns:\n        The value associated with the key.\n    \"\"\"\n    return self._global_context.get(key, self.get_local(key, default))\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.get_local","title":"get_local","text":"
get_local(key: str, default: Any = None) -> Any\n

Get the value of a local variable.

PARAMETER DESCRIPTION key

The key of the local variable to retrieve.

TYPE: str

RETURNS DESCRIPTION Any

The value of the local variable.

Source code in faststream/utils/context/main.py
def get_local(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value of a local variable.\n\n    Args:\n        key: The key of the local variable to retrieve.\n\n    Returns:\n        The value of the local variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is not None:  # pragma: no branch\n        return context_var.get()\n    else:\n        return default\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.reset_global","title":"reset_global","text":"
reset_global(key: str) -> None\n

Resets a key in the global context.

PARAMETER DESCRIPTION key

The key to reset in the global context.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_global(self, key: str) -> None:\n    \"\"\"Resets a key in the global context.\n\n    Args:\n        key (str): The key to reset in the global context.\n\n    Returns:\n        None\n    \"\"\"\n    self._global_context.pop(key, None)\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.reset_local","title":"reset_local","text":"
reset_local(key: str, tag: Token[Any]) -> None\n

Resets the local context for a given key.

PARAMETER DESCRIPTION key

The key to reset the local context for.

TYPE: str

tag

The tag associated with the local context.

TYPE: Token[Any]

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_local(self, key: str, tag: \"Token[Any]\") -> None:\n    \"\"\"Resets the local context for a given key.\n\n    Args:\n        key (str): The key to reset the local context for.\n        tag (Token[Any]): The tag associated with the local context.\n\n    Returns:\n        None\n    \"\"\"\n    self._scope_context[key].reset(tag)\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.resolve","title":"resolve","text":"
resolve(argument: str) -> Any\n

Resolve the context of an argument.

PARAMETER DESCRIPTION argument

A string representing the argument.

TYPE: str

RETURNS DESCRIPTION Any

The resolved context of the argument.

RAISES DESCRIPTION AttributeError

If the attribute does not exist in the context.

Source code in faststream/utils/context/main.py
def resolve(self, argument: str) -> Any:\n    \"\"\"Resolve the context of an argument.\n\n    Args:\n        argument: A string representing the argument.\n\n    Returns:\n        The resolved context of the argument.\n\n    Raises:\n        AttributeError: If the attribute does not exist in the context.\n    \"\"\"\n    first, *keys = argument.split(\".\")\n\n    if (v := self.get(first, _empty)) is _empty:\n        raise KeyError(f\"`{self.context}` does not contains `{first}` key\")\n\n    for i in keys:\n        if isinstance(v, Mapping):\n            v = v[i]\n        else:\n            v = getattr(v, i)\n    return v\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.scope","title":"scope","text":"
scope(key: str, value: Any) -> Iterator[None]\n

Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.

PARAMETER DESCRIPTION key

The key of the local variable

TYPE: str

value

The value to set the local variable to

TYPE: Any

YIELDS DESCRIPTION Iterator[None]

None

RETURNS DESCRIPTION Iterator[None]

An iterator that yields None

Source code in faststream/utils/context/main.py
@contextmanager\ndef scope(self, key: str, value: Any) -> Iterator[None]:\n    \"\"\"Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.\n\n    Args:\n        key: The key of the local variable\n        value: The value to set the local variable to\n\n    Yields:\n        None\n\n    Returns:\n        An iterator that yields None\n    \"\"\"\n    token = self.set_local(key, value)\n    try:\n        yield\n    finally:\n        self.reset_local(key, token)\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.set_global","title":"set_global","text":"
set_global(key: str, v: Any) -> None\n

Sets a value in the global context.

PARAMETER DESCRIPTION key

The key to set in the global context.

TYPE: str

v

The value to set.

TYPE: Any

RETURNS DESCRIPTION None

None.

Source code in faststream/utils/context/main.py
def set_global(self, key: str, v: Any) -> None:\n    \"\"\"Sets a value in the global context.\n\n    Args:\n        key: The key to set in the global context.\n        v: The value to set.\n\n    Returns:\n        None.\n    \"\"\"\n    self._global_context[key] = v\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.set_local","title":"set_local","text":"
set_local(key: str, value: T) -> Token[T]\n

Set a local context variable.

PARAMETER DESCRIPTION key

The key for the context variable.

TYPE: str

value

The value to set for the context variable.

TYPE: T

RETURNS DESCRIPTION Token[T]

Token[T]: A token representing the context variable.

Source code in faststream/utils/context/main.py
def set_local(self, key: str, value: T) -> \"Token[T]\":\n    \"\"\"Set a local context variable.\n\n    Args:\n        key (str): The key for the context variable.\n        value (T): The value to set for the context variable.\n\n    Returns:\n        Token[T]: A token representing the context variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is None:\n        context_var = ContextVar(key, default=None)\n        self._scope_context[key] = context_var\n    return context_var.set(value)\n
","boost":0.5},{"location":"api/faststream/utils/context/Header/","title":"Header","text":"","boost":0.5},{"location":"api/faststream/utils/context/Header/#faststream.utils.context.Header","title":"faststream.utils.context.Header","text":"
Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.headers.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/Path/","title":"Path","text":"","boost":0.5},{"location":"api/faststream/utils/context/Path/#faststream.utils.context.Path","title":"faststream.utils.context.Path","text":"
Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.path.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/builders/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/utils/context/builders/Context/#faststream.utils.context.builders.Context","title":"faststream.utils.context.builders.Context","text":"
Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/builders/Header/","title":"Header","text":"","boost":0.5},{"location":"api/faststream/utils/context/builders/Header/#faststream.utils.context.builders.Header","title":"faststream.utils.context.builders.Header","text":"
Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.headers.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/builders/Path/","title":"Path","text":"","boost":0.5},{"location":"api/faststream/utils/context/builders/Path/#faststream.utils.context.builders.Path","title":"faststream.utils.context.builders.Path","text":"
Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.path.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/","title":"ContextRepo","text":"","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo","title":"faststream.utils.context.main.ContextRepo","text":"
ContextRepo()\n

Bases: Singleton

A class to represent a context repository.

METHOD DESCRIPTION __init__

initializes the ContextRepo object

set_global

sets a global context variable

reset_global

resets a global context variable

set_local

sets a local context variable

reset_local

resets a local context variable

get_local

gets the value of a local context variable

clear

clears the global and scope context

get

gets the value of a context variable

__getattr__

gets the value of a context variable using attribute access

context

gets the current context as a dictionary

scope

creates a context scope for a specific key and value

Initialize the class.

Source code in faststream/utils/context/main.py
def __init__(self) -> None:\n    \"\"\"Initialize the class.\n\n    Attributes:\n        _global_context : a dictionary representing the global context\n        _scope_context : a dictionary representing the scope context\n    \"\"\"\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.context","title":"context property","text":"
context: AnyDict\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.clear","title":"clear","text":"
clear() -> None\n
Source code in faststream/utils/context/main.py
def clear(self) -> None:\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.get","title":"get","text":"
get(key: str, default: Any = None) -> Any\n

Get the value associated with a key.

PARAMETER DESCRIPTION key

The key to retrieve the value for.

TYPE: str

RETURNS DESCRIPTION Any

The value associated with the key.

Source code in faststream/utils/context/main.py
def get(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value associated with a key.\n\n    Args:\n        key: The key to retrieve the value for.\n\n    Returns:\n        The value associated with the key.\n    \"\"\"\n    return self._global_context.get(key, self.get_local(key, default))\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.get_local","title":"get_local","text":"
get_local(key: str, default: Any = None) -> Any\n

Get the value of a local variable.

PARAMETER DESCRIPTION key

The key of the local variable to retrieve.

TYPE: str

RETURNS DESCRIPTION Any

The value of the local variable.

Source code in faststream/utils/context/main.py
def get_local(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value of a local variable.\n\n    Args:\n        key: The key of the local variable to retrieve.\n\n    Returns:\n        The value of the local variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is not None:  # pragma: no branch\n        return context_var.get()\n    else:\n        return default\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.reset_global","title":"reset_global","text":"
reset_global(key: str) -> None\n

Resets a key in the global context.

PARAMETER DESCRIPTION key

The key to reset in the global context.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_global(self, key: str) -> None:\n    \"\"\"Resets a key in the global context.\n\n    Args:\n        key (str): The key to reset in the global context.\n\n    Returns:\n        None\n    \"\"\"\n    self._global_context.pop(key, None)\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.reset_local","title":"reset_local","text":"
reset_local(key: str, tag: Token[Any]) -> None\n

Resets the local context for a given key.

PARAMETER DESCRIPTION key

The key to reset the local context for.

TYPE: str

tag

The tag associated with the local context.

TYPE: Token[Any]

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_local(self, key: str, tag: \"Token[Any]\") -> None:\n    \"\"\"Resets the local context for a given key.\n\n    Args:\n        key (str): The key to reset the local context for.\n        tag (Token[Any]): The tag associated with the local context.\n\n    Returns:\n        None\n    \"\"\"\n    self._scope_context[key].reset(tag)\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.resolve","title":"resolve","text":"
resolve(argument: str) -> Any\n

Resolve the context of an argument.

PARAMETER DESCRIPTION argument

A string representing the argument.

TYPE: str

RETURNS DESCRIPTION Any

The resolved context of the argument.

RAISES DESCRIPTION AttributeError

If the attribute does not exist in the context.

Source code in faststream/utils/context/main.py
def resolve(self, argument: str) -> Any:\n    \"\"\"Resolve the context of an argument.\n\n    Args:\n        argument: A string representing the argument.\n\n    Returns:\n        The resolved context of the argument.\n\n    Raises:\n        AttributeError: If the attribute does not exist in the context.\n    \"\"\"\n    first, *keys = argument.split(\".\")\n\n    if (v := self.get(first, _empty)) is _empty:\n        raise KeyError(f\"`{self.context}` does not contains `{first}` key\")\n\n    for i in keys:\n        if isinstance(v, Mapping):\n            v = v[i]\n        else:\n            v = getattr(v, i)\n    return v\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.scope","title":"scope","text":"
scope(key: str, value: Any) -> Iterator[None]\n

Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.

PARAMETER DESCRIPTION key

The key of the local variable

TYPE: str

value

The value to set the local variable to

TYPE: Any

YIELDS DESCRIPTION Iterator[None]

None

RETURNS DESCRIPTION Iterator[None]

An iterator that yields None

Source code in faststream/utils/context/main.py
@contextmanager\ndef scope(self, key: str, value: Any) -> Iterator[None]:\n    \"\"\"Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.\n\n    Args:\n        key: The key of the local variable\n        value: The value to set the local variable to\n\n    Yields:\n        None\n\n    Returns:\n        An iterator that yields None\n    \"\"\"\n    token = self.set_local(key, value)\n    try:\n        yield\n    finally:\n        self.reset_local(key, token)\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.set_global","title":"set_global","text":"
set_global(key: str, v: Any) -> None\n

Sets a value in the global context.

PARAMETER DESCRIPTION key

The key to set in the global context.

TYPE: str

v

The value to set.

TYPE: Any

RETURNS DESCRIPTION None

None.

Source code in faststream/utils/context/main.py
def set_global(self, key: str, v: Any) -> None:\n    \"\"\"Sets a value in the global context.\n\n    Args:\n        key: The key to set in the global context.\n        v: The value to set.\n\n    Returns:\n        None.\n    \"\"\"\n    self._global_context[key] = v\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.set_local","title":"set_local","text":"
set_local(key: str, value: T) -> Token[T]\n

Set a local context variable.

PARAMETER DESCRIPTION key

The key for the context variable.

TYPE: str

value

The value to set for the context variable.

TYPE: T

RETURNS DESCRIPTION Token[T]

Token[T]: A token representing the context variable.

Source code in faststream/utils/context/main.py
def set_local(self, key: str, value: T) -> \"Token[T]\":\n    \"\"\"Set a local context variable.\n\n    Args:\n        key (str): The key for the context variable.\n        value (T): The value to set for the context variable.\n\n    Returns:\n        Token[T]: A token representing the context variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is None:\n        context_var = ContextVar(key, default=None)\n        self._scope_context[key] = context_var\n    return context_var.set(value)\n
","boost":0.5},{"location":"api/faststream/utils/context/path/compile_path/","title":"compile_path","text":"","boost":0.5},{"location":"api/faststream/utils/context/path/compile_path/#faststream.utils.context.path.compile_path","title":"faststream.utils.context.path.compile_path","text":"
compile_path(\n    path: str, replace_symbol: str\n) -> Tuple[Optional[Pattern[str]], str]\n
Source code in faststream/utils/context/path.py
def compile_path(\n    path: str,\n    replace_symbol: str,\n) -> Tuple[Optional[Pattern[str]], str]:\n    path_regex = \"^\"\n    path_format = \"\"\n\n    idx = 0\n    params = set()\n    duplicated_params = set()\n    for match in PARAM_REGEX.finditer(path):\n        param_name = match.groups(\"str\")[0]\n\n        path_regex += re.escape(path[idx : match.start()])\n        path_regex += f\"(?P<{param_name.replace('+', '')}>[^/]+)\"\n\n        path_format += path[idx : match.start()]\n        path_format += replace_symbol\n\n        if param_name in params:\n            duplicated_params.add(param_name)\n        else:\n            params.add(param_name)\n\n        idx = match.end()\n\n    if duplicated_params:\n        names = \", \".join(sorted(duplicated_params))\n        ending = \"s\" if len(duplicated_params) > 1 else \"\"\n        raise ValueError(f\"Duplicated param name{ending} {names} at path {path}\")\n\n    if idx == 0:\n        regex = None\n    else:\n        path_regex += re.escape(path[idx:]) + \"$\"\n        regex = re.compile(path_regex)\n\n    path_format += path[idx:]\n    return regex, path_format\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context","title":"faststream.utils.context.types.Context","text":"
Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n    prefix: str = \"\"\n)\n

Bases: CustomField

A class to represent a context.

METHOD DESCRIPTION __init__

constructor method

use

method to use the context

Initialize the object.

PARAMETER DESCRIPTION real_name

The real name of the object.

TYPE: str DEFAULT: ''

cast

Whether to cast the object.

TYPE: bool DEFAULT: False

default

The default value of the object.

TYPE: Any DEFAULT: _empty

RAISES DESCRIPTION TypeError

If the default value is not provided.

Source code in faststream/utils/context/types.py
def __init__(\n    self,\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n    prefix: str = \"\",\n) -> None:\n    \"\"\"Initialize the object.\n\n    Args:\n        real_name: The real name of the object.\n        cast: Whether to cast the object.\n        default: The default value of the object.\n\n    Raises:\n        TypeError: If the default value is not provided.\n    \"\"\"\n    self.name = real_name\n    self.default = default\n    self.prefix = prefix\n    super().__init__(\n        cast=cast,\n        required=(default is _empty),\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.cast","title":"cast instance-attribute","text":"
cast: bool = cast\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.default","title":"default instance-attribute","text":"
default = default\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.name","title":"name instance-attribute","text":"
name = real_name\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.param_name","title":"param_name instance-attribute","text":"
param_name: str\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.required","title":"required instance-attribute","text":"
required: bool = required\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.set_param_name","title":"set_param_name","text":"
set_param_name(name: str) -> Cls\n
Source code in fast_depends/library/model.py
def set_param_name(self: Cls, name: str) -> Cls:\n    self.param_name = name\n    return self\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.use","title":"use","text":"
use(**kwargs: Any) -> AnyDict\n

Use the given keyword arguments.

PARAMETER DESCRIPTION **kwargs

Keyword arguments to be used

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION AnyDict

A dictionary containing the updated keyword arguments

RAISES DESCRIPTION KeyError

If the parameter name is not found in the keyword arguments

AttributeError

If the parameter name is not a valid attribute

Source code in faststream/utils/context/types.py
def use(self, /, **kwargs: Any) -> AnyDict:\n    \"\"\"Use the given keyword arguments.\n\n    Args:\n        **kwargs: Keyword arguments to be used\n\n    Returns:\n        A dictionary containing the updated keyword arguments\n\n    Raises:\n        KeyError: If the parameter name is not found in the keyword arguments\n        AttributeError: If the parameter name is not a valid attribute\n    \"\"\"\n    name = f\"{self.prefix}{self.name or self.param_name}\"\n\n    try:\n        kwargs[self.param_name] = context.resolve(name)\n    except (KeyError, AttributeError):\n        if self.required is False:\n            kwargs[self.param_name] = self.default\n\n    return kwargs\n
","boost":0.5},{"location":"api/faststream/utils/data/filter_by_dict/","title":"filter_by_dict","text":"","boost":0.5},{"location":"api/faststream/utils/data/filter_by_dict/#faststream.utils.data.filter_by_dict","title":"faststream.utils.data.filter_by_dict","text":"
filter_by_dict(\n    typed_dict: Type[TypedDictCls], data: AnyDict\n) -> TypedDictCls\n

Filter a dictionary based on a typed dictionary.

PARAMETER DESCRIPTION typed_dict

The typed dictionary to filter by.

TYPE: Type[TypedDictCls]

data

The dictionary to filter.

TYPE: AnyDict

RETURNS DESCRIPTION TypedDictCls

A new instance of the typed dictionary with only the keys present in the data dictionary.

Source code in faststream/utils/data.py
def filter_by_dict(typed_dict: Type[TypedDictCls], data: AnyDict) -> TypedDictCls:\n    \"\"\"Filter a dictionary based on a typed dictionary.\n\n    Args:\n        typed_dict: The typed dictionary to filter by.\n        data: The dictionary to filter.\n\n    Returns:\n        A new instance of the typed dictionary with only the keys present in the data dictionary.\n    \"\"\"\n    annotations = typed_dict.__annotations__\n    return typed_dict(  # type: ignore\n        {k: v for k, v in data.items() if k in annotations}\n    )\n
","boost":0.5},{"location":"api/faststream/utils/functions/call_or_await/","title":"call_or_await","text":"","boost":0.5},{"location":"api/faststream/utils/functions/call_or_await/#fast_depends.utils.run_async","title":"fast_depends.utils.run_async async","text":"
run_async(\n    func: Union[Callable[P, T], Callable[P, Awaitable[T]]],\n    *args: P.args,\n    **kwargs: P.kwargs\n) -> T\n
Source code in fast_depends/utils.py
async def run_async(\n    func: Union[\n        Callable[P, T],\n        Callable[P, Awaitable[T]],\n    ],\n    *args: P.args,\n    **kwargs: P.kwargs,\n) -> T:\n    if is_coroutine_callable(func):\n        return await cast(Callable[P, Awaitable[T]], func)(*args, **kwargs)\n    else:\n        return await run_in_threadpool(cast(Callable[P, T], func), *args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/utils/functions/drop_response_type/","title":"drop_response_type","text":"","boost":0.5},{"location":"api/faststream/utils/functions/drop_response_type/#faststream.utils.functions.drop_response_type","title":"faststream.utils.functions.drop_response_type","text":"
drop_response_type(\n    model: CallModel[F_Spec, F_Return]\n) -> CallModel[F_Spec, F_Return]\n
Source code in faststream/utils/functions.py
def drop_response_type(\n    model: CallModel[F_Spec, F_Return]\n) -> CallModel[F_Spec, F_Return]:\n    model.response_model = None\n    return model\n
","boost":0.5},{"location":"api/faststream/utils/functions/fake_context/","title":"fake_context","text":"","boost":0.5},{"location":"api/faststream/utils/functions/fake_context/#faststream.utils.functions.fake_context","title":"faststream.utils.functions.fake_context async","text":"
fake_context(\n    *args: Any, **kwargs: Any\n) -> AsyncIterator[None]\n
Source code in faststream/utils/functions.py
@asynccontextmanager\nasync def fake_context(*args: Any, **kwargs: Any) -> AsyncIterator[None]:\n    yield None\n
","boost":0.5},{"location":"api/faststream/utils/functions/get_function_positional_arguments/","title":"get_function_positional_arguments","text":"","boost":0.5},{"location":"api/faststream/utils/functions/get_function_positional_arguments/#faststream.utils.functions.get_function_positional_arguments","title":"faststream.utils.functions.get_function_positional_arguments","text":"
get_function_positional_arguments(\n    func: AnyCallable,\n) -> List[str]\n

Get the positional arguments of a function.

PARAMETER DESCRIPTION func

The function to get the positional arguments from.

TYPE: AnyCallable

RETURNS DESCRIPTION List[str]

A list of strings representing the names of the positional arguments.

Source code in faststream/utils/functions.py
def get_function_positional_arguments(func: AnyCallable) -> List[str]:\n    \"\"\"Get the positional arguments of a function.\n\n    Args:\n        func: The function to get the positional arguments from.\n\n    Returns:\n        A list of strings representing the names of the positional arguments.\n    \"\"\"\n    signature = inspect.signature(func)\n\n    arg_kinds = (\n        inspect.Parameter.POSITIONAL_ONLY,\n        inspect.Parameter.POSITIONAL_OR_KEYWORD,\n    )\n\n    return [\n        param.name for param in signature.parameters.values() if param.kind in arg_kinds\n    ]\n
","boost":0.5},{"location":"api/faststream/utils/functions/timeout_scope/","title":"timeout_scope","text":"","boost":0.5},{"location":"api/faststream/utils/functions/timeout_scope/#faststream.utils.functions.timeout_scope","title":"faststream.utils.functions.timeout_scope","text":"
timeout_scope(\n    timeout: Optional[float] = 30,\n    raise_timeout: bool = False,\n) -> ContextManager[anyio.CancelScope]\n
Source code in faststream/utils/functions.py
def timeout_scope(\n    timeout: Optional[float] = 30,\n    raise_timeout: bool = False,\n) -> ContextManager[anyio.CancelScope]:\n    scope: Callable[[Optional[float]], ContextManager[anyio.CancelScope]]\n    if raise_timeout:\n        scope = anyio.fail_after\n    else:\n        scope = anyio.move_on_after\n\n    return scope(timeout)\n
","boost":0.5},{"location":"api/faststream/utils/functions/to_async/","title":"to_async","text":"","boost":0.5},{"location":"api/faststream/utils/functions/to_async/#faststream.utils.functions.to_async","title":"faststream.utils.functions.to_async","text":"
to_async(\n    func: Union[\n        Callable[F_Spec, F_Return],\n        Callable[F_Spec, Awaitable[F_Return]],\n    ]\n) -> Callable[F_Spec, Awaitable[F_Return]]\n

Converts a synchronous function to an asynchronous function.

PARAMETER DESCRIPTION func

The synchronous function to be converted.

TYPE: Union[Callable[F_Spec, F_Return], Callable[F_Spec, Awaitable[F_Return]]]

RETURNS DESCRIPTION Callable[F_Spec, Awaitable[F_Return]]

The asynchronous version of the input function.

Source code in faststream/utils/functions.py
def to_async(\n    func: Union[\n        Callable[F_Spec, F_Return],\n        Callable[F_Spec, Awaitable[F_Return]],\n    ]\n) -> Callable[F_Spec, Awaitable[F_Return]]:\n    \"\"\"Converts a synchronous function to an asynchronous function.\n\n    Args:\n        func: The synchronous function to be converted.\n\n    Returns:\n        The asynchronous version of the input function.\n    \"\"\"\n\n    @wraps(func)\n    async def to_async_wrapper(*args: F_Spec.args, **kwargs: F_Spec.kwargs) -> F_Return:\n        \"\"\"Wraps a function to make it asynchronous.\n\n        Args:\n            func: The function to be wrapped\n            args: Positional arguments to be passed to the function\n            kwargs: Keyword arguments to be passed to the function\n\n        Returns:\n            The result of the wrapped function\n\n        Raises:\n            Any exceptions raised by the wrapped function\n        \"\"\"\n        return await call_or_await(func, *args, **kwargs)\n\n    return to_async_wrapper\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/","title":"NoCast","text":"","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast","title":"faststream.utils.no_cast.NoCast","text":"
NoCast()\n

Bases: CustomField

A class that represents a custom field without casting.

METHOD DESCRIPTION __init__

Initializes the NoCast object.

use

Returns the provided keyword arguments as a dictionary.

Source code in faststream/utils/no_cast.py
def __init__(self) -> None:\n    super().__init__(cast=False)\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast.cast","title":"cast instance-attribute","text":"
cast: bool = cast\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast.param_name","title":"param_name instance-attribute","text":"
param_name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast.required","title":"required instance-attribute","text":"
required: bool = required\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast.set_param_name","title":"set_param_name","text":"
set_param_name(name: str) -> Cls\n
Source code in fast_depends/library/model.py
def set_param_name(self: Cls, name: str) -> Cls:\n    self.param_name = name\n    return self\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast.use","title":"use","text":"
use(**kwargs: Any) -> AnyDict\n

Return a dictionary containing the keyword arguments passed to the function.

PARAMETER DESCRIPTION **kwargs

Keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION AnyDict

Dictionary containing the keyword arguments

Source code in faststream/utils/no_cast.py
def use(self, **kwargs: Any) -> AnyDict:\n    \"\"\"Return a dictionary containing the keyword arguments passed to the function.\n\n    Args:\n        **kwargs: Keyword arguments\n\n    Returns:\n        Dictionary containing the keyword arguments\n    \"\"\"\n    return kwargs\n
","boost":0.5},{"location":"getting-started/","title":"QUICK START","text":"

Install using pip:

KafkaRabbitMQNATSRedis
pip install \"faststream[kafka]\"\n

Tip

To start a new project, we need a test broker container

docker run -d --rm -p 9092:9092 --name test-mq \\\n-e KAFKA_ENABLE_KRAFT=yes \\\n-e KAFKA_CFG_NODE_ID=1 \\\n-e KAFKA_CFG_PROCESS_ROLES=broker,controller \\\n-e KAFKA_CFG_CONTROLLER_LISTENER_NAMES=CONTROLLER \\\n-e KAFKA_CFG_LISTENERS=PLAINTEXT://:9092,CONTROLLER://:9093 \\\n-e KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP=CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT \\\n-e KAFKA_CFG_ADVERTISED_LISTENERS=PLAINTEXT://127.0.0.1:9092 \\\n-e KAFKA_BROKER_ID=1 \\\n-e KAFKA_CFG_CONTROLLER_QUORUM_VOTERS=1@kafka:9093 \\\n-e ALLOW_PLAINTEXT_LISTENER=yes \\\nbitnami/kafka:3.5.0\n

pip install \"faststream[rabbit]\"\n

Tip

To start a new project, we need a test broker container

docker run -d --rm -p 5672:5672 --name test-mq rabbitmq:alpine\n

pip install \"faststream[nats]\"\n

Tip

To start a new project, we need a test broker container

bash docker run -d --rm -p 4222:4222 --name test-mq nats -js\n

pip install \"faststream[redis]\"\n

Tip

To start a new project, we need a test broker container

bash docker run -d --rm -p 6379:6379 --name test-mq redis\n

","boost":10},{"location":"getting-started/#basic-usage","title":"Basic Usage","text":"

To create a basic application, add the following code to a new file (e.g. serve.py):

KafkaRabbitMQNATSRedis serve.py
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n
serve.py
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\n\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n
serve.py
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\n\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n
serve.py
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\n\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n

And just run this command:

faststream run serve:app\n

After running the command, you should see the following output:

Enjoy your new development experience!

Don't forget to stop the test broker container
docker container stop test-mq\n
","boost":10},{"location":"getting-started/logging/","title":"Application and Access Logging","text":"

FastStream uses two already configured loggers:

","boost":10},{"location":"getting-started/logging/#logging-requests","title":"Logging Requests","text":"

To log requests, it is strongly recommended to use the access_logger of your broker, as it is available from the Context of your application.

from faststream import Logger\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker()\n\n@broker.subscriber(\"test\")\nasync def func(logger: Logger):\n    logger.info(\"message received\")\n

This approach offers several advantages:

","boost":10},{"location":"getting-started/logging/#logging-levels","title":"Logging Levels","text":"

If you use the FastStream CLI, you can change the current logging level of the entire application directly from the command line.

The --log-level flag sets the current logging level for both the broker and the FastStream app. This allows you to configure the levels of not only the default loggers but also your custom loggers, if you use them inside FastStream.

faststream run serve:app --log-level debug\n

If you want to completely disable the default logging of FastStream, you can set logger=None

from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(logger=None)     # Disables broker logs\napp = FastStream(broker, logger=None)  # Disables application logs\n

Warning

Be careful: the logger that you get from the context will also have the value None if you turn off broker logging.

If you don't want to lose access to the `logger' inside your context but want to disable the default logs of FastStream, you can lower the level of logs that the broker publishes itself.

import logging\nfrom faststream.rabbit import RabbitBroker\n\n# Sets the broker logs to the DEBUG level\nbroker = RabbitBroker(log_level=logging.DEBUG)\n
","boost":10},{"location":"getting-started/logging/#formatting-logs","title":"Formatting Logs","text":"

If you are not satisfied with the current format of your application logs, you can change it directly in your broker's constructor.

from faststream.rabbit import RabbitBroker\nbroker = RabbitBroker(log_fmt=\"%(asctime)s %(levelname)s - %(message)s\")\n
","boost":10},{"location":"getting-started/logging/#logger-access","title":"Logger Access","text":"

If you want to override default logger's behavior, you can access them directly via logging.

import logging\nlogger = logging.getLogger(\"faststream\")\naccess_logger = logging.getLogger(\"faststream.access\")\n

Or you can import them from FastStream.

from faststream.log import access_logger, logger\n
","boost":10},{"location":"getting-started/logging/#using-your-own-loggers","title":"Using Your Own Loggers","text":"

Since FastStream works with the standard logging.Logger object, you can initiate an application and a broker using your own logger.

import logging\nfrom faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nlogger = logging.getLogger(\"my_logger\")\n\nbroker = RabbitBroker(logger=logger)\napp = FastStream(broker, logger=logger)\n

Note

Doing this, you doesn't change the CLI logs behavior (multiprocessing and hot reload logs). This was done to keep your log storage clear of unnecessary stuff.

This logger will be used only for FastStream and StreamBroker service messages and will be passed to your function through the Context.

By doing this, you will lose information about the context of the current request. However, you can retrieve it directly from the context anywhere in your code.

from faststream import context\nlog_context: dict[str, str] = context.get_local(\"log_context\")\n

This way, all broker handlers can get access to your broker logger right from the context:

from faststream import Logger\n\n@broker.subscriber(...)\nasync def handler(\n    msg,\n    logger: Logger,  # <-- YOUR logger here\n):\n    logger.info(msg)\n
","boost":10},{"location":"getting-started/logging/#structlog-example","title":"Structlog Example","text":"

Structlog is a production-ready logging solution for Python. It can be easely integrated with any log storage system, making it suitable for use in production projects.

Here is a quick tutorial on integrating Structlog with FastStream:

Start with the Structlog guide example:

import sys\nimport structlog\n\nshared_processors = [\n    structlog.processors.add_log_level,\n    structlog.processors.StackInfoRenderer(),\n    structlog.dev.set_exc_info,\n    structlog.processors.TimeStamper(fmt=\"iso\"),\n]\n\nif sys.stderr.isatty():\n    # terminal session\n    processors = shared_processors + [\n        structlog.dev.ConsoleRenderer()\n    ]\nelse:\n    # Docker container session\n    processors = shared_processors + [\n        structlog.processors.dict_tracebacks,\n        structlog.processors.JSONRenderer(),\n    ]\n\nstructlog.configure(\n    processors=processors,\n    logger_factory=structlog.PrintLoggerFactory(),\n    cache_logger_on_first_use=False,\n)\n\nlogger = structlog.get_logger()\n

We created a logger that prints messages to the console in a user-friendly format during development and uses JSON-formatted logs in production.

To integrate this logger with our FastStream application, we just need to access it through context information and pass it to our objects:

import logging\n\nimport structlog\n\nfrom faststream import FastStream, context\nfrom faststream.kafka import KafkaBroker\n\ndef merge_contextvars(\n    logger: structlog.types.WrappedLogger,\n    method_name: str,\n    event_dict: structlog.types.EventDict,\n) -> structlog.types.EventDict:\n    event_dict[\"extra\"] = event_dict.get(\n        \"extra\",\n        context.get(\"log_context\", {}),\n    )\n    return event_dict\n\nshared_processors = [\n    merge_contextvars,\n    ...\n]\n\n...\n\nbroker = KafkaBroker(logger=logger, log_level=logging.DEBUG)\napp = FastStream(broker, logger=logger)\n

And the job is done! Now you have a perfectly structured logs using Structlog.

","boost":10},{"location":"getting-started/asyncapi/custom/","title":"Customizing AsyncAPI Documentation for FastStream","text":"

In this guide, we will explore how to customize AsyncAPI documentation for your FastStream application. Whether you want to add custom app info, broker information, handlers, or fine-tune payload details, we'll walk you through each step.

","boost":10},{"location":"getting-started/asyncapi/custom/#prerequisites","title":"Prerequisites","text":"

Before we dive into customization, ensure you have a basic FastStream application up and running. If you haven't done that yet, let's setup a simple appication right now.

Copy the following code in your basic.py file:

from faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaMessage\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n@broker.publisher(\"output_data\")\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg):\n    # your processing logic\n    pass\n

Now, when you run

faststream docs serve basic:app\n
you should see the following documentation:

","boost":10},{"location":"getting-started/asyncapi/custom/#setup-custom-faststream-app-info","title":"Setup Custom FastStream App Info","text":"

Let's start by customizing the app information that appears in your AsyncAPI documentation. This is a great way to give your documentation a personal touch. Here's how:

  1. Locate the app configuration in your FastStream application.
  2. Update the title, version, and description fields to reflect your application's details.
  3. Save the changes.
  4. Serve your FastStream app documentation.

Copy the following code in your basic.py file, we have highligted the additional info passed to FastStream app:

from faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaMessage\nfrom faststream.asyncapi.schema import Contact, ExternalDocs, License, Tag\n\nbroker = KafkaBroker(\"localhost:9092\")\ndescription=\"\"\"# Title of the description\nThis description supports **Markdown** syntax\"\"\"\napp = FastStream(\n    broker,\n    title=\"My App\",\n    version=\"1.0.0\",\n    description=description,\n    license=License(name=\"MIT\", url=\"https://opensource.org/license/mit/\"),\n    terms_of_service=\"https://my-terms.com/\",\n    contact=Contact(name=\"support\", url=\"https://help.com/\"),\n)\n\n@broker.publisher(\"output_data\")\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg):\n    # your processing logic\n    pass\n

Now, when you run

faststream docs serve basic:app\n
you should see the following in your general app documentation:

Now, your documentation reflects your application's identity and purpose.

Note

The description field in the above example supports Markdown text.

","boost":10},{"location":"getting-started/asyncapi/custom/#setup-custom-broker-information","title":"Setup Custom Broker Information","text":"

The next step is to customize broker information. This helps users understand the messaging system your application uses. Follow these steps:

  1. Locate the broker configuration in your FastStream application.
  2. Update the description field.
  3. Update the asyncapi_url field with a non-sensitive URL if you want to conceal your broker's actual bootstrap server URL.
  4. Save the changes.
  5. Serve your FastStream app.

Copy the following code in your basic.py file, we have highligted the additional info passed to the FastStream app broker:

from faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaMessage\nfrom faststream.asyncapi.schema import Tag\n\nbroker = KafkaBroker(\n    \"localhost:9092\",\n    description=\"Kafka broker running locally\",\n    asyncapi_url=\"non-sensitive-url:9092\",\n)\napp = FastStream(broker)\n\n\n@broker.publisher(\"output_data\")\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg):\n    # your processing logic\n    pass\n

Now, when you run

faststream docs serve basic:app\n
you should see the description in your broker documentation:

Your AsyncAPI documentation now provides clear insights into the messaging infrastructure you're using.

","boost":10},{"location":"getting-started/asyncapi/custom/#setup-custom-handler-information","title":"Setup Custom Handler Information","text":"

Customizing handler information helps users comprehend the purpose and behavior of each message handler. Here's how to do it:

  1. Navigate to your handler definitions in your FastStream application.
  2. Add descriptions to each handler using description field.
  3. For subscriber, consumer function's docstring can be used as description.
  4. Add titles to each handler using title field adhering to URI format.
  5. Add publishing schema to publisher handler using schema field.
  6. Save the changes.
  7. Serve your FastStream app.

Copy the following code in your basic.py file, we have highligted the additional info passed to the FastStream app handlers:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaMessage\n\n\nclass DataBasic(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.publisher(\n    \"output_data\",\n    description=\"My publisher description\",\n    title=\"output_data:Produce\",\n    schema=DataBasic,\n)\n@broker.subscriber(\n    \"input_data\", title=\"input_data:Consume\"\n)\nasync def on_input_data(msg):\n    \"\"\"Consumer function\n\n    Args:\n        msg: input msg\n    \"\"\"\n    # your processing logic\n    pass\n

Now, when you run

faststream docs serve basic:app\n
you should see the descriptions in your handlers:

Now, your documentation is enriched with meaningful details about each message handler.

","boost":10},{"location":"getting-started/asyncapi/custom/#setup-payload-information-via-pydantic-model","title":"Setup Payload Information via Pydantic Model","text":"

To describe your message payload effectively, you can use Pydantic models. Here's how:

  1. Define Pydantic models for your message payloads.
  2. Annotate these models with descriptions and examples.
  3. Use these models as argument types or return types in your handlers.
  4. Save the changes.
  5. Serve your FastStream app.

Copy the following code in your basic.py file, we have highligted the creation of payload info and you can see it being passed to the return type and the msg argument type in the on_input_data function:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\n\nclass DataBasic(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.publisher(\"output_data\")\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: DataBasic) -> DataBasic:\n    # your processing logic\n    pass\n

Now, when you run

faststream docs serve basic:app\n
you should see the payload schema described in your documentation:

Your AsyncAPI documentation now showcases well-structured payload information.

","boost":10},{"location":"getting-started/asyncapi/custom/#generate-schemajson-customize-and-serve-it","title":"Generate Schema.json, customize and serve it","text":"

To take customization to the next level, you can manually modify the schema.json file. Follow these steps:

  1. Generate the initial schema.json by running
    faststream docs gen basic:app\n
  2. Manually edit the asyncapi.json file to add custom fields, descriptions, and details.
  3. Save your changes.
  4. Serve your FastStream app with the updated asyncapi.json by running
    faststream docs serve asyncapi.json\n

Now, you have fine-tuned control over your AsyncAPI documentation.

","boost":10},{"location":"getting-started/asyncapi/custom/#conclusion","title":"Conclusion","text":"

Customizing AsyncAPI documentation for your FastStream application not only enhances its appearance but also provides valuable insights to users. With these steps, you can create documentation that's not only informative but also uniquely yours.

Happy coding with your customized FastStream AsyncAPI documentation!

","boost":10},{"location":"getting-started/asyncapi/export/","title":"How to Generate and Serve AsyncAPI Documentation","text":"

In this guide, let's explore how to generate and serve AsyncAPI documentation for our FastStream application.

","boost":10},{"location":"getting-started/asyncapi/export/#writing-the-faststream-application","title":"Writing the FastStream Application","text":"

Here's an example Python application using FastStream that consumes data from a topic, increments the value, and outputs the data to another topic. Save it in a file called basic.py.

basic.py
from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n\n\nclass DataBasic(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.publisher(\"output_data\")\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: DataBasic, logger: Logger) -> DataBasic:\n    logger.info(msg)\n    return DataBasic(data=msg.data + 1.0)\n
","boost":10},{"location":"getting-started/asyncapi/export/#generating-the-asyncapi-specification","title":"Generating the AsyncAPI Specification","text":"

Now that we have a FastStream application, we can proceed with generating the AsyncAPI specification using a CLI command.

faststream docs gen basic:app\n

The above command will generate the AsyncAPI specification and save it in a file called asyncapi.json.

If you prefer yaml instead of json, please run the following command to generate asyncapi.yaml.

faststream docs gen --yaml basic:app\n

Tip

To generate the documentation in yaml format, please install the necessary dependency to work with YAML file format at first.

pip install PyYAML\n
","boost":10},{"location":"getting-started/asyncapi/hosting/","title":"Serving the AsyncAPI Documentation","text":"

FastStream provides a command to serve the AsyncAPI documentation.

Note

This feature requires an Internet connection to obtain the AsyncAPI HTML via CDN.

faststream docs serve basic:app\n

In the above command, we are providing the path in the format of python_module:FastStream. Alternatively, you can also specify asyncapi.json or asyncapi.yaml to serve the AsyncAPI documentation.

JSONYAML
faststream docs serve asyncapi.json\n
faststream docs serve asyncapi.yaml\n

After running the command, it should serve the AsyncAPI documentation on port 8000 and display the following logs in the terminal.

And you should be able to see the following page in your browser:

ShortExpand

Tip

The command also offers options to serve the documentation on a different host and port.

","boost":10},{"location":"getting-started/asyncapi/hosting/#customizing-asyncapi-documentation","title":"Customizing AsyncAPI Documentation","text":"

FastStream also provides query parameters to show and hide specific sections of AsyncAPI documentation.

You can use the following parameters control the visibility of relevant sections:

  1. sidebar: Whether to include the sidebar. Default is true.
  2. info: Whether to include the info section. Default is true.
  3. servers: Whether to include the servers section. Default is true.
  4. operations: Whether to include the operations section. Default is true.
  5. messages: Whether to include the messages section. Default is true.
  6. schemas: Whether to include the schemas section. Default is true.
  7. errors: Whether to include the errors section. Default is true.
  8. expandMessageExamples: Whether to expand message examples. Default is true.

For example, to hide the entire Servers section of the documentation, simply add servers=false as a query parameter, i.e., http://localhost:8000?servers=false. The resulting page would look like the image below:

Please use the above-listed query parameters to show and hide sections of the AsyncAPI documentation.

","boost":10},{"location":"getting-started/cli/","title":"CLI","text":"

FastStream has its own built-in CLI tool for your maximum comfort as a developer.

Thanks to typer and watchfiles. Their work is the basis of this tool.

faststream --help\n
","boost":10},{"location":"getting-started/cli/#running-the-project","title":"Running the Project","text":"","boost":10},{"location":"getting-started/cli/#multiprocessing-scaling","title":"Multiprocessing Scaling","text":"

FastStream allows you to scale application right from the command line by running you application in the Process pool.

Just set the --worker option to scale your application:

faststream run serve:app --workers 2\n
","boost":10},{"location":"getting-started/cli/#hot-reload","title":"Hot Reload","text":"

Thanks to watchfiles, written in Rust, you can work with your project easily. Edit the code as much as you like - the new version has already been launched and is waiting for your requests!

faststream run serve:app --reload\n

Tip

Please, install watchfiles if you want to use --reload feature

pip install watchfiles\n

By default FastStream watches for .py file changes, but you can specify an extra file extensions to watch by (your config files as an example)

faststream run serve:app --reload  --reload-ext .yml --realod-ext .yaml\n
","boost":10},{"location":"getting-started/cli/#environment-management","title":"Environment Management","text":"

You can pass any custom flags and launch options to the FastStream CLI even without first registering them. Just use them when launching the application - and they will be right in your environment.

Use this option to select environment files, configure logging, or at your discretion.

For example, we will pass the .env file to the context of our application:

faststream run serve:app --env=.env.dev\n
KafkaRabbitMQNATSRedis
from faststream import FastStream, ContextRepo\nfrom faststream.kafka import KafkaBroker\nfrom pydantic_settings import BaseSettings\n\nbroker = KafkaBroker()\n\napp = FastStream(broker)\n\nclass Settings(BaseSettings):\n    host: str = \"localhost:9092\"\n\n@app.on_startup\nasync def setup(env: str, context: ContextRepo):\n    settings = Settings(_env_file=env)\n    await broker.connect(settings.host)\n    context.set_global(\"settings\", settings)\n
from faststream import FastStream, ContextRepo\nfrom faststream.rabbit import RabbitBroker\nfrom pydantic_settings import BaseSettings\n\nbroker = RabbitBroker()\n\napp = FastStream(broker)\n\nclass Settings(BaseSettings):\n    host: str = \"amqp://guest:guest@localhost:5672/\" \n\n@app.on_startup\nasync def setup(env: str, context: ContextRepo):\n    settings = Settings(_env_file=env)\n    await broker.connect(settings.host)\n    context.set_global(\"settings\", settings)\n
from faststream import FastStream, ContextRepo\nfrom faststream.nats import NatsBroker\nfrom pydantic_settings import BaseSettings\n\nbroker = NatsBroker()\n\napp = FastStream(broker)\n\nclass Settings(BaseSettings):\n    host: str = \"nats://localhost:4222\"\n\n@app.on_startup\nasync def setup(env: str, context: ContextRepo):\n    settings = Settings(_env_file=env)\n    await broker.connect(settings.host)\n    context.set_global(\"settings\", settings)\n
from faststream import FastStream, ContextRepo\nfrom faststream.redis import RedisBroker\nfrom pydantic_settings import BaseSettings\n\nbroker = RedisBroker()\n\napp = FastStream(broker)\n\nclass Settings(BaseSettings):\n    host: str = \"redis://localhost:6379\"\n\n@app.on_startup\nasync def setup(env: str, context: ContextRepo):\n    settings = Settings(_env_file=env)\n    await broker.connect(settings.host)\n    context.set_global(\"settings\", settings)\n

Note

Note that the env parameter was passed to the setup function directly from the command line

All passed values can be of type bool, str or list[str].

In this case, the flags will be interpreted as follows:

You can use them both individually and together in unlimited quantities.

","boost":10},{"location":"getting-started/cli/#asyncapi-schema","title":"AsyncAPI Schema","text":"

Also, the FastStream CLI allows you to work with the AsyncAPI schema in a simple way.

You are able to generate .json or .yaml files by your application code or host HTML representation directly:

faststream docs --help\n

To learn more about the commands above, please visit AsyncAPI export and AsyncAPI hosting.

","boost":10},{"location":"getting-started/config/","title":"Settings and Environment Variables","text":"

In many cases, your application may require external settings or configurations, such as a broker connection or database credentials.

To manage these settings effectively, it's common to provide them through environment variables that can be read by the application.

","boost":10},{"location":"getting-started/config/#pydantic-settings","title":"Pydantic Settings","text":"

Fortunately, Pydantic provides a useful utility for handling settings coming from environment variables with Pydantic: Settings management.

","boost":10},{"location":"getting-started/config/#install-pydantic-settings","title":"Install pydantic-settings","text":"

First, install the pydantic-settings package:

pip install pydantic-settings\n

Info

In Pydantic v1, this functionality was included with the main package. Now it is distributed as an independent package so that you can choose not to install it if you don't need that functionality.

","boost":10},{"location":"getting-started/config/#create-the-settings-object","title":"Create the Settings Object","text":"

Import BaseSettings from Pydantic and create a subclass, similar to what you would do with a Pydantic model.

Just like with Pydantic models, you declare class attributes with type annotations and can use all the same validation features and tools, including different data types and additional validations with Field().

Pydantic v2Pydantic v1 config.py
from pydantic_settings import BaseSettings\n\n\nclass Settings(BaseSettings):\n    url: str = \"\"\n    queue: str = \"test-queue\"\n\n\nsettings = Settings()\n

Info

In Pydantic v1 you would import BaseSettings directly from pydantic instead of from pydantic_settings.

config.py
from pydantic import BaseSettings\n\n\nclass Settings(BaseSettings):\n    url: str = \"\"\n    queue: str = \"test-queue\"\n\n\nsettings = Settings()\n

When you create an instance of that Settings class (in this case, in the settings object), Pydantic will read the environment variables in a case-insensitive way. For example, an upper-case variable APP_NAME will still be read for the attribute app_name.

It will also convert and validate the data, so when you use that settings object, you will have data of the type you declared (e.g. items_per_user will be an int).

","boost":10},{"location":"getting-started/config/#using-the-settings","title":"Using the settings","text":"

Now you can use the new settings object in your application:

serve.py
import os\n\nfrom pydantic_settings import BaseSettings\n\nfrom faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\n\nclass Settings(BaseSettings):\n    url: str\n    queue: str = \"test-queue\"\n\n\nsettings = Settings(_env_file=os.getenv(\"ENV\", \".env\"))\n\nbroker = RabbitBroker(settings.url)\napp = FastStream(broker)\n\n\n@broker.subscriber(settings.queue)\nasync def handler(msg):\n    ...\n
","boost":10},{"location":"getting-started/config/#running-the-application","title":"Running the Application","text":"

You can run the application while passing the configuration parameters as environment variables. For example, you could set an URL:

URL=\"amqp://guest:guest@localhost:5672\" faststream run serve:app\n

Tip

To set multiple environment variables for a single command, separate them with spaces and put them all before the command.

","boost":10},{"location":"getting-started/config/#reading-a-env-file","title":"Reading a .env File","text":"

If you have many settings that may change frequently, especially in different environments, it might be useful to store them in a file and then read them as if they were environment variables.

This practice is common enough that it has a name; these environment variables are typically placed in a file named .env, commonly referred to as a \"dotenv\" file.

Tip

In Unix-like systems like Linux and macOS, a file starting with a dot (.) is considered a hidden file.

But a dotenv file doesn't really have to have that exact filename.

Pydantic supports reading from these types of files using an external library. You can learn more at Pydantic Settings: Dotenv (.env) support.

Tip

To use this feature, you need to install the python-dotenv library.

","boost":10},{"location":"getting-started/config/#the-env-file","title":"The .env File","text":"

You can create a .env file with contents like this:

URL=\"amqp://guest:guest@localhost:5672\"\nQUEUE=\"test-queue\"\n
","boost":10},{"location":"getting-started/config/#reading-settings-from-env","title":"Reading Settings from .env","text":"

Then update your config.py as follows:

import os\n\nfrom pydantic_settings import BaseSettings\n\n\nclass Settings(BaseSettings):\n    url: str\n    queue: str = \"test-queue\"\n\n\nsettings = Settings(_env_file=os.getenv(\"ENV\", \".env\"))\n

This way, you can specify different .env files directly from your terminal, which can be extremely helpful for various testing and production scenarios.

Note

By default, Pydantic will attempt to find a .env file. If it's not present, Pydantic will use the default field values.

","boost":10},{"location":"getting-started/config/#choosing-the-env-file-at-startup","title":"Choosing the .env File at Startup","text":"

Now you can run the apllication with different .env files like so:

ENV=.local.env faststream run serve:app\n

Or, for a production environment:

ENV=.production.env faststream run serve:app\n

Or even for a test environment:

ENV=.test.env pytest\n
","boost":10},{"location":"getting-started/context/","title":"Application Context","text":"

FastStreams has its own Dependency Injection container - Context, used to store application runtime objects and variables.

With this container, you can access both application scope and message processing scope objects. This functionality is similar to Depends usage.

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message=Context(),  # get access to raw message\n):\n    ...\n
from faststream import Context, FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message=Context(),  # get access to raw message\n):\n    ...\n
from faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message=Context(),  # get access to raw message\n):\n    ...\n
from faststream import Context, FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message=Context(),  # get access to raw message\n):\n    ...\n

But, with the Annotated Python feature usage, it is much closer to @pytest.fixture.

KafkaRabbitMQNATSRedis
from typing import Annotated\n\nfrom faststream import Context, FastStream\nfrom faststream.kafka import KafkaBroker\nfrom faststream.kafka.message import KafkaMessage\n\nMessage = Annotated[KafkaMessage, Context()]\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message: Message,  # get access to raw message\n):\n    ...\n
from typing import Annotated\n\nfrom faststream import Context, FastStream\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.rabbit.message import RabbitMessage\n\nMessage = Annotated[RabbitMessage, Context()]\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message: Message,  # get access to raw message\n):\n    ...\n
from typing import Annotated\n\nfrom faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.message import NatsMessage\n\nMessage = Annotated[NatsMessage, Context()]\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message: Message,  # get access to raw message\n):\n    ...\n
from typing import Annotated\n\nfrom faststream import Context, FastStream\nfrom faststream.redis import RedisBroker\nfrom faststream.redis.message import RedisMessage\n\nMessage = Annotated[RedisMessage, Context()]\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message: Message,  # get access to raw message\n):\n    ...\n
","boost":10},{"location":"getting-started/context/#usages","title":"Usages","text":"

By default, the context is available in the same place as Depends:

Tip

Fields obtained from the Context are editable, so editing them in a function means editing them everywhere.

","boost":10},{"location":"getting-started/context/#compatibility-with-regular-functions","title":"Compatibility with Regular Functions","text":"

To use context in other functions, use the @apply_types decorator. In this case, the context of the called function will correspond to the context of the event handler from which it was called.

from faststream import Context, apply_types\n\n@broker.subscriber(\"test\")\nasync def handler(body):\n    nested_func(body)\n\n@apply_types\ndef nested_func(body, logger=Context()):\n    logger.info(body)\n

In the example above, we did not pass the logger function at calling it; it was placed from context.

","boost":10},{"location":"getting-started/context/custom/","title":"Context Fields Declaration","text":"

You can also store your own objects in the Context.

","boost":10},{"location":"getting-started/context/custom/#global","title":"Global","text":"

To declare an application-level context field, you need to call the context.set_global method with with a key to indicate where the object will be placed in the context.

KafkaRabbitMQNATSRedis
from faststream import FastStream, ContextRepo, Context\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n@app.on_startup\nasync def set_global(context: ContextRepo):\n    context.set_global(\"secret_str\", \"my-perfect-secret\")\n
from faststream import FastStream, ContextRepo, Context\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n@app.on_startup\nasync def set_global(context: ContextRepo):\n    context.set_global(\"secret_str\", \"my-perfect-secret\")\n
from faststream import FastStream, ContextRepo, Context\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n@app.on_startup\nasync def set_global(context: ContextRepo):\n    context.set_global(\"secret_str\", \"my-perfect-secret\")\n
from faststream import FastStream, ContextRepo, Context\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n@app.on_startup\nasync def set_global(context: ContextRepo):\n    context.set_global(\"secret_str\", \"my-perfect-secret\")\n

Afterward, you can access your secret field in the usual way:

KafkaRabbitMQNATSRedis
@broker.subscriber(\"test-topic\")\nasync def handle(\n    msg: str,\n    secret_str: str=Context(),\n):\n    assert secret_str == \"my-perfect-secret\"\n
@broker.subscriber(\"test-queue\")\nasync def handle(\n    msg: str,\n    secret_str: str=Context(),\n):\n    assert secret_str == \"my-perfect-secret\"\n
@broker.subscriber(\"test-subject\")\nasync def handle(\n    msg: str,\n    secret_str: str=Context(),\n):\n    assert secret_str == \"my-perfect-secret\"\n
@broker.subscriber(\"test-channel\")\nasync def handle(\n    msg: str,\n    secret_str: str=Context(),\n):\n    assert secret_str == \"my-perfect-secret\"\n

In this case, the field becomes a global context field: it does not depend on the current message handler (unlike message)

To remove a field from the context use the reset_global method:

context.reset_global(\"my_key\")\n
","boost":10},{"location":"getting-started/context/custom/#local","title":"Local","text":"

To set a local context (available only within the message processing scope), use the context manager scope

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream, apply_types\nfrom faststream.kafka import KafkaBroker\nfrom faststream.kafka.annotations import ContextRepo, KafkaMessage\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    msg: str,\n    message: KafkaMessage,\n    context: ContextRepo,\n):\n    with context.scope(\"correlation_id\", message.correlation_id):\n        call()\n\n\n@apply_types\ndef call(\n    message: KafkaMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n
from faststream import Context, FastStream, apply_types\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.rabbit.annotations import ContextRepo, RabbitMessage\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    msg: str,\n    message: RabbitMessage,\n    context: ContextRepo,\n):\n    with context.scope(\"correlation_id\", message.correlation_id):\n        call()\n\n\n@apply_types\ndef call(\n    message: RabbitMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n
from faststream import Context, FastStream, apply_types\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import ContextRepo, NatsMessage\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    msg: str,\n    message: NatsMessage,\n    context: ContextRepo,\n):\n    with context.scope(\"correlation_id\", message.correlation_id):\n        call()\n\n\n@apply_types\ndef call(\n    message: NatsMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n
from faststream import Context, FastStream, apply_types\nfrom faststream.redis import RedisBroker\nfrom faststream.redis.annotations import ContextRepo, RedisMessage\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    msg: str,\n    message: RedisMessage,\n    context: ContextRepo,\n):\n    with context.scope(\"correlation_id\", message.correlation_id):\n        call()\n\n\n@apply_types\ndef call(\n    message: RedisMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n

You can also set the context by yourself, and it will remain within the current call stack until you clear it.

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream, apply_types, context\nfrom faststream.kafka import KafkaBroker\nfrom faststream.kafka.annotations import KafkaMessage\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    msg: str,\n    message: KafkaMessage,\n):\n    tag = context.set_local(\"correlation_id\", message.correlation_id)\n    call(tag)\n\n\n@apply_types\ndef call(\n    tag,\n    message: KafkaMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n    context.reset_local(\"correlation_id\", tag)\n
from faststream import Context, FastStream, apply_types, context\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.rabbit.annotations import RabbitMessage\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    msg: str,\n    message: RabbitMessage,\n):\n    tag = context.set_local(\"correlation_id\", message.correlation_id)\n    call(tag)\n\n\n@apply_types\ndef call(\n    tag,\n    message: RabbitMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n    context.reset_local(\"correlation_id\", tag)\n
from faststream import Context, FastStream, apply_types, context\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import NatsMessage\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    msg: str,\n    message: NatsMessage,\n):\n    tag = context.set_local(\"correlation_id\", message.correlation_id)\n    call(tag)\n\n\n@apply_types\ndef call(\n    tag,\n    message: NatsMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n    context.reset_local(\"correlation_id\", tag)\n
from faststream import Context, FastStream, apply_types, context\nfrom faststream.redis import RedisBroker\nfrom faststream.redis.annotations import RedisMessage\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    msg: str,\n    message: RedisMessage,\n):\n    tag = context.set_local(\"correlation_id\", message.correlation_id)\n    call(tag)\n\n\n@apply_types\ndef call(\n    tag,\n    message: RedisMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n    context.reset_local(\"correlation_id\", tag)\n
","boost":10},{"location":"getting-started/context/existed/","title":"Existing Fields","text":"

Context already contains some global objects that you can always access:

At the same time, thanks to contextlib.ContextVar, message is local for you current consumer scope.

","boost":10},{"location":"getting-started/context/existed/#access-to-context-fields","title":"Access to Context Fields","text":"

By default, the context searches for an object based on the argument name.

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker_object = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"test-topic\")\nasync def handle(\n    msg: str,\n    logger=Context(),\n    message=Context(),\n    broker=Context(),\n    context=Context(),\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream import Context, FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker_object = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"test-queue\")\nasync def handle(\n    msg: str,\n    logger=Context(),\n    message=Context(),\n    broker=Context(),\n    context=Context(),\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\n\nbroker_object = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"test-subject\")\nasync def handle(\n    msg: str,\n    logger=Context(),\n    message=Context(),\n    broker=Context(),\n    context=Context(),\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream import Context, FastStream\nfrom faststream.redis import RedisBroker\n\nbroker_object = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"test-channel\")\nasync def handle(\n    msg: str,\n    logger=Context(),\n    message=Context(),\n    broker=Context(),\n    context=Context(),\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
","boost":10},{"location":"getting-started/context/existed/#annotated-aliases","title":"Annotated Aliases","text":"

Also, FastStream has already created Annotated aliases to provide you with comfortable access to existing objects. You can import them directly from faststream or your broker-specific modules:

from faststream import Logger, ContextRepo\n
KafkaRabbitMQNATSRedis
from faststream.kafka.annotations import (\n    Logger, ContextRepo, KafkaMessage,\n    KafkaBroker, KafkaProducer, NoCast,\n)\n

faststream.kafka.KafkaMessage is an alias to faststream.kafka.annotations.KafkaMessage

from faststream.kafka import KafkaMessage\n

To use them, simply import and use them as subscriber argument annotations.

from faststream import Context, FastStream\nfrom faststream.kafka import KafkaBroker\nfrom faststream.kafka.annotations import (\n    ContextRepo,\n    KafkaMessage,\n    Logger,\n    KafkaBroker as BrokerAnnotation,\n)\n\nbroker_object = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"response-topic\")\nasync def handle_response(\n    msg: str,\n    logger: Logger,\n    message: KafkaMessage,\n    context: ContextRepo,\n    broker: BrokerAnnotation,\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream.rabbit.annotations import (\n    Logger, ContextRepo, RabbitMessage,\n    RabbitBroker, RabbitProducer, NoCast,\n)\n

faststream.rabbit.RabbitMessage is an alias to faststream.rabbit.annotations.RabbitMessage

from faststream.rabbit import RabbitMessage\n

To use them, simply import and use them as subscriber argument annotations.

from faststream import Context, FastStream\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.rabbit.annotations import (\n    ContextRepo,\n    RabbitMessage,\n    Logger,\n    RabbitBroker as BrokerAnnotation,\n)\n\nbroker_object = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"response-queue\")\nasync def handle_response(\n    msg: str,\n    logger: Logger,\n    message: RabbitMessage,\n    context: ContextRepo,\n    broker: BrokerAnnotation,\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream.nats.annotations import (\n    Logger, ContextRepo, NatsMessage,\n    NatsBroker, NatsProducer, NatsJsProducer,\n    Client, JsClient, NoCast,\n)\n

faststream.nats.NatsMessage is an alias to faststream.nats.annotations.NatsMessage

from faststream.nats import NatsMessage\n

To use them, simply import and use them as subscriber argument annotations.

from faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import (\n    ContextRepo,\n    NatsMessage,\n    Logger,\n    NatsBroker as BrokerAnnotation,\n)\n\nbroker_object = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"response-subject\")\nasync def handle_response(\n    msg: str,\n    logger: Logger,\n    message: NatsMessage,\n    context: ContextRepo,\n    broker: BrokerAnnotation,\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream.redis.annotations import (\n    Logger, ContextRepo, RedisMessage,\n    RedisBroker, Redis, NoCast,\n)\n

faststream.redis.RedisMessage is an alias to faststream.redis.annotations.RedisMessage

from faststream.redis import RedisMessage\n

To use them, simply import and use them as subscriber argument annotations.

from faststream import Context, FastStream\nfrom faststream.redis import RedisBroker\nfrom faststream.redis.annotations import (\n    ContextRepo,\n    RedisMessage,\n    Logger,\n    RedisBroker as BrokerAnnotation,\n)\n\nbroker_object = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"response-channel\")\nasync def handle_response(\n    msg: str,\n    logger: Logger,\n    message: RedisMessage,\n    context: ContextRepo,\n    broker: BrokerAnnotation,\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
","boost":10},{"location":"getting-started/context/extra/","title":"Context Extra Options","text":"

Additionally, Context provides you with some extra capabilities for working with containing objects.

","boost":10},{"location":"getting-started/context/extra/#default-values","title":"Default Values","text":"

For instance, if you attempt to access a field that doesn't exist in the global context, you will receive a pydantic.ValidationError exception.

However, you can set default values if needed.

KafkaRabbitMQNATSRedis
@broker.subscriber(\"test-topic\")\nasync def handle(\n    not_existed: None = Context(\"not_existed\", default=None),\n):\n    assert not_existed is None\n
@broker.subscriber(\"test-queue\")\nasync def handle(\n    not_existed: None = Context(\"not_existed\", default=None),\n):\n    assert not_existed is None\n
@broker.subscriber(\"test-subject\")\nasync def handle(\n    not_existed: None = Context(\"not_existed\", default=None),\n):\n    assert not_existed is None\n
@broker.subscriber(\"test-channel\")\nasync def handle(\n    not_existed: None = Context(\"not_existed\", default=None),\n):\n    assert not_existed is None\n
","boost":10},{"location":"getting-started/context/extra/#cast-context-types","title":"Cast Context Types","text":"

By default, context fields are NOT CAST to the type specified in their annotation.

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream, context\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\ncontext.set_global(\"secret\", \"1\")\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    secret: int = Context(),\n):\n    assert secret == \"1\"\n
from faststream import Context, FastStream, context\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\ncontext.set_global(\"secret\", \"1\")\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    secret: int = Context(),\n):\n    assert secret == \"1\"\n
from faststream import Context, FastStream, context\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\ncontext.set_global(\"secret\", \"1\")\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    secret: int = Context(),\n):\n    assert secret == \"1\"\n
from faststream import Context, FastStream, context\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\ncontext.set_global(\"secret\", \"1\")\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    secret: int = Context(),\n):\n    assert secret == \"1\"\n

If you require this functionality, you can enable the appropriate flag.

KafkaRabbitMQNATSRedis
@broker.subscriber(\"test-topic2\")\nasync def handle_int(\n    secret: int = Context(cast=True),\n):\n    assert secret == 1\n
@broker.subscriber(\"test-queue2\")\nasync def handle_int(\n    secret: int = Context(cast=True),\n):\n    assert secret == 1\n
@broker.subscriber(\"test-subject2\")\nasync def handle_int(\n    secret: int = Context(cast=True),\n):\n    assert secret == 1\n
@broker.subscriber(\"test-channel2\")\nasync def handle_int(\n    secret: int = Context(cast=True),\n):\n    assert secret == 1\n
","boost":10},{"location":"getting-started/context/fields/","title":"Access by Name","text":"

Sometimes, you may need to use a different name for the argument (not the one under which it is stored in the context) or get access to specific parts of the object. To do this, simply specify the name of what you want to access, and the context will provide you with the object.

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream\nfrom faststream.kafka import KafkaBroker\nfrom faststream.kafka.message import KafkaMessage\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    msg: KafkaMessage = Context(\"message\"),\n    correlation_id: str = Context(\"message.correlation_id\"),\n    user_header: str = Context(\"message.headers.user\"),\n):\n    assert msg.correlation_id == correlation_id\n    assert msg.headers[\"user\"] == user_header\n

This way you can get access to context object by its name

msg: KafkaMessage = Context(\"message\"),\n
from faststream import Context, FastStream\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.rabbit.message import RabbitMessage\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    msg: RabbitMessage = Context(\"message\"),\n    correlation_id: str = Context(\"message.correlation_id\"),\n    user_header: str = Context(\"message.headers.user\"),\n):\n    assert msg.correlation_id == correlation_id\n    assert msg.headers[\"user\"] == user_header\n

This way you can get access to context object by its name

msg: RabbitMessage = Context(\"message\"),\n
from faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.message import NatsMessage\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    msg: NatsMessage = Context(\"message\"),\n    correlation_id: str = Context(\"message.correlation_id\"),\n    user_header: str = Context(\"message.headers.user\"),\n):\n    assert msg.correlation_id == correlation_id\n    assert msg.headers[\"user\"] == user_header\n

This way you can get access to context object by its name

msg: NatsMessage = Context(\"message\"),\n
from faststream import Context, FastStream\nfrom faststream.redis import RedisBroker\nfrom faststream.redis.message import RedisMessage\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    msg: RedisMessage = Context(\"message\"),\n    correlation_id: str = Context(\"message.correlation_id\"),\n    user_header: str = Context(\"message.headers.user\"),\n):\n    assert msg.correlation_id == correlation_id\n    assert msg.headers[\"user\"] == user_header\n

This way you can get access to context object by its name

msg: RedisMessage = Context(\"message\"),\n

This way you can get access to context object specific field

correlation_id: str = Context(\"message.correlation_id\"),\n

Or even to a dict key

user_header: str = Context(\"message.headers.user\"),\n
","boost":10},{"location":"getting-started/contributing/CONTRIBUTING/","title":"Development","text":"

After cloning the project, you'll need to set up the development environment. Here are the guidelines on how to do this.

","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#virtual-environment-with-venv","title":"Virtual Environment with venv","text":"

Create a virtual environment in a directory using Python's venv module:

python -m venv venv\n

That will create a ./venv/ directory with Python binaries, allowing you to install packages in an isolated environment.

","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#activate-the-environment","title":"Activate the Environment","text":"

Activate the new environment with:

source ./venv/bin/activate\n

Ensure you have the latest pip version in your virtual environment:

python -m pip install --upgrade pip\n
","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#installing-dependencies","title":"Installing Dependencies","text":"

After activating the virtual environment as described above, run:

pip install -e \".[dev]\"\n

This will install all the dependencies and your local FastStream in your virtual environment.

","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#using-your-local-faststream","title":"Using Your local FastStream","text":"

If you create a Python file that imports and uses FastStream, and run it with the Python from your local environment, it will use your local FastStream source code.

Whenever you update your local FastStream source code, it will automatically use the latest version when you run your Python file again. This is because it is installed with -e.

This way, you don't have to \"install\" your local version to be able to test every change.

To use your local FastStream CLI, type:

python -m faststream ...\n
","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#running-tests","title":"Running Tests","text":"","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#pytest","title":"Pytest","text":"

To run tests with your current FastStream application and Python environment, use:

pytest tests\n# or\n./scripts/test.sh\n# with coverage output\n./scripts/test-cov.sh\n

In your project, you'll find some pytest marks:

By default, running pytest will execute \"not slow\" tests.

To run all tests use:

pytest -m 'all'\n

If you don't have a local broker instance running, you can run tests without those dependencies:

pytest -m 'not rabbit and not kafka and not nats and not redis'\n

To run tests based on RabbitMQ, Kafka, or other dependencies, the following dependencies are needed to be started as docker containers:

version: \"3\"\nservices:\n  # nosemgrep: yaml.docker-compose.security.writable-filesystem-service.writable-filesystem-service\n  rabbitmq:\n    image: rabbitmq:alpine\n    ports:\n      - \"5672:5672\"\n    # https://semgrep.dev/r?q=yaml.docker-compose.security.no-new-privileges.no-new-privileges\n    security_opt:\n      - no-new-privileges:true\n  # nosemgrep: yaml.docker-compose.security.writable-filesystem-service.writable-filesystem-service\n  kafka:\n    image: bitnami/kafka:3.5.0\n    ports:\n      - \"9092:9092\"\n    environment:\n      KAFKA_ENABLE_KRAFT: \"true\"\n      KAFKA_CFG_NODE_ID: \"1\"\n      KAFKA_CFG_PROCESS_ROLES: \"broker,controller\"\n      KAFKA_CFG_CONTROLLER_LISTENER_NAMES: \"CONTROLLER\"\n      KAFKA_CFG_LISTENERS: \"PLAINTEXT://:9092,CONTROLLER://:9093\"\n      KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP: \"CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT\"\n      KAFKA_CFG_ADVERTISED_LISTENERS: \"PLAINTEXT://127.0.0.1:9092\"\n      KAFKA_BROKER_ID: \"1\"\n      KAFKA_CFG_CONTROLLER_QUORUM_VOTERS: \"1@kafka:9093\"\n      ALLOW_PLAINTEXT_LISTENER: \"true\"\n    # https://semgrep.dev/r?q=yaml.docker-compose.security.no-new-privileges.no-new-privileges\n    security_opt:\n      - no-new-privileges:true\n  # nosemgrep: yaml.docker-compose.security.writable-filesystem-service.writable-filesystem-service\n  nats:\n    image: nats\n    command: -js\n    ports:\n      - 4222:4222\n      - 8222:8222  # management\n    # https://semgrep.dev/r?q=yaml.docker-compose.security.no-new-privileges.no-new-privileges\n    security_opt:\n      - no-new-privileges:true\n  # nosemgrep: yaml.docker-compose.security.writable-filesystem-service.writable-filesystem-service\n  redis:\n    image: redis:alpine\n    ports:\n      - 6379:6379\n    # https://semgrep.dev/r?q=yaml.docker-compose.security.no-new-privileges.no-new-privileges\n    security_opt:\n      - no-new-privileges:true\n

You can start the dependencies easily using provided script by running:

./scripts/start_test_env.sh\n

Once you are done with development and running tests, you can stop the dependencies' docker containers by running:

./scripts/stop_test_env.sh\n
","boost":3},{"location":"getting-started/contributing/docs/","title":"Documentation","text":"","boost":3},{"location":"getting-started/contributing/docs/#how-to-help","title":"How to help","text":"

You will be of invaluable help if you contribute to the documentation.

Such a contribution can be:

You can report all this in discussions on GitHub, start issue, or write about it in our discord group.

Note

Special thanks to those who are ready to offer help with the case and help in developing documentation, as well as translating it into other languages.

","boost":3},{"location":"getting-started/contributing/docs/#how-to-get-started","title":"How to get started","text":"

To develop the documentation, you don't even need to install the entire FastStream project as a whole.

Enough:

  1. Clone the project repository
  2. Create a virtual environment
    python -m venv venv\n
  3. Activate it
    source venv/bin/activate\n
  4. Install documentation dependencies
    pip install \".[devdocs]\"\n
  5. Go to the docs/ directory
  6. Start the local documentation server
    mkdocs serve\n

Now all changes in the documentation files will be reflected on your local version of the site. After making all the changes, you can issue a PR with them - and we will gladly accept it!

","boost":3},{"location":"getting-started/dependencies/","title":"Dependencies","text":"

FastStream uses the secondary library FastDepends for dependency management. This dependency system is literally borrowed from FastAPI, so if you know how to work with that framework, you'll be comfortable with dependencies in FastStream.

You can visit the FastDepends documentation for more details, but the key points and additions are covered here.

","boost":10},{"location":"getting-started/dependencies/#type-casting","title":"Type Casting","text":"

The key function in the dependency management and type conversion system in FastStream is the decorator @apply_types (also known as @inject in FastDepends).

By default, it applies to all event handlers, unless you disabled the same option when creating the broker.

KafkaRabbitMQNATSRedis
from faststream.kafka import KafkaBroker\nbroker = KafkaBroker(..., apply_types=False)\n
from faststream.rabbit import RabbitBroker\nbroker = RabbitBroker(..., apply_types=False)\n
from faststream.nats import NatsBroker\nbroker = NatsBroker(..., apply_types=False)\n
from faststream.redis import RedisBroker\nbroker = RedisBroker(..., apply_types=False)\n

Warning

Setting the apply_types=False flag not only disables type casting but also Depends and Context. If you want to disable only type casting, use validate=False instead.

This flag can be useful if you are using FastStream within another framework and you need to use its native dependency system.

","boost":10},{"location":"getting-started/dependencies/#dependency-injection","title":"Dependency Injection","text":"

To implement dependencies in FastStream, a special class called Depends is used

KafkaRabbitMQNATSRedis
from faststream import FastStream, Depends\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\ndef simple_dependency():\n    return 1\n\n@broker.subscriber(\"test\")\nasync def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
from faststream import FastStream, Depends\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\ndef simple_dependency():\n    return 1\n\n@broker.subscriber(\"test\")\nasync def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
from faststream import FastStream, Depends\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\ndef simple_dependency():\n    return 1\n\n@broker.subscriber(\"test\")\nasync def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
from faststream import FastStream, Depends\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\ndef simple_dependency():\n    return 1\n\n@broker.subscriber(\"test\")\nasync def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n

The first step: You need to declare a dependency, which can be any Callable object.

Callable

A \"Callable\" is an object that can be \"called\". It can be a function, a class, or a class method.

In other words, if you can write code like my_object() - my_object is Callable

KafkaRabbitMQNATSRedis
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n

Second step: Declare which dependencies you need using Depends

KafkaRabbitMQNATSRedis
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n

The last step: Just use the result of executing your dependency!

It's easy, isn't it?

Auto @apply_types

In the code above, we didn't use this decorator for our dependencies. However, it still applies to all functions used as dependencies. Please keep this in your mind.

","boost":10},{"location":"getting-started/dependencies/#top-level-dependencies","title":"Top-level Dependencies","text":"

If you don't need a dependency result, you can use the following code:

@broker.subscriber(\"test\")\ndef method(_ = Depends(...)): ...\n

But, using a special subscriber parameter is much more suitable:

@broker.subscriber(\"test\", dependencies=[Depends(...)])\ndef method(): ...\n

You can also declare broker-level dependencies, which will be applied to all broker's handlers:

broker = RabbitBroker(dependencies=[Depends(...)])\n
","boost":10},{"location":"getting-started/dependencies/#nested-dependencies","title":"Nested Dependencies","text":"

Dependencies can also contain other dependencies. This works in a very predictable way: just declare Depends in the dependent function.

KafkaRabbitMQNATSRedis
from faststream import FastStream, Depends\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\ndef another_dependency():\n    return 1\n\ndef simple_dependency(b: int = Depends(another_dependency)): # (1)\n    return b * 2\n\n@broker.subscriber(\"test\")\nasync def handler(\n    body: dict,\n    a: int = Depends(another_dependency),\n    b: int = Depends(simple_dependency)):\n    assert (a + b) == 3\n
  1. A nested dependency is called here
from faststream import FastStream, Depends\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\ndef another_dependency():\n    return 1\n\ndef simple_dependency(b: int = Depends(another_dependency)): # (1)\n    return b * 2\n\n@broker.subscriber(\"test\")\nasync def handler(\n    body: dict,\n    a: int = Depends(another_dependency),\n    b: int = Depends(simple_dependency)):\n    assert (a + b) == 3\n
  1. A nested dependency is called here
from faststream import FastStream, Depends\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\ndef another_dependency():\n    return 1\n\ndef simple_dependency(b: int = Depends(another_dependency)): # (1)\n    return b * 2\n\n@broker.subscriber(\"test\")\nasync def handler(\n    body: dict,\n    a: int = Depends(another_dependency),\n    b: int = Depends(simple_dependency)):\n    assert (a + b) == 3\n
  1. A nested dependency is called here
from faststream import FastStream, Depends\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\ndef another_dependency():\n    return 1\n\ndef simple_dependency(b: int = Depends(another_dependency)): # (1)\n    return b * 2\n\n@broker.subscriber(\"test\")\nasync def handler(\n    body: dict,\n    a: int = Depends(another_dependency),\n    b: int = Depends(simple_dependency)):\n    assert (a + b) == 3\n
  1. A nested dependency is called here

Caching

In the example above, the another_dependency function will be called at ONCE! FastDepends caches all dependency execution results within ONE @apply_types call stack. This means that all nested dependencies will receive the cached result of dependency execution. But, between different calls of the main function, these results will be different.

To prevent this behavior, just use Depends(..., cache=False). In this case, the dependency will be used for each function in the call stack where it is used.

","boost":10},{"location":"getting-started/dependencies/#use-with-regular-functions","title":"Use with Regular Functions","text":"

You can use the decorator @apply_types not only with @broker.subscriber(...), but also with regular functions, both synchronous and asynchronous.

SyncAsync
from faststream import Depends, apply_types\n\ndef simple_dependency(a: int, b: int = 3):\n    return a + b\n\n@apply_types\ndef method(a: int, d: int = Depends(simple_dependency)):\n    return a + d\n\ndef test_sync_dependency():\n    assert method(\"1\") == 5\n
import asyncio\nimport pytest\nfrom faststream import Depends, apply_types\n\nasync def simple_dependency(a: int, b: int = 3):\n    return a + b\n\ndef another_dependency(a: int):\n    return a\n\n@apply_types\nasync def method(\n    a: int,\n    b: int = Depends(simple_dependency),\n    c: int = Depends(another_dependency),\n):\n    return a + b + c\n\n@pytest.mark.asyncio\nasync def test_async_dependency():\n    assert 6 == await method(\"1\")\n

Be careful

In asynchronous code, you can use both synchronous and asynchronous dependencies. But in synchronous code, only synchronous dependencies are available to you.

","boost":10},{"location":"getting-started/dependencies/#casting-dependency-types","title":"Casting Dependency Types","text":"

FastDepends, used by FastStream, also gives the type return. This means that the value returned by the dependency will be be cast to the type twice: as return for dependencies and as the input argument of the main function. This does not incur additional costs if these types have the same annotation. Just keep it in mind. Or not... Anyway, I've warned you.

from faststream import Depends, apply_types\n\ndef simple_dependency(a: int, b: int = 3) -> str:\n    return a + b  # 'return' is cast to `str` for the first time\n\n@apply_types\ndef method(a: int, d: int = Depends(simple_dependency)):\n    # 'd' is cast to `int` for the second time\n    return a + d\n\nassert method(\"1\") == 5\n

Also, the result of executing the dependency is cached. If you use this dependency in N functions, this cached result will be converted to type N times (at the input to the function being used).

To avoid problems with this, use mypy or just be careful with the annotation of types in your project.

","boost":10},{"location":"getting-started/dependencies/global/","title":"Global","text":""},{"location":"getting-started/dependencies/testing/","title":"Testing","text":"

https://lancetnik.github.io/FastDepends/tutorial/overrides/

"},{"location":"getting-started/integrations/django/","title":"Using FastStream with Django","text":"

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel. It\u2019s free and open source.

In this tutorial, let's see how to use the FastStream app alongside a Django app.

","boost":10},{"location":"getting-started/integrations/django/#asgi","title":"ASGI","text":"

ASGI protocol supports lifespan events, and Django can be served as an ASGI application. So, the best way to integrate FastStream with the Django is by using ASGI lifespan. You can write it by yourself (it is really easy) or use something like this, but the prefered way for us is using Starlette Router.

Starlette Router allows you to serve any ASGI application you want, and it also supports lifespans. So, you can use it in your project to serve your regular Django ASGI and start up your FastStream broker too. Additionally, Starlette has much better static files support, providing an extra zero-cost feature.

","boost":10},{"location":"getting-started/integrations/django/#default-django-application","title":"Default Django Application","text":"

Well, lets take a look at a default Django asgi.py

asgi.py
import os\n\nfrom django.core.asgi import get_asgi_application\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\")\n\napplication = get_asgi_application()\n

You can already serve it using any ASGI server

For example, using uvicorn:

uvicorn asgi:app --workers 4\n

Or you can use Gunicorn with uvicorn workers

gunicorn asgi:app --workers 4 --worker-class uvicorn.workers.UvicornWorker\n

Your Django views, models and other stuff has no any changes if you serving it through ASGI, so you need no worry about it.

","boost":10},{"location":"getting-started/integrations/django/#faststream-integration","title":"FastStream Integration","text":"","boost":10},{"location":"getting-started/integrations/django/#serving-django-via-starlette","title":"Serving Django via Starlette","text":"

Now, we need to modify our asgi.py to serve it using Starlette

asgi.py
# regular Djano stuff\nimport os\n\nfrom django.core.asgi import get_asgi_application\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\")\n\ndjango_asgi = get_asgi_application()\n\n# Starlette serving\nfrom starlette.applications import Starlette\nfrom starlette.routing import Mount\n\napp = Starlette(\n    routes=(\n        Mount(\"/\", django_asgi()),  # redirect all requests to Django\n    ),\n)\n
","boost":10},{"location":"getting-started/integrations/django/#serving-static-files-with-starlette","title":"Serving static files with Starlette","text":"

Also, Starlette has a better static files provider than original Django one, so we can reuse it too.

Just add this line to your settings.py

settings.py
STATIC_ROOT = \"static/\"\n

And collect all static files by default Django command

python manage.py collectstatic\n

It creates a static/ directory in the root of your project, so you can serve it using Starlette

asgi.py
# Code above omitted \ud83d\udc46\n\nfrom starlette.staticfiles import StaticFiles\n\napp = Starlette(\n    routes=(\n        # /static is your STATIC_URL setting\n        Mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\"),\n        Mount(\"/\", get_asgi_application()),  # regular Django ASGI\n    ),\n)\n
","boost":10},{"location":"getting-started/integrations/django/#faststream-lifespan","title":"FastStream lifespan","text":"

Finally, we can add our FastStream integration like a regular lifespan

asgi.py
# Code above omitted \ud83d\udc46\n\nfrom contextlib import asynccontextmanager\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker()\n\n@asynccontextmanager\nasync def broker_lifespan(app):\n    await broker.start()\n    try:\n        yield\n    finally:\n        await broker.close()\n\napp = Starlette(\n    ...,\n    lifespan=broker_lifespan,\n)\n

Note

The code imports KafkaBroker as our application is going to connect with Kafka. Depending on your requirements, import the necessary service's broker from the options provided by FastStream, such as RabbitBroker, NatsBroker or KafkaBroker.

Full Example asgi.py
import os\nfrom contextlib import asynccontextmanager\n\nfrom django.core.asgi import get_asgi_application\nfrom starlette.applications import Starlette\nfrom starlette.routing import Mount\nfrom starlette.staticfiles import StaticFiles\nfrom faststream.kafka import KafkaBroker\n\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\")\n\nbroker = KafkaBroker()\n\n@asynccontextmanager\nasync def broker_lifespan(app):\n    await broker.start()\n    try:\n        yield\n    finally:\n        await broker.close()\n\napp = Starlette(\n    routes=(\n        Mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\"),\n        Mount(\"/\", get_asgi_application()),\n    ),\n    lifespan=broker_lifespan,\n)\n

This way we can easely integrate our FastStream apllication with the Django!

","boost":10},{"location":"getting-started/integrations/fastapi/","title":"FastAPI Plugin","text":"","boost":10},{"location":"getting-started/integrations/fastapi/#handling-messages","title":"Handling messages","text":"

FastStream can be used as a part of FastAPI.

Just import a StreamRouter you need and declare the message handler in the same way as with a regular FastStream application.

Tip

When used in this way, FastStream does not use its own dependency system but integrates into FastAPI. That is, you can use Depends, BackgroundTasks and other original FastAPI features as if it were a regular HTTP endpoint, but you can't use faststream.Context and faststream.Depends.

Note that the code below uses fastapi.Depends, not faststream.Depends.

Also, instead original faststream.Context you should use faststream.[broker].fastapi.Context (the same with already created annotations)

KafkaRabbitMQNATSRedis
from fastapi import Depends, FastAPI\nfrom pydantic import BaseModel\n\nfrom faststream.kafka.fastapi import KafkaRouter, Logger\n\nrouter = KafkaRouter(\"localhost:9092\")\n\nclass Incoming(BaseModel):\n    m: dict\n\ndef call():\n    return True\n\n@router.subscriber(\"test\")\n@router.publisher(\"response\")\nasync def hello(m: Incoming, logger: Logger, d=Depends(call)):\n    logger.info(m)\n    return {\"response\": \"Hello, Kafka!\"}\n\n@router.get(\"/\")\nasync def hello_http():\n    return \"Hello, HTTP!\"\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom pydantic import BaseModel\n\nfrom faststream.rabbit.fastapi import RabbitRouter, Logger\n\nrouter = RabbitRouter(\"amqp://guest:guest@localhost:5672/\")\n\nclass Incoming(BaseModel):\n    m: dict\n\ndef call():\n    return True\n\n@router.subscriber(\"test\")\n@router.publisher(\"response\")\nasync def hello(m: Incoming, logger: Logger, d=Depends(call)):\n    logger.info(m)\n    return {\"response\": \"Hello, Rabbit!\"}\n\n@router.get(\"/\")\nasync def hello_http():\n    return \"Hello, HTTP!\"\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom pydantic import BaseModel\n\nfrom faststream.nats.fastapi import NatsRouter, Logger\n\nrouter = NatsRouter(\"nats://localhost:4222\")\n\nclass Incoming(BaseModel):\n    m: dict\n\ndef call():\n    return True\n\n@router.subscriber(\"test\")\n@router.publisher(\"response\")\nasync def hello(m: Incoming, logger: Logger, d=Depends(call)):\n    logger.info(m)\n    return {\"response\": \"Hello, NATS!\"}\n\n@router.get(\"/\")\nasync def hello_http():\n    return \"Hello, HTTP!\"\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom pydantic import BaseModel\n\nfrom faststream.redis.fastapi import RedisRouter, Logger\n\nrouter = RedisRouter(\"redis://localhost:6379\")\n\nclass Incoming(BaseModel):\n    m: dict\n\ndef call():\n    return True\n\n@router.subscriber(\"test\")\n@router.publisher(\"response\")\nasync def hello(m: Incoming, logger: Logger, d=Depends(call)):\n    logger.info(m)\n    return {\"response\": \"Hello, Redis!\"}\n\n@router.get(\"/\")\nasync def hello_http():\n    return \"Hello, HTTP!\"\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n

When processing a message from a broker, the entire message body is placed simultaneously in both the body and path request parameters. You can access them in any way convenient for you. The message header is placed in headers.

Also, this router can be fully used as an HttpRouter (of which it is the inheritor). So, you can use it to declare any get, post, put and other HTTP methods. For example, this is done at line 20.

Warning

If your ASGI server does not support installing state inside lifespan, you can disable this behavior as follows:

router = StreamRouter(..., setup_state=False)\n

However, after that, you will not be able to access the broker from your application's state (but it is still available as the router.broker).

","boost":10},{"location":"getting-started/integrations/fastapi/#accessing-the-broker-object","title":"Accessing the Broker Object","text":"

Inside each router, there is a broker. You can easily access it if you need to send a message to MQ:

KafkaRabbitMQNATSRedis
from fastapi import FastAPI\n\nfrom faststream.kafka.fastapi import KafkaRouter\n\nrouter = KafkaRouter(\"localhost:9092\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\n@router.get(\"/\")\nasync def hello_http():\n    await router.broker.publish(\"Hello, Kafka!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.rabbit.fastapi import RabbitRouter\n\nrouter = RabbitRouter(\"amqp://guest:guest@localhost:5672/\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\n@router.get(\"/\")\nasync def hello_http():\n    await router.broker.publish(\"Hello, Rabbit!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.nats.fastapi import NatsRouter\n\nrouter = NatsRouter(\"nats://localhost:4222\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\n@router.get(\"/\")\nasync def hello_http():\n    await router.broker.publish(\"Hello, NATS!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.redis.fastapi import RedisRouter\n\nrouter = RedisRouter(\"redis://localhost:6379\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\n@router.get(\"/\")\nasync def hello_http():\n    await router.broker.publish(\"Hello, Redis!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n

Also, you can use the following Depends to access the broker if you want to use it at different parts of your program:

KafkaRabbitMQNATSRedis
from fastapi import Depends, FastAPI\nfrom typing_extensions import Annotated\n\nfrom faststream.kafka import KafkaBroker, fastapi\n\nrouter = fastapi.KafkaRouter(\"localhost:9092\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\ndef broker():\n    return router.broker\n\n\n@router.get(\"/\")\nasync def hello_http(broker: Annotated[KafkaBroker, Depends(broker)]):\n    await broker.publish(\"Hello, Kafka!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom typing_extensions import Annotated\n\nfrom faststream.rabbit import RabbitBroker, fastapi\n\nrouter = fastapi.RabbitRouter(\"amqp://guest:guest@localhost:5672/\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\ndef broker():\n    return router.broker\n\n\n@router.get(\"/\")\nasync def hello_http(broker: Annotated[RabbitBroker, Depends(broker)]):\n    await broker.publish(\"Hello, Rabbit!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom typing_extensions import Annotated\n\nfrom faststream.nats import NatsBroker, fastapi\n\nrouter = fastapi.NatsRouter(\"nats://localhost:4222\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\ndef broker():\n    return router.broker\n\n\n@router.get(\"/\")\nasync def hello_http(broker: Annotated[NatsBroker, Depends(broker)]):\n    await broker.publish(\"Hello, NATS!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom typing_extensions import Annotated\n\nfrom faststream.redis import RedisBroker, fastapi\n\nrouter = fastapi.RedisRouter(\"redis://localhost:6379\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\ndef broker():\n    return router.broker\n\n\n@router.get(\"/\")\nasync def hello_http(broker: Annotated[RedisBroker, Depends(broker)]):\n    await broker.publish(\"Hello, Redis!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n

Or you can access the broker from a FastAPI application state (if you don't disable it with setup_state=False):

from fastapi import Request\n\n@app.get(\"/\")\ndef main(request: Request):\n    broker = request.state.broker\n
","boost":10},{"location":"getting-started/integrations/fastapi/#after_startup","title":"@after_startup","text":"

The FastStream application has the @after_startup hook, which allows you to perform operations with your message broker after the connection is established. This can be extremely convenient for managing your brokers' objects and/or sending messages. This hook is also available for your FastAPI StreamRouter

KafkaRabbitMQNATSRedis
from fastapi import FastAPI\n\nfrom faststream.kafka.fastapi import KafkaRouter\n\nrouter = KafkaRouter(\"localhost:9092\")\n\n\n@router.subscriber(\"test\")\nasync def hello(msg: str):\n    return {\"response\": \"Hello, Kafka!\"}\n\n\n@router.after_startup\nasync def test(app: FastAPI):\n    await router.broker.publish(\"Hello!\", \"test\")\n\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.rabbit.fastapi import RabbitRouter\n\nrouter = RabbitRouter(\"amqp://guest:guest@localhost:5672/\")\n\n\n@router.subscriber(\"test\")\nasync def hello(msg: str):\n    return {\"response\": \"Hello, Rabbit!\"}\n\n\n@router.after_startup\nasync def test(app: FastAPI):\n    await router.broker.publish(\"Hello!\", \"test\")\n\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.nats.fastapi import NatsRouter\n\nrouter = NatsRouter(\"nats://localhost:4222\")\n\n\n@router.subscriber(\"test\")\nasync def hello(msg: str):\n    return {\"response\": \"Hello, NATS!\"}\n\n\n@router.after_startup\nasync def test(app: FastAPI):\n    await router.broker.publish(\"Hello!\", \"test\")\n\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.redis.fastapi import RedisRouter\n\nrouter = RedisRouter(\"redis://localhost:6379\")\n\n\n@router.subscriber(\"test\")\nasync def hello(msg: str):\n    return {\"response\": \"Hello, Redis!\"}\n\n\n@router.after_startup\nasync def test(app: FastAPI):\n    await router.broker.publish(\"Hello!\", \"test\")\n\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
","boost":10},{"location":"getting-started/integrations/fastapi/#documentation","title":"Documentation","text":"

When using FastStream as a router for FastAPI, the framework automatically registers endpoints for hosting AsyncAPI documentation into your application with the following default values:

KafkaRabbitMQNATSRedis
from faststream.kafka.fastapi import KafkaRouter\n\nrouter = KafkaRouter(\n    ...,\n    schema_url=\"/asyncapi\",\n    include_in_schema=True,\n)\n
from faststream.rabbit.fastapi import RabbitRouter\n\nrouter = RabbitRouter(\n    ...,\n    schema_url=\"/asyncapi\",\n    include_in_schema=True,\n)\n
from faststream.nats.fastapi import NatsRouter\n\nrouter = NatsRouter(\n    ...,\n    schema_url=\"/asyncapi\",\n    include_in_schema=True,\n)\n
from faststream.redis.fastapi import RedisRouter\n\nrouter = RedisRouter(\n    ...,\n    schema_url=\"/asyncapi\",\n    include_in_schema=True,\n)\n

This way, you will have three routes to interact with your application's AsyncAPI schema:

","boost":10},{"location":"getting-started/integrations/fastapi/#testing","title":"Testing","text":"

To test your FastAPI StreamRouter, you can still use it with the TestClient:

KafkaRabbitMQNATSRedis
import pytest\n\nfrom faststream.kafka import TestKafkaBroker, fastapi\n\nrouter = fastapi.KafkaRouter()\n\n\n@router.subscriber(\"test\")\nasync def handler(msg: str):\n    ...\n\n\n@pytest.mark.asyncio\nasync def test_router():\n    async with TestKafkaBroker(router.broker) as br:\n        await br.publish(\"Hi!\", \"test\")\n\n        handler.mock.assert_called_once_with(\"Hi!\")\n
import pytest\n\nfrom faststream.rabbit import TestRabbitBroker, fastapi\n\nrouter = fastapi.RabbitRouter()\n\n\n@router.subscriber(\"test\")\nasync def handler(msg: str):\n    ...\n\n\n@pytest.mark.asyncio\nasync def test_router():\n    async with TestRabbitBroker(router.broker) as br:\n        await br.publish(\"Hi!\", \"test\")\n\n        handler.mock.assert_called_once_with(\"Hi!\")\n
import pytest\n\nfrom faststream.nats import TestNatsBroker, fastapi\n\nrouter = fastapi.NatsRouter()\n\n\n@router.subscriber(\"test\")\nasync def handler(msg: str):\n    ...\n\n\n@pytest.mark.asyncio\nasync def test_router():\n    async with TestNatsBroker(router.broker) as br:\n        await br.publish(\"Hi!\", \"test\")\n\n        handler.mock.assert_called_once_with(\"Hi!\")\n
import pytest\n\nfrom faststream.redis import TestRedisBroker, fastapi\n\nrouter = fastapi.RedisRouter()\n\n\n@router.subscriber(\"test\")\nasync def handler(msg: str):\n    ...\n\n\n@pytest.mark.asyncio\nasync def test_router():\n    async with TestRedisBroker(router.broker) as br:\n        await br.publish(\"Hi!\", \"test\")\n\n        handler.mock.assert_called_once_with(\"Hi!\")\n
","boost":10},{"location":"getting-started/integrations/fastapi/#miltiple-routers","title":"Miltiple Routers","text":"

Using FastStream as a FastAPI plugin you are still able to separate messages processing logic between different routers (like with a regular HTTPRouter). But it can be confusing - how you should include multiple routers, if we have to setup router.lifespan_context as a FastAPI object lifespan.

You can make it in a two ways, depends on you reminds.

","boost":10},{"location":"getting-started/integrations/fastapi/#routers-nesting","title":"Routers nesting","text":"

If you want to use the SAME CONNECTION for all of you routers you should nest them each other and finally use only the core router to include it into FastAPI object.

KafkaRabbitMQNATSRedis
from fastapi import FastAPI\nfrom faststream.kafka.fastapi import KafkaRouter\n\ncore_router = KafkaRouter()\nnested_router = KafkaRouter()\n\n@core_router.subscriber(\"core-topic\")\nasync def handler():\n    ...\n\n@nested_router.subscriber(\"nested-topic\")\nasync def nested_handler():\n    ...\n\ncore_router.include_router(nested_router)\n\napp = FastAPI(lifespan=core_router.lifespan_context)\napp.include_router(core_router)\n
from fastapi import FastAPI\nfrom faststream.rabbit.fastapi import RabbitRouter\n\ncore_router = RabbitRouter()\nnested_router = RabbitRouter()\n\n@core_router.subscriber(\"core-queue\")\nasync def handler():\n    ...\n\n@nested_router.subscriber(\"nested-queue\")\nasync def nested_handler():\n    ...\n\ncore_router.include_router(nested_router)\n\napp = FastAPI(lifespan=core_router.lifespan_context)\napp.include_router(core_router)\n
from fastapi import FastAPI\nfrom faststream.nats.fastapi import NatsRouter\n\ncore_router = NatsRouter()\nnested_router = NatsRouter()\n\n@core_router.subscriber(\"core-subject\")\nasync def handler():\n    ...\n\n@nested_router.subscriber(\"nested-subject\")\nasync def nested_handler():\n    ...\n\ncore_router.include_router(nested_router)\n\napp = FastAPI(lifespan=core_router.lifespan_context)\napp.include_router(core_router)\n
from fastapi import FastAPI\nfrom faststream.redis.fastapi import RedisRouter\n\ncore_router = RedisRouter()\nnested_router = RedisRouter()\n\n@core_router.subscriber(\"core-channel\")\nasync def handler():\n    ...\n\n@nested_router.subscriber(\"nested-channel\")\nasync def nested_handler():\n    ...\n\ncore_router.include_router(nested_router)\n\napp = FastAPI(lifespan=core_router.lifespan_context)\napp.include_router(core_router)\n

This way the core router collects all nested routers publishers and subscribers and stores it like its own.

","boost":10},{"location":"getting-started/integrations/fastapi/#custom-lifespan","title":"Custom lifespan","text":"

Overwise, if you want to has multiple connections to different broker instances, you should start routers independently in your custom lifespan

KafkaRabbitMQNATSRedis
from contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom faststream.kafka.fastapi import KafkaRouter\n\ncore_router = KafkaRouter()\nnested_router = KafkaRouter()\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    async with (\n        core_router.lifespan_context(app),\n        nested_router.lifespan_context(app),\n    ):\n        yield\n\napp = FastAPI(lifespan=lifespan)\napp.include_router(core_router)\napp.include_router(nested_router)\n
from contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom faststream.rabbit.fastapi import RabbitRouter\n\ncore_router = RabbitRouter()\nnested_router = RabbitRouter()\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    async with (\n        core_router.lifespan_context(app),\n        nested_router.lifespan_context(app),\n    ):\n        yield\n\napp = FastAPI(lifespan=lifespan)\napp.include_router(core_router)\napp.include_router(nested_router)\n
from contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom faststream.nats.fastapi import NatsRouter\n\ncore_router = NatsRouter()\nnested_router = NatsRouter()\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    async with (\n        core_router.lifespan_context(app),\n        nested_router.lifespan_context(app),\n    ):\n        yield\n\napp = FastAPI(lifespan=lifespan)\napp.include_router(core_router)\napp.include_router(nested_router)\n
from contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom faststream.redis.fastapi import RedisRouter\n\ncore_router = RedisRouter()\nnested_router = RedisRouter()\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    async with (\n        core_router.lifespan_context(app),\n        nested_router.lifespan_context(app),\n    ):\n        yield\n\napp = FastAPI(lifespan=lifespan)\napp.include_router(core_router)\napp.include_router(nested_router)\n

Warning

This way you lose AsyncAPI schema, but we are working on it.

","boost":10},{"location":"getting-started/integrations/frameworks/","title":"INTEGRATIONS","text":"

FastStream brokers are very easy to integrate with any of your applications: it is enough to initialize the broker at startup and close it correctly at the end of your application.

Most HTTP frameworks have built-in lifecycle hooks for this.

FastAPILitestarAiohttpBlacksheepFalconQuartSanic

Tip

If you want to use FastStream in conjunction with FastAPI, perhaps you should use a special plugin

from contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    await broker.start()\n    yield\n    await broker.close()\n\napp = FastAPI(lifespan=lifespan)\n\n@app.get(\"/\")\ndef read_root():\n    return {\"Hello\": \"World\"}\n
from litestar import Litestar, get\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\n\n@broker.subscriber(\"queue\")\nasync def handle(msg):\n    print(msg)\n\n@get(\"/\")\nasync def index() -> str:\n    return \"Hello, world!\"\n\napp = Litestar(\n    [index],\n    on_startup=(broker.start,),\n    on_shutdown=(broker.close,),\n)\n
from aiohttp import web\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\nasync def start_broker(app):\n    await broker.start()\n\n\nasync def stop_broker(app):\n    await broker.close()\n\n\nasync def hello(request):\n    return web.Response(text=\"Hello, world\")\n\n\napp = web.Application()\napp.add_routes([web.get(\"/\", hello)])\napp.on_startup.append(start_broker)\napp.on_cleanup.append(stop_broker)\n\n\nif __name__ == \"__main__\":\n    web.run_app(app)\n
from blacksheep import Application\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\napp = Application()\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\n@app.on_start\nasync def start_broker(application: Application) -> None:\n    await broker.start()\n\n\n@app.on_stop\nasync def stop_broker(application: Application) -> None:\n    await broker.close()\n\n\n@app.route(\"/\")\nasync def home():\n    return \"Hello, World!\"\n
import falcon\nimport falcon.asgi\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\nclass ThingsResource:\n    async def on_get(self, req, resp):\n        resp.status = falcon.HTTP_200\n        resp.content_type = falcon.MEDIA_TEXT\n        resp.text = (\n            \"\\nTwo things awe me most, the starry sky \"\n            \"above me and the moral law within me.\\n\"\n            \"\\n\"\n            \"    ~ Immanuel Kant\\n\\n\"\n        )\n\n\nclass StreamMiddleware:\n    async def process_startup(self, scope, event):\n        await broker.start()\n\n    async def process_shutdown(self, scope, event):\n        await broker.close()\n\n\napp = falcon.asgi.App()\napp.add_middleware(StreamMiddleware())\napp.add_route(\"/things\", ThingsResource())\n
from quart import Quart\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\napp = Quart(__name__)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\n@app.before_serving\nasync def start_broker():\n    await broker.start()\n\n\n@app.after_serving\nasync def stop_broker():\n    await broker.close()\n\n\n@app.route(\"/\")\nasync def json():\n    return {\"hello\": \"world\"}\n
from sanic import Sanic\nfrom sanic.response import text\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\napp = Sanic(\"MyHelloWorldApp\")\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\n@app.after_server_start\nasync def start_broker(app, loop):\n    await broker.start()\n\n\n@app.after_server_stop\nasync def stop_broker(app, loop):\n    await broker.close()\n\n\n@app.get(\"/\")\nasync def hello_world(request):\n    return text(\"Hello, world.\")\n

However, even if such a hook is not provided, you can do it yourself.

Tornado
import asyncio\n\nimport tornado.web\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\nclass MainHandler(tornado.web.RequestHandler):\n    def get(self):\n        self.write(\"Hello, world\")\n\n\ndef make_app():\n    return tornado.web.Application(\n        [\n            (r\"/\", MainHandler),\n        ]\n    )\n\n\nasync def main():\n    app = make_app()\n    app.listen(8888)\n\n    await broker.start()\n    try:\n        await asyncio.Event().wait()\n    finally:\n        await broker.close()\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n
","boost":10},{"location":"getting-started/lifespan/","title":"Lifespan Events","text":"

Sometimes you need to define the logic that should be executed before launching the application. This means that the code will be executed once - even before your application starts receiving messages.

Also, you may need to terminate some processes after stopping the application. In this case, your code will also be executed exactly once: but after the completion of the main application.

Since this code is executed before the application starts and after it stops, it covers the entire lifecycle (lifespan) of the application.

This can be very useful for initializing your application settings at startup, raising a pool of connections to a database, or running machine learning models.

","boost":10},{"location":"getting-started/lifespan/context/","title":"Lifespan Context Manager","text":"

Also, you can define startup and shutdown logic using the lifespan parameter of the FastSTream app, and a \"context manager\" (I'll show you what that is in a second).

Let's start with an example from hooks page and refactor it using \"context manager\".

We create an async function lifespan() with yield like this:

KafkaRabbitMQNATSRedis
from contextlib import asynccontextmanager\n\nfrom faststream import Context, ContextRepo, FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n\ndef fake_ml_model_answer(x: float):\n    return x * 42\n\n\n@asynccontextmanager\nasync def lifespan(context: ContextRepo):\n    # load fake ML model\n    ml_models = { \"answer_to_everything\": fake_ml_model_answer }\n    context.set_global(\"model\", ml_models)\n\n    yield\n\n    # Clean up the ML models and release the resources\n    ml_models.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n\n\napp = FastStream(broker, lifespan=lifespan)\n
from contextlib import asynccontextmanager\n\nfrom faststream import Context, ContextRepo, FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\n\n\ndef fake_ml_model_answer(x: float):\n    return x * 42\n\n\n@asynccontextmanager\nasync def lifespan(context: ContextRepo):\n    # load fake ML model\n    ml_models = { \"answer_to_everything\": fake_ml_model_answer }\n    context.set_global(\"model\", ml_models)\n\n    yield\n\n    # Clean up the ML models and release the resources\n    ml_models.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n\n\napp = FastStream(broker, lifespan=lifespan)\n
from contextlib import asynccontextmanager\n\nfrom faststream import Context, ContextRepo, FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\n\n\ndef fake_ml_model_answer(x: float):\n    return x * 42\n\n\n@asynccontextmanager\nasync def lifespan(context: ContextRepo):\n    # load fake ML model\n    ml_models = { \"answer_to_everything\": fake_ml_model_answer }\n    context.set_global(\"model\", ml_models)\n\n    yield\n\n    # Clean up the ML models and release the resources\n    ml_models.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n\n\napp = FastStream(broker, lifespan=lifespan)\n
from contextlib import asynccontextmanager\n\nfrom faststream import Context, ContextRepo, FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\n\n\ndef fake_ml_model_answer(x: float):\n    return x * 42\n\n\n@asynccontextmanager\nasync def lifespan(context: ContextRepo):\n    # load fake ML model\n    ml_models = { \"answer_to_everything\": fake_ml_model_answer }\n    context.set_global(\"model\", ml_models)\n\n    yield\n\n    # Clean up the ML models and release the resources\n    ml_models.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n\n\napp = FastStream(broker, lifespan=lifespan)\n

As you can see, lifespan parameter is much suitable for case (than @app.on_startup and @app.after_shutdown separated calls) if you have object needs to process at application startup and shutdown both.

Tip

lifespan starts BEFORE your broken started (@app.on_startup hook) and AFTER broker was shutdown (@app.after_shutdown), so you can't publish any messages here.

If you want to make some actions will already/still running broker, please use @app.after_startup and @app.on_shutdown hooks.

Also, lifespan supports all FastStream hooks features:

","boost":10},{"location":"getting-started/lifespan/hooks/","title":"Lifespan Hooks","text":"","boost":10},{"location":"getting-started/lifespan/hooks/#usage-example","title":"Usage example","text":"

Let's imagine that your application uses pydantic as your settings manager.

I highly recommend using pydantic for these purposes, because this dependency is already used at FastStream and you don't have to install an additional package

Also, let's imagine that you have several .env, .env.development, .env.test, .env.production files with your application settings, and you want to switch them at startup without any code changes.

By passing optional arguments with the command line to your code FastStream allows you to do this easily.

","boost":10},{"location":"getting-started/lifespan/hooks/#lifespan","title":"Lifespan","text":"

Let's write some code for our example

KafkaRabbitMQNATSRedis
from pydantic_settings import BaseSettings\n\nfrom faststream import ContextRepo, FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker()\napp = FastStream(broker)\n\n\nclass Settings(BaseSettings):\n    host: str = \"localhost:9092\"\n\n\n@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
from pydantic_settings import BaseSettings\n\nfrom faststream import ContextRepo, FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\n\nclass Settings(BaseSettings):\n    host: str = \"amqp://guest:guest@localhost:5672/\" \n\n\n@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
from pydantic_settings import BaseSettings\n\nfrom faststream import ContextRepo, FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n\nclass Settings(BaseSettings):\n    host: str = \"nats://localhost:4222\"\n\n\n@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
from pydantic_settings import BaseSettings\n\nfrom faststream import ContextRepo, FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\nclass Settings(BaseSettings):\n    host: str = \"redis://localhost:6379\"\n\n\n@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n

Now this application can be run using the following command to manage the environment:

faststream run serve:app --env .env.test\n
","boost":10},{"location":"getting-started/lifespan/hooks/#details","title":"Details","text":"

Now let's look into a little more detail

To begin with, we used a decorator

@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n

to declare a function that should run when our application starts

The next step is to declare the arguments that our function will receive

@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n

In this case, the env field will be passed to the setup function from the arguments with the command line

Tip

The default lifecycle functions are used with the decorator @apply_types, therefore, all context fields and dependencies are available in them

Then, we initialized the settings of our application using the file passed to us from the command line

@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n

And put these settings in a global context

KafkaRabbitMQNATSRedis
@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
Note

Now we can access our settings anywhere in the application right from the context

from faststream import Context, apply_types\n@apply_types\nasync def func(settings = Context()): ...\n

The last step we initialized our broker: now, when the application starts, it will be ready to receive messages

@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
","boost":10},{"location":"getting-started/lifespan/hooks/#another-example","title":"Another example","text":"

Now let's imagine that we have a machine learning model that needs to process messages from some broker.

Initialization of such models usually takes a long time. It would be wise to do this at the start of the application, and not when processing each message.

You can initialize your model somewhere at the top of your module/file. However, in this case, this code will be run even just in case of importing this module, for example, during testing. It is unlikely that you want to run your model on every test run...

Therefore, it is worth initializing the model in the @app.on_startup hook.

Also, we don't want the model to finish its work incorrectly when the application is stopped. To avoid this, we need the hook @app.on_shutdown

KafkaRabbitMQNATSRedis
from faststream import Context, ContextRepo, FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\nml_models = {}  # fake ML model\n\n\ndef fake_answer_to_everything_ml_model(x: float):\n    return x * 42\n\n\n@app.on_startup\nasync def setup_model(context: ContextRepo):\n    # Load the ML model\n    ml_models[\"answer_to_everything\"] = fake_answer_to_everything_ml_model\n    context.set_global(\"model\", ml_models)\n\n\n@app.on_shutdown\nasync def shutdown_model(model: dict = Context()):\n    # Clean up the ML models and release the resources\n    model.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n
from faststream import Context, ContextRepo, FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\nml_models = {}  # fake ML model\n\n\ndef fake_answer_to_everything_ml_model(x: float):\n    return x * 42\n\n\n@app.on_startup\nasync def setup_model(context: ContextRepo):\n    # Load the ML model\n    ml_models[\"answer_to_everything\"] = fake_answer_to_everything_ml_model\n    context.set_global(\"model\", ml_models)\n\n\n@app.on_shutdown\nasync def shutdown_model(model: dict = Context()):\n    # Clean up the ML models and release the resources\n    model.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n
from faststream import Context, ContextRepo, FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\nml_models = {}  # fake ML model\n\n\ndef fake_answer_to_everything_ml_model(x: float):\n    return x * 42\n\n\n@app.on_startup\nasync def setup_model(context: ContextRepo):\n    # Load the ML model\n    ml_models[\"answer_to_everything\"] = fake_answer_to_everything_ml_model\n    context.set_global(\"model\", ml_models)\n\n\n@app.on_shutdown\nasync def shutdown_model(model: dict = Context()):\n    # Clean up the ML models and release the resources\n    model.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n
from faststream import Context, ContextRepo, FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\nml_models = {}  # fake ML model\n\n\ndef fake_answer_to_everything_ml_model(x: float):\n    return x * 42\n\n\n@app.on_startup\nasync def setup_model(context: ContextRepo):\n    # Load the ML model\n    ml_models[\"answer_to_everything\"] = fake_answer_to_everything_ml_model\n    context.set_global(\"model\", ml_models)\n\n\n@app.on_shutdown\nasync def shutdown_model(model: dict = Context()):\n    # Clean up the ML models and release the resources\n    model.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n
","boost":10},{"location":"getting-started/lifespan/hooks/#multiple-hooks","title":"Multiple hooks","text":"

If you want to declare multiple lifecycle hooks, they will be used in the order they are registered:

from faststream import Context, ContextRepo, FastStream\n\napp = FastStream()\n\n\n@app.on_startup\nasync def setup(context: ContextRepo):\n    context.set_global(\"field\", 1)\n\n\n@app.on_startup\nasync def setup_later(field: int = Context()):\n    assert field == 1\n
","boost":10},{"location":"getting-started/lifespan/hooks/#some-more-details","title":"Some more details","text":"","boost":10},{"location":"getting-started/lifespan/hooks/#async-or-not-async","title":"Async or not async","text":"

In the asynchronous version of the application, both asynchronous and synchronous methods can be used as hooks. In the synchronous version, only synchronous methods are available.

","boost":10},{"location":"getting-started/lifespan/hooks/#command-line-arguments","title":"Command line arguments","text":"

Command line arguments are available in all @app.on_startup hooks. To use them in other parts of the application, put them in the ContextRepo.

","boost":10},{"location":"getting-started/lifespan/hooks/#broker-initialization","title":"Broker initialization","text":"

The @app.on_startup hooks are called BEFORE the broker is launched by the application. The @app.after_shutdown hooks are triggered AFTER stopping the broker.

If you want to perform some actions AFTER initializing the broker: send messages, initialize objects, etc., you should use the @app.after_startup hook.

","boost":10},{"location":"getting-started/lifespan/test/","title":"Events Testing","text":"

In the most cases you are testing your subsriber/publisher functions, but sometimes you need to trigger some lifespan hooks in your tests too.

For this reason, FastStream has a special TestApp patcher working as a regular async context manager.

KafkaRabbitMQNATSRedis
import pytest\n\nfrom faststream import FastStream, TestApp\nfrom faststream.kafka import KafkaBroker, TestKafkaBroker\n\napp = FastStream(KafkaBroker())\n\n\n@app.after_startup\nasync def handle():\n    print(\"Calls in tests too!\")\n\n\n@pytest.mark.asyncio\nasync def test_lifespan():\n    async with (\n        TestKafkaBroker(app.broker, connect_only=True),\n        TestApp(app),\n    ):\n        # test something\n        pass\n
import pytest\n\nfrom faststream import FastStream, TestApp\nfrom faststream.rabbit import RabbitBroker, TestRabbitBroker\n\napp = FastStream(RabbitBroker())\n\n\n@app.after_startup\nasync def handle():\n    print(\"Calls in tests too!\")\n\n\n@pytest.mark.asyncio\nasync def test_lifespan():\n    async with (\n        TestRabbitBroker(app.broker, connect_only=True),\n        TestApp(app),\n    ):\n        # test something\n        pass\n
import pytest\n\nfrom faststream import FastStream, TestApp\nfrom faststream.nats import NatsBroker, TestNatsBroker\n\napp = FastStream(NatsBroker())\n\n\n@app.after_startup\nasync def handle():\n    print(\"Calls in tests too!\")\n\n\n@pytest.mark.asyncio\nasync def test_lifespan():\n    async with (\n        TestNatsBroker(app.broker, connect_only=True),\n        TestApp(app),\n    ):\n        # test something\n        pass\n
import pytest\n\nfrom faststream import FastStream, TestApp\nfrom faststream.redis import RedisBroker, TestRedisBroker\n\napp = FastStream(RedisBroker())\n\n\n@app.after_startup\nasync def handle():\n    print(\"Calls in tests too!\")\n\n\n@pytest.mark.asyncio\nasync def test_lifespan():\n    async with (\n        TestRedisBroker(app.broker, connect_only=True),\n        TestApp(app),\n    ):\n        # test something\n        pass\n
","boost":10},{"location":"getting-started/lifespan/test/#using-with-testbroker","title":"Using with TestBroker","text":"

If you want to use In-Memory patched broker in your tests, it's advisable to patch the broker first (before applying the application patch).

Also, TestApp and TestBroker are calling broker.start() both. According to the original logic, broker should be started in the FastStream application, but TestBroker applied first breaks this behavior. This reason TestApp prevents TestBroker broker.start() call if it placed incide TestBroker context.

This behavior is ruled by connect_only TestBroker argument. By default it has None value, but TestApp can set it to True/False by inner logic. To prevent this \"magic\", just setup connect_only argument manually.

Warning

With connect_only=False, all FastStream hooks will be called after broker was started, what can breaks some @app.on_startup logic.

","boost":10},{"location":"getting-started/middlewares/","title":"Middlewares","text":"

Middlewares are a powerful mechanism that allows you to add additional logic to any stage of the message processing pipeline.

This way, you can greatly extend your FastStream application with features such as:

Middlewares have several methods to override. You can implement some or all of them and use middlewares at the broker, router, or subscriber level. Thus, middlewares are the most flexible FastStream feature.

","boost":10},{"location":"getting-started/middlewares/#message-receive-wrapper","title":"Message Receive Wrapper","text":"

Unfortunately, this powerful feature has a somewhat complex signature too.

Using middlewares, you can wrap the entire message processing pipeline. In this case, you need to specify on_receive and after_processed methods:

from faststream import BaseMiddleware\n\nclass MyMiddleware(BaseMiddleware):\n    async def on_receive(self):\n        print(f\"Received: {self.message}\")\n        return await super().on_receive()\n\n    async def after_processed(self, exc_type, exc_val, exec_tb):\n        return await super().after_processed(exc_type, exc_val, exec_tb)\n

These methods should be overwritten only in a broker-level middlewares.

Broker(middlewares=[MyMiddleware])\n

In other cases, on_receive will be called at every subscriber filter function call.

Tip

Please always call super() methods at the end of your function; this is important for correct error processing.

","boost":10},{"location":"getting-started/middlewares/#message-consuming-wrapper","title":"Message Consuming Wrapper","text":"

Also, using middlewares, you are able to wrap consumer function calls directly.

In this case, you need to specify on_receive and after_processed methods:

from typing import Optional\n\nfrom faststream import BaseMiddleware:\nfrom faststream.types import DecodedMessage\n\nclass MyMiddleware(BaseMiddleware):\n    async def on_consume(self, msg: DecodedMessage) -> DecodedMessage:\n        return await super().on_consume(msg)\n\n    async def after_consume(self, err: Optional[Exception]) -> None:\n        return await super().after_consume(err)\n

This way, you can patch the incoming message body right before passing it to your consumer subscriber.

Also, if you have multiple filters for one subscriber, these methods will be called at once when the filtering is completed successfully.

","boost":10},{"location":"getting-started/middlewares/#message-publishing-wrapper","title":"Message Publishing Wrapper","text":"

Finally, using middlewares, you are able to patch outgoing messages too. For example, you can compress/encode outgoing messages at the application level.

In this, case you need to specify on_publish and after_publish methods:

from typing import Optional\n\nfrom faststream import BaseMiddleware:\nfrom faststream.types import SendableMessage\n\nclass MyMiddleware(BaseMiddleware):\n    async def on_publish(self, msg: SendableMessage) -> SendableMessage:\n        return await super().on_publish(msg)\n\n    async def after_publish(self, err: Optional[Exception]) -> None:\n        return await super().after_publish(err)\n
","boost":10},{"location":"getting-started/publishing/","title":"Publishing Basics","text":"

FastStream is broker-agnostic and easy to use, even as a client in non-FastStream applications.

It offers several use cases for publishing messages:

All of these variants have their own advantages and limitations, so you can choose what you want based on your requirements. Please visit the following pages for details.

","boost":10},{"location":"getting-started/publishing/#serialization","title":"Serialization","text":"

FastStream allows you to publish any JSON-serializable messages (Python types, Pydantic models, etc.) or raw bytes.

It automatically sets up all required headers, especially the correlation_id, which is used to trace message processing pipelines across all services.

The content-type is a meaningfull header for FastStream services. It helps the framework serialize messages faster, selecting the right serializer based on the header. This header is automatically set by FastStream too, but you should set it up manually using other libraries to interact with FastStream applications.

Content-Type can be:

By the way, you can use application/json for all of your messages if they are not raw bytes. You can even omit using any header at all, but it makes serialization slightly slower.

","boost":10},{"location":"getting-started/publishing/#publishing","title":"Publishing","text":"

FastStream can also be used as a Broker client to send messages in other applications. It is quite straightforward and similar to aiohttp or requests.

You just need to connect your broker, and you are ready to send a message. Additionally, you can use Broker as an async context manager to establish a connection and disconnect when leaving the scope.

To publish a message, simply set up the message content and a routing key:

KafkaRabbitMQNATSRedis
async with KafkaBroker() as br:\n    await br.publish(\"message\", \"topic\")\n
async with RabbitBroker() as br:\n    await br.publish(\"message\", \"queue\")\n
async with NatsBroker() as br:\n    await br.publish(\"message\", \"subject\")\n
async with RedisBroker() as br:\n    await br.publish(\"message\", \"channel\")\n
","boost":10},{"location":"getting-started/publishing/broker/","title":"Broker Publishing","text":"

The easiest way to publish a message is to use a Broker, which allows you to use it as a publisher client in any applications.

In the FastStream project, this call is not represented in the AsyncAPI scheme. You can use it to send rarely-publishing messages, such as startup or shutdown events.

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle():\n    await broker.publish(\"Hi!\", topic=\"another-topic\")\n\n\n@broker.subscriber(\"another-topic\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", topic=\"test-topic\")\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle():\n    await broker.publish(\"Hi!\", queue=\"another-queue\")\n\n\n@broker.subscriber(\"another-queue\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", queue=\"test-queue\")\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle():\n    await broker.publish(\"Hi!\", subject=\"another-subject\")\n\n\n@broker.subscriber(\"another-subject\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", subject=\"test-subject\")\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle():\n    await broker.publish(\"Hi!\", channel=\"another-channel\")\n\n\n@broker.subscriber(\"another-channel\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", channel=\"test-channel\")\n
","boost":10},{"location":"getting-started/publishing/decorator/","title":"Publisher Decorator","text":"

The second easiest way to publish messages is by using the Publisher Decorator. This method has an AsyncAPI representation and is suitable for quickly creating applications. However, it doesn't provide all testing features.

It creates a structured DataPipeline unit with an input and output. The order of Subscriber and Publisher decorators doesn't matter, but @broker.publisher(...) can be used only with functions already decorated by a @broker.subscriber(...).

Note

It uses the handler function's return type annotation to cast the function's return value before sending, so be accurate with it.

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\n@broker.publisher(\"another-topic\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-topic\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", topic=\"test-topic\")\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\n@broker.publisher(\"another-queue\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-queue\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", queue=\"test-queue\")\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\n@broker.publisher(\"another-subject\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-subject\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", subject=\"test-subject\")\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\n@broker.publisher(\"another-channel\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-channel\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", channel=\"test-channel\")\n
","boost":10},{"location":"getting-started/publishing/decorator/#message-broadcasting","title":"Message Broadcasting","text":"

The decorator can be used multiple times with one function to broadcast the function's return:

@broker.subscriber(\"in\")\n@broker.publisher(\"first-out\")\n@broker.publisher(\"second-out\")\nasync def handle(msg) -> str:\n    return \"Response\"\n

This way you will send a copy of your return to the all output topics.

Note

Also, if this subscriber consumes a message with RPC mode, it sends a reply not only to the RPC channel but also to all publishers as well.

","boost":10},{"location":"getting-started/publishing/decorator/#details","title":"Details","text":"

Additionally, @broker.publisher(...) automatically sends a message with the same correlation_id as the incoming message. This way, you get the same correlation_id for the entire message pipeline process across all services, allowing you to collect a trace.

","boost":10},{"location":"getting-started/publishing/direct/","title":"Publisher Direct Usage","text":"

The Publisher Object provides a full-featured way to publish messages. It has an AsyncAPI representation and includes testability features.

This method creates a reusable Publisher object that can be used directly to publish a message:

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-topic\")\n\n@broker.subscriber(\"test-topic\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n\n\n@broker.subscriber(\"another-topic\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-queue\")\n\n@broker.subscriber(\"test-queue\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n\n\n@broker.subscriber(\"another-queue\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-subject\")\n\n@broker.subscriber(\"test-subject\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n\n\n@broker.subscriber(\"another-subject\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-channel\")\n\n@broker.subscriber(\"test-channel\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n\n\n@broker.subscriber(\"another-channel\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n

It is something in the middle between broker publish and object decorator. It has an AsyncAPI representation and testability features (like the object decorator), but allows you to send different messages to different outputs (like the broker publish).

@broker.subscriber(\"in\")\nasync def handle(msg) -> str:\n    await publisher1.publish(\"Response-1\")\n    await publisher2.publish(\"Response-2\")\n

Note

When using this method, FastStream doesn't reuse the incoming correlation_id to mark outgoing messages with it. You should set it manually if it is required.

","boost":10},{"location":"getting-started/publishing/object/","title":"Publisher Object","text":"

The Publisher Object provides a full-featured way to publish messages. It has an AsyncAPI representation and includes testability features. This method creates a reusable Publisher object.

Additionally, this object can be used as a decorator. The order of Subscriber and Publisher decorators doesn't matter, but @publisher can be used only with functions already decorated by a @broker.subscriber(...).

Note

It uses the handler function's return type annotation to cast the function's return value before sending, so be accurate with it.

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-topic\")\n\n@publisher\n@broker.subscriber(\"test-topic\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-topic\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-queue\")\n\n@publisher\n@broker.subscriber(\"test-queue\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-queue\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-subject\")\n\n@publisher\n@broker.subscriber(\"test-subject\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-subject\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-channel\")\n\n@publisher\n@broker.subscriber(\"test-channel\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-channel\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
","boost":10},{"location":"getting-started/publishing/object/#message-broadcasting","title":"Message Broadcasting","text":"

The decorator can be used multiple times with one function to broadcast the function's return:

@publisher1\n@publisher2\n@broker.subscriber(\"in\")\nasync def handle(msg) -> str:\n    return \"Response\"\n

This way, you will send a copy of your return to all output topics.

Note

Also, if this subscriber consumes a message with RPC mode, it sends a reply not only to the RPC channel but also to all publishers as well.

","boost":10},{"location":"getting-started/publishing/object/#details","title":"Details","text":"

Additionally, @publisher automatically sends a message with the same correlation_id as the incoming message. This way, you get the same correlation_id for the entire message pipeline process across all services, allowing you to collect a trace.

","boost":10},{"location":"getting-started/publishing/test/","title":"Publisher Testing","text":"

If you are working with a Publisher object (either as a decorator or directly), you have several testing features available:

","boost":10},{"location":"getting-started/publishing/test/#base-application","title":"Base Application","text":"

Let's take a look at a simple application example with a publisher as a decorator or as a direct call:

DecoratorDirect KafkaRabbitMQNATSRedis
publisher = broker.publisher(\"another-topic\")\n\n@publisher\n@broker.subscriber(\"test-topic\")\nasync def handle() -> str:\n    return \"Hi!\"\n
publisher = broker.publisher(\"another-queue\")\n\n@publisher\n@broker.subscriber(\"test-queue\")\nasync def handle() -> str:\n    return \"Hi!\"\n
publisher = broker.publisher(\"another-subject\")\n\n@publisher\n@broker.subscriber(\"test-subject\")\nasync def handle() -> str:\n    return \"Hi!\"\n
publisher = broker.publisher(\"another-channel\")\n\n@publisher\n@broker.subscriber(\"test-channel\")\nasync def handle() -> str:\n    return \"Hi!\"\n
KafkaRabbitMQNATSRedis
publisher = broker.publisher(\"another-topic\")\n\n@broker.subscriber(\"test-topic\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n
publisher = broker.publisher(\"another-queue\")\n\n@broker.subscriber(\"test-queue\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n
publisher = broker.publisher(\"another-subject\")\n\n@broker.subscriber(\"test-subject\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n
publisher = broker.publisher(\"another-channel\")\n\n@broker.subscriber(\"test-channel\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n
","boost":10},{"location":"getting-started/publishing/test/#testing","title":"Testing","text":"

To test it, you just need to patch your broker with a special TestBroker.

KafkaRabbitMQNATSRedis
import pytest\n\nfrom faststream.kafka import TestKafkaBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestKafkaBroker(broker) as br:\n        await br.publish(\"\", topic=\"test-topic\")\n
import pytest\n\nfrom faststream.rabbit import TestRabbitBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRabbitBroker(broker) as br:\n        await br.publish(\"\", queue=\"test-queue\")\n
import pytest\n\nfrom faststream.nats import TestNatsBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestNatsBroker(broker) as br:\n        await br.publish(\"\", subject=\"test-subject\")\n
import pytest\n\nfrom faststream.redis import TestRedisBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRedisBroker(broker) as br:\n        await br.publish(\"\", channel=\"test-channel\")\n

By default, it patches you broker to run In-Memory, so you can use it without any external broker. It should be extremely usefull in your CI or local development environment.

Also, it allows you to check the outgoing message body in the same way as with a subscriber.

publisher.mock.assert_called_once_with(\"Hi!\")\n

Note

The Publisher mock contains not just a publish method input value. It sets up a virtual consumer for an outgoing topic, consumes a message, and stores this consumed one.

Additionally, TestBroker can be used with a real external broker to make your tests end-to-end suitable. For more information, please visit the subscriber testing page.

","boost":10},{"location":"getting-started/routers/","title":"Broker Router","text":"

Sometimes you want to:

For these reasons, FastStream has a special Broker Router.

","boost":10},{"location":"getting-started/routers/#router-usage","title":"Router Usage","text":"

First, you need to import the Broker Router from the same module from where you imported the broker.

When creating a Broker Router, you can specify a prefix that will be automatically applied to all subscribers and publishers of this router.

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaRouter\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\nrouter = KafkaRouter(prefix=\"prefix_\")\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker, RabbitRouter\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\nrouter = RabbitRouter(prefix=\"prefix_\")\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker, NatsRouter\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\nrouter = NatsRouter(prefix=\"prefix_\")\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker, RedisRouter\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\nrouter = RedisRouter(prefix=\"prefix_\")\n

Now you can use the created router to register handlers and publishers as if it were a regular broker

KafkaRabbitMQNATSRedis
@router.subscriber(\"test-topic\")\n@router.publisher(\"another-topic\")\nasync def handle(name: str, user_id: int) -> str:\n    assert name == \"John\"\n    assert user_id == 1\n    return \"Hi!\"\n\n\n@router.subscriber(\"another-topic\")\nasync def handle_response(msg: str):\n    assert msg == \"Hi!\"\n
@router.subscriber(\"test-queue\")\n@router.publisher(\"another-queue\")\nasync def handle(name: str, user_id: int) -> str:\n    assert name == \"John\"\n    assert user_id == 1\n    return \"Hi!\"\n\n\n@router.subscriber(\"another-queue\")\nasync def handle_response(msg: str):\n    assert msg == \"Hi!\"\n
@router.subscriber(\"test-subject\")\n@router.publisher(\"another-subject\")\nasync def handle(name: str, user_id: int) -> str:\n    assert name == \"John\"\n    assert user_id == 1\n    return \"Hi!\"\n\n\n@router.subscriber(\"another-subject\")\nasync def handle_response(msg: str):\n    assert msg == \"Hi!\"\n
@router.subscriber(\"test-channel\")\n@router.publisher(\"another-channel\")\nasync def handle(name: str, user_id: int) -> str:\n    assert name == \"John\"\n    assert user_id == 1\n    return \"Hi!\"\n\n\n@router.subscriber(\"another-channel\")\nasync def handle_response(msg: str):\n    assert msg == \"Hi!\"\n

Then you can simply include all the handlers declared using the router in your broker

broker.include_router(router)\n

Please note that when publishing a message, you now need to specify the same prefix that you used when creating the router

KafkaRabbitMQNATSRedis
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    topic=\"prefix_test-topic\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    queue=\"prefix_test-queue\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    subject=\"prefix_test-subject\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    channel=\"prefix_test-channel\",\n)\n

Tip

Also, when creating a Broker Router, you can specify middleware, dependencies, parser and decoder to apply them to all subscribers declared via this router.

","boost":10},{"location":"getting-started/routers/#delay-handler-registration","title":"Delay Handler Registration","text":"

If you want to separate your application's core logic from FastStream's routing logic, you can write some core functions and use them as Broker Router handlers later:

KafkaRabbitMQNATSRedis
from faststream.kafka import KafkaRoute, KafkaRouter\n\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\nrouter = KafkaRouter(\n    handlers=(\n        KafkaRoute(handle, \"test-topic\"),\n    )\n)\n
from faststream.rabbit import RabbitRoute, RabbitRouter\n\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\nrouter = RabbitRouter(\n    handlers=(\n        RabbitRoute(handle, \"test-queue\"),\n    )\n)\n
from faststream.nats import NatsRoute, NatsRouter\n\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\nrouter = NatsRouter(\n    handlers=(\n        NatsRoute(handle, \"test-subject\"),\n    )\n)\n
from faststream.redis import RedisRouter, RedisRoute\n\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\nrouter = RedisRouter(\n    handlers=(\n        RedisRoute(handle, \"test-channel\"),\n    )\n)\n

Warning

Be careful, this way you won't be able to test your handlers with a mock object.

","boost":10},{"location":"getting-started/serialization/","title":"Custom Serialization","text":"

By default, FastStream uses the JSON format to send and receive messages. However, if you need to handle messages in other formats or with additional serialization steps, such as gzip, lz4, Avro, Protobuf or Msgpack, you can easily modify the serialization logic.

","boost":10},{"location":"getting-started/serialization/#serialization-steps","title":"Serialization Steps","text":"

Before the message reaches your subscriber, FastStream applies two functions to it sequentially: parse_message and decode_message. You can modify one or both stages depending on your needs.

","boost":10},{"location":"getting-started/serialization/#message-parsing","title":"Message Parsing","text":"

At this stage, FastStream serializes an incoming message from the broker's framework into a general format called - StreamMessage. During this stage, the message body remains in the form of raw bytes.

This stage is closely related to the features of the broker used, and in most cases, redefining it is not necessary.

The parser declared at the broker level will be applied to all subscribers. The parser declared at the subscriber level is applied only to that specific subscriber and overrides the `broker' parser if specified.

","boost":10},{"location":"getting-started/serialization/#message-decoding","title":"Message Decoding","text":"

At this stage, the body of the StreamMessage is transformed into a format suitable for processing within your subscriber function. This is the stage you may need to redefine more often.

","boost":10},{"location":"getting-started/serialization/decoder/","title":"Custom Decoder","text":"

At this stage, the body of a StreamMessage is transformed into the format that it will take when it enters your handler function. This stage is the one you will need to redefine more often.

","boost":10},{"location":"getting-started/serialization/decoder/#signature","title":"Signature","text":"

The original decoder function has a relatively simple signature (this is a simplified version):

KafkaRabbitMQNATSRedis
from faststream.types import DecodedMessage\nfrom faststream.kafka import KafkaMessage\n\ndef decoder(msg: KafkaMessage) -> DecodedMessage:\n    ...\n
from faststream.types import DecodedMessage\nfrom faststream.rabbit import RabbitMessage\n\ndef decoder(msg: RabbitMessage) -> DecodedMessage:\n    ...\n
from faststream.types import DecodedMessage\nfrom faststream.nats import NatsMessage\n\ndef decoder(msg: NatsMessage) -> DecodedMessage:\n    ...\n
from faststream.types import DecodedMessage\nfrom faststream.redis import RedisMessage\n\ndef decoder(msg: RedisMessage) -> DecodedMessage:\n    ...\n

Alternatively, you can reuse the original decoder function with the following signature:

KafkaRabbitMQNATSRedis
from types import Callable, Awaitable\nfrom faststream.types import DecodedMessage\nfrom faststream.kafka import KafkaMessage\n\nasync def decoder(\n    msg: KafkaMessage,\n    original_decoder: Callable[[KafkaMessage], Awaitable[DecodedMessage]],\n) -> DecodedMessage:\n    return await original_decoder(msg)\n
from types import Callable, Awaitable\nfrom faststream.types import DecodedMessage\nfrom faststream.rabbit import RabbitMessage\n\nasync def decoder(\n    msg: RabbitMessage,\n    original_decoder: Callable[[RabbitMessage], Awaitable[DecodedMessage]],\n) -> DecodedMessage:\n    return await original_decoder(msg)\n
from types import Callable, Awaitable\nfrom faststream.types import DecodedMessage\nfrom faststream.nats import NatsMessage\n\nasync def decoder(\n    msg: NatsMessage,\n    original_decoder: Callable[[NatsMessage], Awaitable[DecodedMessage]],\n) -> DecodedMessage:\n    return await original_decoder(msg)\n
from types import Callable, Awaitable\nfrom faststream.types import DecodedMessage\nfrom faststream.redis import RedisMessage\n\nasync def decoder(\n    msg: RedisMessage,\n    original_decoder: Callable[[RedisMessage], Awaitable[DecodedMessage]],\n) -> DecodedMessage:\n    return await original_decoder(msg)\n

Note

The original decoder is always an asynchronous function, so your custom decoder should also be asynchronous.

Afterward, you can set this custom decoder at the broker or subscriber level.

","boost":10},{"location":"getting-started/serialization/decoder/#example","title":"Example","text":"

You can find examples of Protobuf, Msgpack and Avro serialization in the next article.

","boost":10},{"location":"getting-started/serialization/examples/","title":"Serialization examples","text":"","boost":10},{"location":"getting-started/serialization/examples/#protobuf","title":"Protobuf","text":"

In this section, we will explore an example using Protobuf. However, this approach is also applicable to other serialization methods.

Protobuf

Protobuf is an alternative message serialization method commonly used in GRPC. Its main advantage is that it results in much smaller message sizes1 compared to JSON, but it requires a message schema (.proto files) on both the client and server sides.

To begin, install the necessary dependencies:

pip install grpcio-tools\n

Next, let's define the schema for our message:

message.proto
syntax = \"proto3\";\n\nmessage Person {\n    string name = 1;\n    float age = 2;\n}\n

Now, generate a Python class to work with messages in Protobuf format:

python -m grpc_tools.protoc --python_out=. --pyi_out=. -I . message.proto\n

This generates two files: message_pb2.py and message_pb2.pyi. We can use the generated class to serialize our messages:

from message_pb2 import Person\n\nfrom faststream import FastStream, Logger, NoCast\nfrom faststream.rabbit import RabbitBroker, RabbitMessage\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\n\nasync def decode_message(msg: RabbitMessage) -> Person:\n    decoded = Person()\n    decoded.ParseFromString(msg.body)\n    return decoded\n\n\n@broker.subscriber(\"test\", decoder=decode_message)\nasync def consume(body: NoCast[Person], logger: Logger):\n    logger.info(body)\n\n\n@app.after_startup\nasync def publish():\n    body = Person(name=\"John\", age=25).SerializeToString()\n    await broker.publish(body, \"test\")\n

Note that we used the NoCast annotation to exclude the message from the pydantic representation of our handler.

async def consume(body: NoCast[Person], logger: Logger):\n
","boost":10},{"location":"getting-started/serialization/examples/#msgpack","title":"Msgpack","text":"

Msgpack is another alternative binary data format. Its main advantage is that it results in smaller message sizes2 compared to JSON, although slightly larger than Protobuf. The key advantage is that it doesn't require a message schema, making it easy to use in most cases.

To get started, install the necessary dependencies:

pip install msgpack\n

Since there is no need for a schema, you can easily write a Msgpack decoder:

import msgpack\n\nfrom faststream import FastStream, Logger\nfrom faststream.rabbit import RabbitBroker, RabbitMessage\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\n\nasync def decode_message(msg: RabbitMessage):\n    return msgpack.loads(msg.body)\n\n\n@broker.subscriber(\"test\", decoder=decode_message)\nasync def consume(name: str, age: int, logger: Logger):\n    logger.info(f\"{name}: {age}\")\n\n\n@app.after_startup\nasync def publish():\n    body = msgpack.dumps({\"name\": \"John\", \"age\": 25}, use_bin_type=True)\n    await broker.publish(body, \"test\")\n

Using Msgpack is much simpler than using Protobuf schemas. Therefore, if you don't have strict message size limitations, you can use Msgpack serialization in most cases.

","boost":10},{"location":"getting-started/serialization/examples/#avro","title":"Avro","text":"

In this section, let's explore how to use Avro encoding and decoding to encode/decode our messages as part of FastStream.

Avro

Apache Avro uses JSON to define data types and protocols and serializes data in a compact binary format. Avro utilizes a schema to structure the data that is being encoded. Schemas are composed of primitive types (null, boolean, int, long, float, double, bytes, and string) and complex types (record, enum, array, map, union, and fixed).

To get started, install the necessary dependencies:

pip install fastavro\n

Next, let's define the schema for our message. You can either define it in the Python file itself as:

person_schema = {\n    \"type\": \"record\",\n    \"namespace\": \"Person\",\n    \"name\": \"Person\",\n    \"fields\": [\n        {\"doc\": \"Name\", \"type\": \"string\", \"name\": \"name\"},\n        {\"doc\": \"Age\", \"type\": \"int\", \"name\": \"age\"},\n    ],\n}\n

Or you can load the schema from an avsc file as:

person_schema = fastavro.schema.load_schema(\"person.avsc\")\n

The contents of the person.avsc file are:

person.avsc
{\n    \"type\": \"record\",\n    \"namespace\": \"Person\",\n    \"name\": \"Person\",\n    \"fields\": [\n        {\"doc\": \"Name\", \"type\": \"string\", \"name\": \"name\"},\n        {\"doc\": \"Age\", \"type\": \"int\", \"name\": \"age\"}\n    ]\n}\n

Finally, let's use Avro's schemaless_reader and schemaless_writer to decode and encode messages in the FastStream app.

import io\n\nimport fastavro\n\nfrom faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker, KafkaMessage\n\nbroker = KafkaBroker()\napp = FastStream(broker)\n\n\n# person_schema = ...\nschema = fastavro.schema.parse_schema(person_schema)\n\nasync def decode_message(msg: KafkaMessage):\n    bytes_reader = io.BytesIO(msg.body)\n    msg_dict = fastavro.schemaless_reader(bytes_reader, schema)\n    return msg_dict\n\n\n@broker.subscriber(\"test\", decoder=decode_message)\nasync def consume(name: str, age: int, logger: Logger):\n    logger.info(f\"{name}: {age}\")\n\n\n@app.after_startup\nasync def publish():\n    msg = {\"name\": \"John\", \"age\": 25}\n\n    bytes_writer = io.BytesIO()\n    fastavro.schemaless_writer(bytes_writer, schema, msg)\n    raw_bytes = bytes_writer.getvalue()\n\n    await broker.publish(raw_bytes, \"test\")\n
","boost":10},{"location":"getting-started/serialization/examples/#tips","title":"Tips","text":"","boost":10},{"location":"getting-started/serialization/examples/#data-compression","title":"Data Compression","text":"

If you are dealing with very large messages, consider compressing them as well. You can explore libraries such as lz4 or zstd for compression algorithms.

Compression can significantly reduce message size, especially if there are repeated blocks. However, in the case of small message bodies, data compression may increase the message size. Therefore, you should assess the compression impact based on your specific application requirements.

","boost":10},{"location":"getting-started/serialization/examples/#broker-level-serialization","title":"Broker-Level Serialization","text":"

You can still set a custom decoder at the Broker or Router level. However, if you want to automatically encode publishing messages as well, you should explore Middleware for serialization implimentation.

  1. For example, a message like { \"name\": \"John\", \"age\": 25 } in JSON takes 27 bytes, while in Protobuf, it takes only 11 bytes. With lists and more complex structures, the savings can be even more significant (up to 20x times).\u00a0\u21a9

  2. A message with Msgpack serialization, such as { \"name\": \"John\", \"age\": 25 }, takes 16 bytes.\u00a0\u21a9

","boost":10},{"location":"getting-started/serialization/parser/","title":"Custom Parser","text":"

At this stage, FastStream serializes an incoming message from the broker's framework into a general format called StreamMessage. During this stage, the message body remains in the form of raw bytes.

StreamMessage is a general representation of a message within FastStream. It contains all the information required for message processing within FastStreams. It is even used to represent message batches, so the primary reason to customize it is to redefine the metadata associated with FastStream messages.

For example, you can specify your own header with the message_id semantic. This allows you to inform FastStream about this custom header through parser customization.

","boost":10},{"location":"getting-started/serialization/parser/#signature","title":"Signature","text":"

To create a custom message parser, you should write a regular Python function (synchronous or asynchronous) with the following signature:

KafkaRabbitMQNATSRedis
from aiokafka import ConsumerRecord\nfrom faststream.kafka import KafkaMessage\n\ndef parser(msg: ConsumerRecord) -> KafkaMessage:\n    ...\n
from aio_pika import IncomingMessage\nfrom faststream.rabbit import RabbitMessage\n\ndef parser(msg: IncomingMessage) -> RabbitMessage:\n    ...\n
from nats.aio.msg import Msg\nfrom faststream.nats import NatsMessage\n\ndef parser(msg: Msg) -> NatsMessage:\n    ...\n
from faststream.redis import RedisMessage\nfrom faststream.redis.message import PubSubMessage\n\ndef parser(msg: PubSubMessage) -> RedisMessage:\n    ...\n

Alternatively, you can reuse the original parser function with the following signature:

KafkaRabbitMQNATSRedis
from types import Callable, Awaitable\nfrom aiokafka import ConsumerRecord\nfrom faststream.kafka import KafkaMessage\n\nasync def parser(\n    msg: ConsumerRecord,\n    original_parser: Callable[[ConsumerRecord], Awaitable[KafkaMessage]],\n) -> KafkaMessage:\n    return await original_parser(msg)\n
from types import Callable, Awaitable\nfrom aio_pika import IncomingMessage\nfrom faststream.rabbit import RabbitMessage\n\nasync def parser(\n    msg: IncomingMessage,\n    original_parser: Callable[[IncomingMessage], Awaitable[RabbitMessage]],\n) -> RabbitMessage:\n    return await original_parser(msg)\n
from types import Callable, Awaitable\nfrom nats.aio.msg import Msg\nfrom faststream.nats import NatsMessage\n\nasync def parser(\n    msg: Msg,\n    original_parser: Callable[[Msg], Awaitable[NatsMessage]],\n) -> NatsMessage:\n    return await original_parser(msg)\n
from types import Callable, Awaitable\nfrom faststream.redis import RedisMessage\nfrom faststream.redis.message import PubSubMessage\n\nasync def parser(\n    msg: PubSubMessage,\n    original_parser: Callable[[PubSubMessage], Awaitable[RedisMessage]],\n) -> RedisMessage:\n    return await original_parser(msg)\n

The argument naming doesn't matter; the parser will always be placed as the second argument.

Note

The original parser is always an asynchronous function, so your custom parser should also be asynchronous.

Afterward, you can set this custom parser at the broker or subscriber level.

","boost":10},{"location":"getting-started/serialization/parser/#example","title":"Example","text":"

As an example, let's redefine message_id to a custom header:

KafkaRabbitMQNATSRedis
from typing import Awaitable, Callable\n\nfrom aiokafka import ConsumerRecord\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaMessage\n\n\nasync def custom_parser(\n    msg: ConsumerRecord,\n    original_parser: Callable[[ConsumerRecord], Awaitable[KafkaMessage]],\n) -> KafkaMessage:\n    parsed_msg = await original_parser(msg)\n    parsed_msg.message_id = parsed_msg.headers[\"custom_message_id\"]\n    return parsed_msg\n\n\nbroker = KafkaBroker(parser=custom_parser)\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def handle():\n    ...\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", \"test\", headers={\"custom_message_id\": \"1\"})\n
from typing import Awaitable, Callable\n\nfrom aio_pika import IncomingMessage\n\nfrom faststream import FastStream\nfrom faststream.rabbit import RabbitBroker, RabbitMessage\n\n\nasync def custom_parser(\n    msg: IncomingMessage,\n    original_parser: Callable[[IncomingMessage], Awaitable[RabbitMessage]],\n) -> RabbitMessage:\n    parsed_msg = await original_parser(msg)\n    parsed_msg.message_id = parsed_msg.headers[\"custom_message_id\"]\n    return parsed_msg\n\n\nbroker = RabbitBroker(parser=custom_parser)\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def handle():\n    ...\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", \"test\", headers={\"custom_message_id\": \"1\"})\n
from typing import Awaitable, Callable\n\nfrom nats.aio.msg import Msg\n\nfrom faststream import FastStream\nfrom faststream.nats import NatsBroker, NatsMessage\n\n\nasync def custom_parser(\n    msg: Msg,\n    original_parser: Callable[[Msg], Awaitable[NatsMessage]],\n) -> NatsMessage:\n    parsed_msg = await original_parser(msg)\n    parsed_msg.message_id = parsed_msg.headers[\"custom_message_id\"]\n    return parsed_msg\n\n\nbroker = NatsBroker(parser=custom_parser)\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def handle():\n    ...\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", \"test\", headers={\"custom_message_id\": \"1\"})\n
from typing import Awaitable, Callable\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker, RedisMessage\nfrom faststream.redis.message import PubSubMessage\n\n\nasync def custom_parser(\n    msg: PubSubMessage,\n    original_parser: Callable[[PubSubMessage], Awaitable[RedisMessage]],\n) -> RedisMessage:\n    parsed_msg = await original_parser(msg)\n    parsed_msg.message_id = parsed_msg.headers[\"custom_message_id\"]\n    return parsed_msg\n\n\nbroker = RedisBroker(parser=custom_parser)\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def handle():\n    ...\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", \"test\", headers={\"custom_message_id\": \"1\"})\n
","boost":10},{"location":"getting-started/subscription/","title":"Subscription Basics","text":"

FastStream provides a Message Broker agnostic way to subscribe to event streams.

You need not even know about topics/queues/subjects or any broker inner objects you use. The basic syntax is the same for all brokers:

KafkaRabbitMQNATSRedis
from faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker()\n\n@broker.subscriber(\"test\")  # topic name\nasync def handle_msg(msg_body):\n    ...\n
from faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker()\n\n@broker.subscriber(\"test\")  # queue name\nasync def handle_msg(msg_body):\n    ...\n
from faststream.nats import NatsBroker\n\nbroker = NatsBroker()\n\n@broker.subscriber(\"test\")  # subject name\nasync def handle_msg(msg_body):\n    ...\n
from faststream.redis import RedisBroker\n\nbroker = RedisBroker()\n\n@broker.subscriber(\"test\")  # channel name\nasync def handle_msg(msg_body):\n    ...\n

Tip

If you want to use Message Broker specific features, please visit the corresponding broker documentation section. In the Tutorial section, the general features are described.

Also, synchronous functions are supported as well:

KafkaRabbitMQNATSRedis
from faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker()\n\n@broker.subscriber(\"test\")  # topic name\ndef handle_msg(msg_body):\n    ...\n
from faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker()\n\n@broker.subscriber(\"test\")  # queue name\ndef handle_msg(msg_body):\n    ...\n
from faststream.nats import NatsBroker\n\nbroker = NatsBroker()\n\n@broker.subscriber(\"test\")  # subject name\ndef handle_msg(msg_body):\n    ...\n
from faststream.redis import RedisBroker\n\nbroker = RedisBroker()\n\n@broker.subscriber(\"test\")  # channel name\ndef handle_msg(msg_body):\n    ...\n
","boost":10},{"location":"getting-started/subscription/#message-body-serialization","title":"Message Body Serialization","text":"

Generally, FastStream uses your function type annotation to serialize incoming message body with Pydantic. This is similar to how FastAPI works (if you are familiar with it).

@broker.subscriber(\"test\")\nasync def handle_str(\n    msg_body: str,\n):\n    ...\n

You can also access some extra features through the function arguments, such as Depends and Context if required.

However, you can easily disable Pydantic validation by creating a broker with the following option Broker(apply_types=False) (this also disables Context and Depends features).

This way FastStream still consumes json.loads result, but without pydantic validation and casting.

KafkaRabbitMQNATSRedis
from faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(apply_types=False)\n\n@broker.subscriber(\"test\")\nasync def handle_msg(msg_body: str):  # just an annotation, has no real effect\n    ...\n
from faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(apply_types=False)\n\n@broker.subscriber(\"test\")\nasync def handle_msg(msg_body: str):  # just an annotation, has no real effect\n    ...\n
from faststream.nats import NatsBroker\n\nbroker = NatsBroker(apply_types=False)\n\n@broker.subscriber(\"test\")\nasync def handle_msg(msg_body: str):  # just an annotation, has no real effect\n    ...\n
from faststream.redis import RedisBroker\n\nbroker = RedisBroker(apply_types=False)\n\n@broker.subscriber(\"test\")\nasync def handle_msg(msg_body: str):  # just an annotation, has no real effect\n    ...\n
","boost":10},{"location":"getting-started/subscription/#multiple-subscriptions","title":"Multiple Subscriptions","text":"

You can also subscribe to multiple event streams at the same time with one function. Just wrap it with multiple @broker.subscriber(...) decorators (they have no effect on each other).

@broker.subscriber(\"first_sub\")\n@broker.subscriber(\"second_sub\")\nasync def handler(msg):\n    ...\n
","boost":10},{"location":"getting-started/subscription/annotation/","title":"Annotation Serialization","text":"","boost":10},{"location":"getting-started/subscription/annotation/#basic-usage","title":"Basic usage","text":"

As you already know, FastStream serializes your incoming message body according to the function type annotations using Pydantic.

So, there are some valid usecases:

@broker.subscriber(\"test\")\nasync def handle(\n    msg: str,\n):\n    ...\n\n@broker.subscriber(\"test\")\nasync def handle(\n    msg: bytes,\n):\n    ...\n\n@broker.subscriber(\"test\")\nasync def handle(\n    msg: int,\n):\n    ...\n

As with other Python primitive types as well (float, bool, datetime, etc)

Note

If the incoming message cannot be serialized by the described schema, FastStream raises a pydantic.ValidationError with a correct log message.

Also, thanks to Pydantic (again), FastStream is able to serialize (and validate) more complex types like pydantic.HttpUrl, pydantic.PostitiveInt, etc.

","boost":10},{"location":"getting-started/subscription/annotation/#json-basic-serialization","title":"JSON Basic Serialization","text":"

But how can we serialize more complex message, like { \"name\": \"John\", \"user_id\": 1 } ?

For sure, we can serialize it as a simple dict

from typing import Dict, Any\n\n@broker.subscriber(\"test\")\nasync def handle(\n    msg: dict[str, Any],\n):\n    ...\n

But it doesn't looks like a correct message validation, does it?

For this reason, FastStream supports per-argument message serialization: you can declare multiple arguments with various types and your message will unpack to them:

KafkaRabbitMQNATSRedis
@broker.subscriber(\"test-topic\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
@broker.subscriber(\"test-queue\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
@broker.subscriber(\"test-subject\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
@broker.subscriber(\"test-channel\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
","boost":10},{"location":"getting-started/subscription/filtering/","title":"Application-level Filtering","text":"

FastStream also allows you to specify the message processing way using message headers, body type or something else. The filter feature enables you to consume various messages with different schemas within a single event stream.

Tip

Message must be consumed at ONCE (crossing filters are not allowed)

As an example, let's create a subscriber for both JSON and non-JSON messages:

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    \"test-topic\",\n    filter=lambda msg: msg.content_type == \"application/json\",\n)\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\n\n@broker.subscriber(\"test-topic\")\nasync def default_handler(msg: str):\n    assert msg == \"Hello, FastStream!\"\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    \"test-queue\",\n    filter=lambda msg: msg.content_type == \"application/json\",\n)\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\n\n@broker.subscriber(\"test-queue\")\nasync def default_handler(msg: str):\n    assert msg == \"Hello, FastStream!\"\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    \"test-subject\",\n    filter=lambda msg: msg.content_type == \"application/json\",\n)\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\n\n@broker.subscriber(\"test-subject\")\nasync def default_handler(msg: str):\n    assert msg == \"Hello, FastStream!\"\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    \"test-channel\",\n    filter=lambda msg: msg.content_type == \"application/json\",\n)\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\n\n@broker.subscriber(\"test-channel\")\nasync def default_handler(msg: str):\n    assert msg == \"Hello, FastStream!\"\n

Note

A subscriber without a filter is a default subscriber. It consumes messages that have not been consumed yet.

For now, the following message will be delivered to the handle function

KafkaRabbitMQNATSRedis
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    topic=\"test-topic\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    queue=\"test-queue\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    subject=\"test-subject\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    channel=\"test-channel\",\n)\n

And this one will be delivered to the default_handler

KafkaRabbitMQNATSRedis
await broker.publish(\n    \"Hello, FastStream!\",\n    topic=\"test-topic\",\n)\n
await broker.publish(\n    \"Hello, FastStream!\",\n    queue=\"test-queue\",\n)\n
await broker.publish(\n    \"Hello, FastStream!\",\n    subject=\"test-subject\",\n)\n
await broker.publish(\n    \"Hello, FastStream!\",\n    channel=\"test-channel\",\n)\n
","boost":10},{"location":"getting-started/subscription/pydantic/","title":"Pydantic Serialization","text":"","boost":10},{"location":"getting-started/subscription/pydantic/#pydanticfield","title":"pydantic.Field","text":"

Besides, FastStream uses your handlers' annotations to collect information about the application schema and generate AsyncAPI schema.

You can access this information with extra details using pydantic.Field (such as title, description and examples). Additionally, Fields usage allows you to add extra validations to your message schema.

Just use pydantic.Field as a function default argument:

KafkaRabbitMQNATSRedis
from pydantic import Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    ),\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    ),\n):\n    assert name == \"John\"\n    assert user_id == 1\n
from pydantic import Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    ),\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    ),\n):\n    assert name == \"John\"\n    assert user_id == 1\n
from pydantic import Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    ),\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    ),\n):\n    assert name == \"John\"\n    assert user_id == 1\n
from pydantic import Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    ),\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    ),\n):\n    assert name == \"John\"\n    assert user_id == 1\n

Tip

Also you can use typing.Annotated (python 3.9+) or typing_extensions.Annotated to declare your handler fields

name: Annotated[\n    str,\n    Field(..., examples=[\"John\"], description=\"Registered user name\")\n],\nuser_id: Annotated[\n    NonNegativeInt,\n    Field(..., examples=[1], description=\"Registered user id\"),\n]\n
","boost":10},{"location":"getting-started/subscription/pydantic/#pydanticbasemodel","title":"pydantic.BaseModel","text":"

To make your message schema reusable between different subscribers and publishers, you can decalre it as a pydantic.BaseModel and use it as a single message annotation:

KafkaRabbitMQNATSRedis
from pydantic import BaseModel, Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\nclass UserInfo(BaseModel):\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    )\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    )\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    user: UserInfo,\n):\n    assert user.name == \"John\"\n    assert user.user_id == 1\n
from pydantic import BaseModel, Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\nclass UserInfo(BaseModel):\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    )\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    )\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    user: UserInfo,\n):\n    assert user.name == \"John\"\n    assert user.user_id == 1\n
from pydantic import BaseModel, Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\nclass UserInfo(BaseModel):\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    )\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    )\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    user: UserInfo,\n):\n    assert user.name == \"John\"\n    assert user.user_id == 1\n
from pydantic import BaseModel, Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\nclass UserInfo(BaseModel):\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    )\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    )\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    user: UserInfo,\n):\n    assert user.name == \"John\"\n    assert user.user_id == 1\n
","boost":10},{"location":"getting-started/subscription/test/","title":"Subscriber Testing","text":"

Testability is a crucial part of any application, and FastStream provides you with the tools to test your code easily.

","boost":10},{"location":"getting-started/subscription/test/#original-application","title":"Original Application","text":"

Let's take a look at the original application to test

KafkaRabbitMQNATSRedis annotation_kafka.py
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
annotation_rabbit.py
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
annotation_nats.py
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
annotation_redis.py
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n

It consumes JSON messages like { \"name\": \"username\", \"user_id\": 1 }

You can test your consume function like a regular one, for sure:

@pytest.mark.asyncio\nasync def test_handler():\n    await handle(\"John\", 1)\n

But if you want to test your function closer to your real runtime, you should use the special FastStream test client.

","boost":10},{"location":"getting-started/subscription/test/#in-memory-testing","title":"In-Memory Testing","text":"

Deploying a whole service with a Message Broker is a bit too much just for testing purposes, especially in your CI environment. Not to mention the possible loss of messages due to network failures when working with real brokers.

For this reason, FastStream has a special TestClient to make your broker work in InMemory mode.

Just use it like a regular async context manager - all published messages will be routed in-memory (without any external dependencies) and consumed by the correct handler.

KafkaRabbitMQNATSRedis
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.kafka import TestKafkaBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestKafkaBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, topic=\"test-topic\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.rabbit import TestRabbitBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRabbitBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, queue=\"test-queue\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.nats import TestNatsBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestNatsBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, subject=\"test-subject\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.redis import TestRedisBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRedisBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, channel=\"test-channel\")\n
","boost":10},{"location":"getting-started/subscription/test/#catching-exceptions","title":"Catching Exceptions","text":"

This way you can catch any exceptions that occur inside your handler:

KafkaRabbitMQNATSRedis
@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestKafkaBroker(broker) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", topic=\"test-topic\")\n
@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestRabbitBroker(broker) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", queue=\"test-queue\")\n
@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestNatsBroker(broker) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", subject=\"test-subject\")\n
@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestRedisBroker(broker) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", channel=\"test-channel\")\n
","boost":10},{"location":"getting-started/subscription/test/#validates-input","title":"Validates Input","text":"

Also, your handler has a mock object to validate your input or call counts.

KafkaRabbitMQNATSRedis
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestKafkaBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, topic=\"test-topic\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRabbitBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, queue=\"test-queue\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestNatsBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, subject=\"test-subject\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRedisBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, channel=\"test-channel\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n

Note

The Handler mock has a not-serialized JSON message body. This way you can validate the incoming message view, not python arguments.

Thus our example checks not mock.assert_called_with(name=\"John\", user_id=1), but mock.assert_called_with({ \"name\": \"John\", \"user_id\": 1 }).

You should be careful with this feature: all mock objects will be cleared when the context manager exits.

KafkaRabbitMQNATSRedis
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestKafkaBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, topic=\"test-topic\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRabbitBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, queue=\"test-queue\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestNatsBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, subject=\"test-subject\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRedisBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, channel=\"test-channel\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n
","boost":10},{"location":"getting-started/subscription/test/#real-broker-testing","title":"Real Broker Testing","text":"

If you want to test your application in a real environment, you shouldn't have to rewrite all your tests: just pass with_real optional parameter to your TestClient context manager. This way, TestClient supports all the testing features but uses an unpatched broker to send and consume messages.

KafkaRabbitMQNATSRedis
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.kafka import TestKafkaBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestKafkaBroker(broker, with_real=True) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, topic=\"test-topic\")\n        await handle.wait_call(timeout=3)\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n\n@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestKafkaBroker(broker, with_real=True) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", topic=\"test-topic\")\n            await handle.wait_call(timeout=3)\n\n        handle.mock.assert_called_once_with(\"wrong message\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.rabbit import TestRabbitBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRabbitBroker(broker, with_real=True) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, queue=\"test-queue\")\n        await handle.wait_call(timeout=3)\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n\n@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestRabbitBroker(broker, with_real=True) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", queue=\"test-queue\")\n            await handle.wait_call(timeout=3)\n\n        handle.mock.assert_called_once_with(\"wrong message\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.nats import TestNatsBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestNatsBroker(broker, with_real=True) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, subject=\"test-subject\")\n        await handle.wait_call(timeout=3)\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n\n@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestNatsBroker(broker, with_real=True) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", subject=\"test-subject\")\n            await handle.wait_call(timeout=3)\n\n        handle.mock.assert_called_once_with(\"wrong message\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.redis import TestRedisBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRedisBroker(broker, with_real=True) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, channel=\"test-channel\")\n        await handle.wait_call(timeout=3)\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n\n@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestRedisBroker(broker, with_real=True) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", channel=\"test-channel\")\n            await handle.wait_call(timeout=3)\n\n        handle.mock.assert_called_once_with(\"wrong message\")\n

Tip

When you're using a patched broker to test your consumers, the publish method is called synchronously with a consumer one, so you need not wait until your message is consumed. But in the real broker's case, it doesn't.

For this reason, you have to wait for message consumption manually with the special handler.wait_call(timeout) method. Also, inner handler exceptions will be raised in this function, not broker.publish(...).

","boost":10},{"location":"getting-started/subscription/test/#a-little-tip","title":"A Little Tip","text":"

It can be very helpful to set the with_real flag using an environment variable. This way, you will be able to choose the testing mode right from the command line:

WITH_REAL=True/False pytest ...\n

To learn more about managing your application configiruation visit this page.

","boost":10},{"location":"getting-started/template/","title":"Using Cookiecutter FastStream Template","text":"

Cookiecutter FastStream is a versatile repository that provides a solid foundation for your Python projects. It comes with a basic application, testing infrastructure, linting scripts, and various development tools to kickstart your development process. Whether you're building a new application from scratch or want to enhance an existing one, this template will save you time and help you maintain high code quality.

","boost":5},{"location":"getting-started/template/#features","title":"Features","text":"","boost":5},{"location":"getting-started/template/#getting-started","title":"Getting Started","text":"

To set up your development environment, follow these steps:

  1. Install the cookiecutter package using the following command:

    pip install cookiecutter\n

  2. Run the provided cookiecutter command and fill out the relevant details to generate a new FastStream project:

    cookiecutter https://github.com/airtai/cookiecutter-faststream.git\n
    The following screenshot illustrates the process of creating a new FastStream app with Kafka using the above command:

  3. Change the working directory to the newly created directory:

    cd <directory-name>\n

    NOTE: Replace <directory-name> with the name of your directory.

  4. Install all development requirements using pip:

    pip install -e \".[dev]\"\n

  5. Create a new repository for our FastStream app on GitHub.

  6. Add all the files, commit and push using the following commands:

    git init\ngit add .\ngit commit -m \"first commit\"\ngit branch -M main\ngit remote add origin git@github.com:<username>/<repo-name>.git\ngit push -u origin main\n

    NOTE: Replace <username> with your GitHub username and <repo-name> with the name of your repository in the above commands.

","boost":5},{"location":"getting-started/template/#development","title":"Development","text":"

The application code is located in the app/ directory. You can add new features or fix bugs in this directory. However, remember that code changes must be accompanied by corresponding updates to the tests located in the tests/ directory.

","boost":5},{"location":"getting-started/template/#running-tests","title":"Running Tests","text":"

Once you have updated tests, you can execute the tests using pytest:

pytest\n
","boost":5},{"location":"getting-started/template/#running-faststream-application-locally","title":"Running FastStream Application Locally","text":"

To run the FastStream application locally, follow these steps:

  1. Start the Kafka Docker container locally using the provided script:

    ./scripts/start_kafka_broker_locally.sh\n

  2. Start the FastStream application with the following command:

    faststream run <directory-name>.application:app --workers 1\n

    NOTE: Replace <directory-name> with the directory that is automatically generated from the project slug name and contains the app.py file.

  3. You can now send messages to the Kafka topic and can test the application. Optionally, if you want to view messages in a topic, you can subscribe to it using the provided script:

    ./scripts/subscribe_to_kafka_broker_locally.sh <topic_name>\n

  4. To stop the FastStream application, press Ctrl+C.

  5. Finally, stop the Kafka Docker container by running the script:

    ./scripts/stop_kafka_broker_locally.sh\n

","boost":5},{"location":"getting-started/template/#building-and-testing-docker-image-locally","title":"Building and Testing Docker Image Locally","text":"

If you'd like to build and test the Docker image locally, follow these steps:

  1. Run the provided script to build the Docker image locally. Use the following command:

    ./scripts/build_docker.sh <username> <repo-name>\n
    This script will build the Docker image locally with the same name as the one built in CI.

  2. Before starting the Docker container, ensure that a Kafka Docker container is running locally. You can start it using the provided script:

    ./scripts/start_kafka_broker_locally.sh\n

  3. Once Kafka is up and running, you can start the local Docker container using the following command:

    docker run --rm --name faststream-app --net=host ghcr.io/<username>/<repo-name>:latest\n
    --rm: This flag removes the container once it stops running, ensuring that it doesn't clutter your system with unused containers. --name faststream-app: Assigns a name to the running container, in this case, \"faststream-app\". --net=host: This flag allows the Docker container to share the host's network namespace.

  4. To stop the local Docker container, simply press Ctrl+C in your terminal.

  5. Finally, stop the Kafka Docker container by running the provided script:

    ./scripts/stop_kafka_broker_locally.sh\n

NOTE: Replace <username> with your GitHub username and <repo-name> with the name of your repository in the above commands.

","boost":5},{"location":"getting-started/template/#code-linting","title":"Code Linting","text":"

After making changes to the code, it's essential to ensure it adheres to coding standards. We provide a script to help you with code formatting and linting. Run the following script to automatically fix linting issues:

./scripts/lint.sh\n
","boost":5},{"location":"getting-started/template/#static-analysis","title":"Static Analysis","text":"

Static analysis tools mypy and bandit can help identify potential issues in your code. To run static analysis, use the following script:

./scripts/static-analysis.sh\n

If there are any static analysis errors, resolve them in your code and rerun the script until it passes successfully.

","boost":5},{"location":"getting-started/template/#viewing-asyncapi-documentation","title":"Viewing AsyncAPI Documentation","text":"

FastStream framework supports AsyncAPI documentation. To ensure that your changes are reflected in the AsyncAPI documentation, follow these steps:

  1. Run the following command to view the AsyncAPI documentation:

    faststream docs serve <directory-name>.application:app\n
    This command builds the AsyncAPI specification file, generates AsyncAPI documentation based on the specification, and serves it at localhost:8000.

    NOTE: Replace <directory-name> with the directory that is automatically generated from the project slug name and contains the app.py file.

  2. Open your web browser and navigate to http://localhost:8000 to view the AsyncAPI documentation reflecting your changes.

  3. To stop the AsyncAPI documentation server, press Ctrl+C.

","boost":5},{"location":"getting-started/template/#contributing","title":"Contributing","text":"

Once you have successfully completed all the above steps, you are ready to contribute your changes:

  1. Add and commit your changes:

    git add .\ngit commit -m \"Your commit message\"\n

  2. Push your changes to GitHub:

    git push origin your-branch\n

  3. Create a merge request on GitHub.

","boost":5},{"location":"getting-started/template/#continuous-integration-ci","title":"Continuous Integration (CI)","text":"

This repository is equipped with GitHub Actions that automate static analysis and pytest in the CI pipeline. Even if you forget to perform any of the required steps, CI will catch any issues before merging your changes.

This repository has three workflows, each triggered when code is pushed:

  1. Tests Workflow: This workflow is named \"Tests\" and consists of two jobs. The first job runs static analysis tools mypy and bandit to identify potential issues in the codebase. The second job runs tests using pytest to ensure the functionality of the application. Both jobs run simultaneously to expedite the CI process.

  2. Build Docker Image Workflow: This workflow is named \"Build Docker Image\" and has one job. In this job, a Docker image is built based on the provided Dockerfile. The built image is then pushed to the GitHub Container Registry, making it available for deployment or other purposes.

  3. Deploy FastStream AsyncAPI Docs Workflow: The final workflow is named \"Deploy FastStream AsyncAPI Docs\" and also consists of a single job. In this job, the AsyncAPI documentation is built from the specification, and the resulting documentation is deployed to GitHub Pages. This allows for easy access and sharing of the AsyncAPI documentation with the project's stakeholders.

","boost":5},{"location":"getting-started/template/#viewing-asyncapi-documentation-hosted-at-github-pages","title":"Viewing AsyncAPI Documentation Hosted at GitHub Pages","text":"

After the Deploy FastStream AsyncAPI Docs workflow in CI has been successfully completed, the AsyncAPI documentation is automatically deployed to GitHub Pages. This provides a convenient way to access and share the documentation with project stakeholders.

To view the deployed AsyncAPI documentation, open your web browser and navigate to the following URL:

https://<username>.github.io/<repo-name>/\n

NOTE: Replace <username> with your GitHub username and <repo-name> with the name of your repository.

You will be directed to the GitHub Pages site where your AsyncAPI documentation is hosted. This hosted documentation allows you to easily share your AsyncAPI specifications with others and provides a centralized location for reviewing the AsyncAPI documentation.

","boost":5},{"location":"getting-started/template/#deploying-docker-container","title":"Deploying Docker Container","text":"

Once the Build Docker Image workflow in CI has successfully completed, the built Docker image is pushed to the GitHub Container Registry. You can then deploy this image on your server by following these steps:

  1. Pull the Docker image from the GitHub Container Registry to your server using the following command:

    docker pull ghcr.io/<username>/<repo-name>:latest\n

    NOTE: Replace <username> with your GitHub username and <repo-name> with the name of your repository.

  2. After successfully pulling the image, start the Docker container using the following command:

    docker run --rm --name faststream-app --env-file /path/to/env-file ghcr.io/<username>/<repo-name>:latest\n
    --rm: This flag removes the container once it stops running, ensuring that it doesn't clutter your system with unused containers. --name faststream-app: Assigns a name to the running container, in this case, \"faststream-app\". --env-file /path/to/env-file: Specifies the path to an environment file (commonly a .env file) that contains environment variables required by your FastStream application. Storing secrets and configuration in an environment file is a secure and best practice for handling sensitive information such as Kafka host, port, and authentication details.

By following these steps, you can easily deploy your FastStream application as a Docker container on your server. Remember to customize the env-file and other environment variables as needed to suit your specific application requirements.

","boost":5},{"location":"kafka/","title":"Kafka Routing","text":"","boost":10},{"location":"kafka/#kafka-overview","title":"Kafka Overview","text":"","boost":10},{"location":"kafka/#what-is-kafka","title":"What is Kafka?","text":"

Kafka is an open-source distributed streaming platform developed by the Apache Software Foundation. It is designed to handle high-throughput, fault-tolerant, real-time data streaming. Kafka is widely used for building real-time data pipelines and streaming applications.

","boost":10},{"location":"kafka/#key-kafka-concepts","title":"Key Kafka Concepts","text":"","boost":10},{"location":"kafka/#1-publish-subscribe-model","title":"1. Publish-Subscribe Model","text":"

Kafka is built around the publish-subscribe messaging model. In this model, data is published to topics, and multiple consumers can subscribe to these topics to receive the data. This decouples the producers of data from the consumers, allowing for flexibility and scalability.

","boost":10},{"location":"kafka/#2-topics","title":"2. Topics","text":"

A topic in Kafka is a logical channel or category to which messages are published by producers and from which messages are consumed by consumers. Topics are used to organize and categorize data streams. Each topic can have multiple partitions, which enable Kafka to distribute data and provide parallelism for both producers and consumers.

","boost":10},{"location":"kafka/#kafka-topics","title":"Kafka Topics","text":"","boost":10},{"location":"kafka/#understanding-kafka-topics","title":"Understanding Kafka Topics","text":"

Topics are fundamental to Kafka and serve as the central point of data distribution. Here are some key points about topics:

","boost":10},{"location":"kafka/#faststream-kafkabroker","title":"FastStream KafkaBroker","text":"

The FastStream KafkaBroker is a key component of the FastStream framework that enables seamless integration with Apache Kafka. With the KafkaBroker, developers can easily connect to Kafka brokers, produce messages to Kafka topics, and consume messages from Kafka topics within their FastStream applications.

","boost":10},{"location":"kafka/#establishing-a-connection","title":"Establishing a Connection","text":"

To connect to Kafka using the FastStream KafkaBroker module, follow these steps:

  1. Initialize the KafkaBroker instance: Start by initializing a KafkaBroker instance with the necessary configuration, including Kafka broker address.

  2. Create your processing logic: Write a function that will consume the incoming messages in the defined format and produce a response to the defined topic

  3. Decorate your processing function: To connect your processing function to the desired Kafka topics you need to decorate it with @broker.subscriber(...) and @broker.publisher(...) decorators. Now, after you start your application, your processing function will be called whenever a new message in the subscribed topic is available and produce the function return value to the topic defined in the publisher decorator.

Here's a simplified code example demonstrating how to establish a connection to Kafka using FastStream's KafkaBroker module:

from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-topic\")\n@broker.publisher(\"out-topic\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n

This minimal example illustrates how FastStream simplifies the process of connecting to Kafka and performing basic message processing from the in_topic to the out-topic. Depending on your specific use case and requirements, you can further customize your Kafka integration with FastStream to build robust and efficient streaming applications.

For more advanced configuration options and detailed usage instructions, please refer to the FastStream Kafka documentation and the offical Kafka documentation.

","boost":10},{"location":"kafka/ack/","title":"Consuming Acknowledgements","text":"

As you may know, Kafka consumer should commit a topic offset when consuming a message.

The default behaviour, also implemented as such in the FastStream, automatically commits (acks) topic offset on message consumption. This is the at most once consuming strategy.

However, if you wish to use at least once strategy, you should commit offset AFTER the message is processed correctly. To accomplish that, set a consumer group and disable auto_commit option like this:

@broker.subscriber(\n    \"test\", group_id=\"group\", auto_commit=False\n)\nasync def base_handler(body: str):\n    ...\n

This way, upon successful return of the processing function, the message processed will be acknowledged. In the case of an exception being raised, the message will not be acknowledged.

However, there are situations where you might want to use a different acknowledgement logic.

","boost":10},{"location":"kafka/ack/#manual-acknowledgement","title":"Manual Acknowledgement","text":"

If you want to acknowledge a message manually, you can get direct access to the message object via the Context and acknowledge the message by calling the ack method:

from faststream.kafka.annotations import KafkaMessage\n\n\n@broker.subscriber(\n    \"test\", group_id=\"group\", auto_commit=False\n)\nasync def base_handler(body: str, msg: KafkaMessage):\n    await msg.ack()\n    # or\n    await msg.nack()\n

Tip

You can use the nack method to prevent offset commit and the message can be consumed by another consumer within the same group.

FastStream will see that the message was already acknowledged and will do nothing at the end of the process.

","boost":10},{"location":"kafka/ack/#interrupt-process","title":"Interrupt Process","text":"

If you wish to interrupt the processing of a message at any call stack level and acknowledge the message, you can achieve that by raising the faststream.exceptions.AckMessage.

from faststream import FastStream\nfrom faststream.exceptions import AckMessage\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    \"test-topic\", group_id=\"test-group\", auto_commit=False\n)\nasync def handle(body):\n    smth_processing(body)\n\n\ndef smth_processing(body):\n    if True:\n        raise AckMessage()\n\n\n@app.after_startup\nasync def test_publishing():\n    await broker.publish(\"Hello!\", \"test-topic\")\n

This way, FastStream interrupts the current message processing and acknowledges it immediately. Similarly, you can raise NackMessage as well to prevent the message from being committed.

Tip

If you want to disable FastStream Acknowledgement logic at all, you can use @broker.subscriber(..., no_ack=True) option. This way you should always process a message (ack/nack/terminate/etc) by yourself.

","boost":10},{"location":"kafka/message/","title":"Access to Message Information","text":"

As you may know, FastStream serializes a message body and provides you access to it through function arguments. However, there are times when you need to access additional message attributes such as offsets, headers, or other metadata.

","boost":10},{"location":"kafka/message/#message-access","title":"Message Access","text":"

You can easily access this information by referring to the message object in the Context

This object serves as a unified FastStream wrapper around the native broker library message (for example, aiokafka.ConsumerRecord in the case of Kafka). It contains most of the required information, including:

For example, if you would like to access the headers of an incoming message, you would do so like this:

from faststream.kafka import KafkaMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    msg: KafkaMessage,\n):\n    print(msg.headers)\n
","boost":10},{"location":"kafka/message/#message-fields-access","title":"Message Fields Access","text":"

In most cases, you don't need all message fields; you need to know just a part of them. You can use Context Fields access feature for this.

For example, you can get access to the headers like this:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    headers: str = Context(\"message.headers\"),\n):\n    print(headers)\n
","boost":10},{"location":"kafka/message/#headers-access","title":"Headers Access","text":"

Sure, you can get access to a raw message and get the headers dict itself, but more often you just need a single header field. So, you can easily access it using the Context:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Context(\"message.headers.user\"),\n):\n    ...\n

Using the special Header class is more convenient, as it also validates the header value using Pydantic. It works the same way as Context, but it is just a shorcut to Context with a default setup. So, you already know how to use it:

from faststream import Header\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Header(),\n):\n    ...\n
","boost":10},{"location":"kafka/security/","title":"FastStream Kafka Security","text":"

This chapter discusses the security options available in FastStream and how to use them.

","boost":10},{"location":"kafka/security/#security-objects","title":"Security Objects","text":"

FastStream allows you to enhance the security of applications by using security objects when creating brokers. These security objects encapsulate security-related configurations and mechanisms. Security objects supported in FastStream are (More are planned in the future such as SASL OAuth):

","boost":10},{"location":"kafka/security/#1-basesecurity-object","title":"1. BaseSecurity Object","text":"

Purpose: The BaseSecurity object wraps ssl.SSLContext object and is used to enable SSL/TLS encryption for secure communication between FastStream services and external components such as message brokers.

Usage:

import ssl\n\nfrom faststream.kafka import KafkaBroker\nfrom faststream.security import BaseSecurity\n\nssl_context = ssl.create_default_context()\nsecurity = BaseSecurity(ssl_context=ssl_context)\n\nbroker = KafkaBroker(\"localhost:9092\", security=security)\n
","boost":10},{"location":"kafka/security/#2-saslplaintext-object-with-ssltls","title":"2. SASLPlaintext Object with SSL/TLS","text":"

Purpose: The SASLPlaintext object is used for authentication in SASL (Simple Authentication and Security Layer) plaintext mode. It allows you to provide a username and password for authentication.

Usage:

import ssl\n\nfrom faststream.kafka import KafkaBroker\nfrom faststream.security import SASLPlaintext\n\nssl_context = ssl.create_default_context()\nsecurity = SASLPlaintext(\n    ssl_context=ssl_context,\n    username=\"admin\",\n    password=\"password\", \n)\n\nbroker = KafkaBroker(\"localhost:9092\", security=security)\n

Using any SASL authentication without SSL:

The following example will log a RuntimeWarning:

SASLPlaintext(username=\"admin\", password=\"password\")\n

If the user does not want to use SSL encryption without the waringning getting logged, they must explicitly set the use_ssl parameter to False when creating a SASL object.

SASLPlaintext(username=\"admin\", password=\"password\", use_ssl=False) \n
","boost":10},{"location":"kafka/security/#3-saslscram256512-object-with-ssltls","title":"3. SASLScram256/512 Object with SSL/TLS","text":"

Purpose: The SASLScram256 and SASLScram512 objects are used for authentication using the Salted Challenge Response Authentication Mechanism (SCRAM).

Usage:

SCRAM256SCRAM512
import ssl\n\nfrom faststream.kafka import KafkaBroker\nfrom faststream.security import SASLScram256\n\nssl_context = ssl.create_default_context()\nsecurity = SASLScram256(\n    ssl_context=ssl_context,\n    username=\"admin\",\n    password=\"password\", \n)\n\nbroker = KafkaBroker(\"localhost:9092\", security=security)\n
import ssl\n\nfrom faststream.kafka import KafkaBroker\nfrom faststream.security import SASLScram512\n\nssl_context = ssl.create_default_context()\nsecurity = SASLScram512(\n    ssl_context=ssl_context,\n    username=\"admin\",\n    password=\"password\", \n)\n\nbroker = KafkaBroker(\"localhost:9092\", security=security)\n
","boost":10},{"location":"kafka/Publisher/","title":"Publishing","text":"

The FastStream KafkaBroker supports all regular publishing use cases, and you can use them without any changes.

However, if you wish to further customize the publishing logic, you should take a closer look at specific KafkaBroker parameters.

","boost":10},{"location":"kafka/Publisher/#basic-kafka-publishing","title":"Basic Kafka Publishing","text":"

The KafkaBroker uses the unified publish method (from a producer object) to send messages.

In this case, you can use Python primitives and pydantic.BaseModel to define the content of the message you want to publish to the Kafka broker.

You can specify the topic to send by its name.

  1. Create your KafkaBroker instance

    broker = KafkaBroker(\"localhost:9092\")\n
  2. Publish a message using the publish method

    msg = Data(data=0.5)\n\nawait broker.publish(\n    model_to_json(msg),\n    \"input_data\",\n    headers={\"content-type\": \"application/json\"},\n)\n

This is the most basic way of using the KafkaBroker to publish a message.

","boost":10},{"location":"kafka/Publisher/#creating-a-publisher-object","title":"Creating a publisher object","text":"

The simplest way to use a KafkaBroker for publishing has a significant limitation: your publishers won't be documented in the AsyncAPI documentation. This might be acceptable for sending occasional one-off messages. However, if you're building a comprehensive service, it's recommended to create publisher objects. These objects can then be parsed and documented in your service's AsyncAPI documentation. Let's go ahead and create those publisher objects!

  1. Create your KafkaBroker instance

    broker = KafkaBroker(\"localhost:9092\")\n
  2. Create a publisher instance

    prepared_publisher = broker.publisher(\"input_data\")\n
  3. Publish a message using the publish method of the prepared publisher

    msg = Data(data=0.5)\n\nawait prepared_publisher.publish(\n    model_to_json(msg),\n    headers={\"content-type\": \"application/json\"},\n)\n

Now, when you wrap your broker into a FastStream object, the publisher will be exported to the AsyncAPI documentation.

","boost":10},{"location":"kafka/Publisher/#decorating-your-publishing-functions","title":"Decorating your publishing functions","text":"

To publish messages effectively in the Kafka context, consider utilizing the Publisher Decorator. This approach offers an AsyncAPI representation and is ideal for rapidly developing applications.

The Publisher Decorator creates a structured DataPipeline unit with both input and output components. The sequence in which you apply Subscriber and Publisher decorators does not affect their functionality. However, note that these decorators can only be applied to functions decorated by a Subscriber as well.

This method relies on the return type annotation of the handler function to properly interpret the function's return value before sending it. Hence, it's important to ensure accuracy in defining the return type.

Let's start by examining the entire application that utilizes the Publisher Decorator and then proceed to walk through it step by step.

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\nto_output_data = broker.publisher(\"output_data\")\n\n\n@to_output_data\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
  1. Initialize the KafkaBroker instance: Start by initializing a KafkaBroker instance with the necessary configuration, including Kafka broker address.

    broker = KafkaBroker(\"localhost:9092\")\n
  2. Prepare your publisher object to use later as a decorator:

    to_output_data = broker.publisher(\"output_data\")\n
  3. Create your processing logic: Write a function that will consume the incoming messages in the defined format and produce a response to the defined topic

    async def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
  4. Decorate your processing function: To connect your processing function to the desired Kafka topics you need to decorate it with @broker.subscriber(...) and @broker.publisher(...) decorators. Now, after you start your application, your processing function will be called whenever a new message in the subscribed topic is available and produce the function return value to the topic defined in the publisher decorator.

    @to_output_data\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
","boost":10},{"location":"kafka/Publisher/batch_publisher/","title":"Publishing in Batches","text":"","boost":10},{"location":"kafka/Publisher/batch_publisher/#general-overview","title":"General Overview","text":"

If you need to send your data in batches, the @broker.publisher(...) decorator offers a convenient way to achieve this. To enable batch production, you need to perform two crucial steps:

  1. When creating your publisher, set the batch argument to True. This configuration tells the publisher that you intend to send messages in batches.

  2. In your producer function, return a tuple containing the messages you want to send as a batch. This action triggers the producer to gather the messages and transmit them as a batch to a Kafka broker.

Let's delve into a detailed example illustrating how to produce messages in batches to the \"output_data\" topic while consuming from the \"input_data_1\" topic.

","boost":10},{"location":"kafka/Publisher/batch_publisher/#code-example","title":"Code Example","text":"

First, let's take a look at the whole app creation and then dive deep into the steps for producing in batches. Here is the application code:

from typing import Tuple\n\nfrom pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\ndecrease_and_increase = broker.publisher(\"output_data\", batch=True)\n\n\n@decrease_and_increase\n@broker.subscriber(\"input_data_1\")\nasync def on_input_data_1(msg: Data, logger: Logger) -> Tuple[Data, Data]:\n    logger.info(msg)\n    return Data(data=(msg.data * 0.5)), Data(data=(msg.data * 2.0))\n\n\n@broker.subscriber(\"input_data_2\")\nasync def on_input_data_2(msg: Data, logger: Logger) -> None:\n    logger.info(msg)\n    await decrease_and_increase.publish(\n        Data(data=(msg.data * 0.5)), Data(data=(msg.data * 2.0))\n    )\n

Below, we have highlighted key lines of code that demonstrate the steps involved in creating and using a batch publisher:

Step 1: Creation of the Publisher

decrease_and_increase = broker.publisher(\"output_data\", batch=True)\n

Step 2: Publishing an Actual Batch of Messages

You can publish a batch by directly calling the publisher with a batch of messages you want to publish, as shown here:

await decrease_and_increase.publish(\n    Data(data=(msg.data * 0.5)), Data(data=(msg.data * 2.0))\n)\n

Or you can decorate your processing function and return a batch of messages, as shown here:

@decrease_and_increase\n@broker.subscriber(\"input_data_1\")\nasync def on_input_data_1(msg: Data, logger: Logger) -> Tuple[Data, Data]:\n    logger.info(msg)\n    return Data(data=(msg.data * 0.5)), Data(data=(msg.data * 2.0))\n

The application in the example imelements both of these ways, so feel free to use whichever option fits your needs better.

Note

Also, you can publishes messages in batches right from a broker object: just call broker.publish_batch(\"msg2\", \"msg2\", topic=\"output_data\")

","boost":10},{"location":"kafka/Publisher/batch_publisher/#why-publish-in-batches","title":"Why Publish in Batches?","text":"

In the above example, we've explored how to leverage the @broker.publisher(...) decorator to efficiently publish messages in batches using FastStream and Kafka. By following the two key steps outlined in the previous sections, you can significantly enhance the performance and reliability of your Kafka-based applications.

Publishing messages in batches offers several advantages when working with Kafka:

  1. Improved Throughput: Batch publishing allows you to send multiple messages in a single transmission, reducing the overhead associated with individual message delivery. This leads to improved throughput and lower latency in your Kafka applications.

  2. Reduced Network and Broker Load: Sending messages in batches reduces the number of network calls and broker interactions. This optimization minimizes the load on the Kafka brokers and network resources, making your Kafka cluster more efficient.

  3. Atomicity: Batches ensure that a group of related messages is processed together or not at all. This atomicity can be crucial in scenarios where message processing needs to maintain data consistency and integrity.

  4. Enhanced Scalability: With batch publishing, you can efficiently scale your Kafka applications to handle high message volumes. By sending messages in larger chunks, you can make the most of Kafka's parallelism and partitioning capabilities.

","boost":10},{"location":"kafka/Publisher/using_a_key/","title":"Using a Partition Key","text":"

Partition keys are a crucial concept in Apache Kafka, enabling you to determine the appropriate partition for a message. This ensures that related messages are kept together in the same partition, which can be invaluable for maintaining order or grouping related messages for efficient processing. Additionally, Kafka utilizes partitioning to distribute load across multiple brokers and scale horizontally, while replicating data across brokers provides fault tolerance.

You can specify your partition keys when utilizing the @KafkaBroker.publisher(...) decorator in FastStream. This guide will walk you through the process of using partition keys effectively.

","boost":10},{"location":"kafka/Publisher/using_a_key/#publishing-with-a-partition-key","title":"Publishing with a Partition Key","text":"

To publish a message to a Kafka topic using a partition key, follow these steps:

","boost":10},{"location":"kafka/Publisher/using_a_key/#step-1-define-the-publisher","title":"Step 1: Define the Publisher","text":"

In your FastStream application, define the publisher using the @KafkaBroker.publisher(...) decorator. This decorator allows you to configure various aspects of message publishing, including the partition key.

to_output_data = broker.publisher(\"output_data\")\n
","boost":10},{"location":"kafka/Publisher/using_a_key/#step-2-pass-the-key","title":"Step 2: Pass the Key","text":"

When you're ready to publish a message with a specific key, simply include the key parameter in the publish function call. This key parameter is used to determine the appropriate partition for the message.

await to_output_data.publish(Data(data=msg.data + 1.0), key=b\"key\")\n
","boost":10},{"location":"kafka/Publisher/using_a_key/#example-application","title":"Example Application","text":"

Let's examine a complete application example that consumes messages from the \"input_data\" topic and publishes them with a specified key to the \"output_data\" topic. This example will illustrate how to incorporate partition keys into your Kafka-based applications:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import Context, FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\nto_output_data = broker.publisher(\"output_data\")\n\n\n@broker.subscriber(\"input_data\")\nasync def on_input_data(\n    msg: Data, logger: Logger, key: bytes = Context(\"message.raw_message.key\")\n) -> None:\n    logger.info(f\"on_input_data({msg=})\")\n    await to_output_data.publish(Data(data=msg.data + 1.0), key=b\"key\")\n

As you can see, the primary difference from standard publishing is the inclusion of the key parameter in the publish call. This key parameter is essential for controlling how Kafka partitions and processes your messages.

In summary, using partition keys in Apache Kafka is a fundamental practice for optimizing message distribution, maintaining order, and achieving efficient processing. It is a key technique for ensuring that your Kafka-based applications scale gracefully and handle large volumes of data effectively.

","boost":10},{"location":"kafka/Subscriber/","title":"Basic Subscriber","text":"

To start consuming from a Kafka topic, simply decorate your consuming function with a @broker.subscriber(...) decorator, passing a string as a topic key.

In the folowing example, we will create a simple FastStream app that will consume HelloWorld messages from a \"hello_world\" topic.

The full app code looks like this:

from pydantic import BaseModel, Field\n\nfrom faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n\n\nclass HelloWorld(BaseModel):\n    msg: str = Field(\n        ...,\n        examples=[\"Hello\"],\n        description=\"Demo hello world message\",\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"hello_world\")\nasync def on_hello_world(msg: HelloWorld, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"kafka/Subscriber/#import-faststream-and-kafkabroker","title":"Import FastStream and KafkaBroker","text":"

To use the @broker.subscriber(...) decorator, first, we need to import the base FastStream app KafkaBroker to create our broker.

from faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n
","boost":10},{"location":"kafka/Subscriber/#define-the-helloworld-message-structure","title":"Define the HelloWorld Message Structure","text":"

Next, you need to define the structure of the messages you want to consume from the topic using Pydantic. For the guide, we\u2019ll stick to something basic, but you are free to define any complex message structure you wish in your project.

class HelloWorld(BaseModel):\n    msg: str = Field(\n        ...,\n        examples=[\"Hello\"],\n        description=\"Demo hello world message\",\n    )\n
","boost":10},{"location":"kafka/Subscriber/#create-a-kafkabroker","title":"Create a KafkaBroker","text":"

Next, we will create a KafkaBroker object and wrap it into the FastStream object so that we can start our app using CLI later.

broker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n
","boost":10},{"location":"kafka/Subscriber/#create-a-function-that-will-consume-messages-from-a-kafka-hello-world-topic","title":"Create a Function that will Consume Messages from a Kafka hello-world Topic","text":"

Let\u2019s create a consumer function that will consume HelloWorld messages from \"hello_world\" topic and log them.

@broker.subscriber(\"hello_world\")\nasync def on_hello_world(msg: HelloWorld, logger: Logger):\n    logger.info(msg)\n

The function decorated with the @broker.subscriber(...) decorator will be called when a message is produced to Kafka.

The message will then be injected into the typed msg argument of the function, and its type will be used to parse the message.

In this example case, when the message is sent to a \"hello_world\" topic, it will be parsed into a HelloWorld class, and the on_hello_world function will be called with the parsed class as the msg argument value.

","boost":10},{"location":"kafka/Subscriber/batch_subscriber/","title":"Batch Subscriber","text":"

If you want to consume data in batches, the @broker.subscriber(...) decorator makes it possible. By defining your consumed msg object as a list of messages and setting the batch parameter to True, the subscriber will call your consuming function with a batch of messages consumed from a single partition. Let's walk through how to achieve this.

","boost":10},{"location":"kafka/Subscriber/batch_subscriber/#using-the-subscriber-with-batching","title":"Using the Subscriber with Batching","text":"

To consume messages in batches, follow these steps:

","boost":10},{"location":"kafka/Subscriber/batch_subscriber/#step-1-define-your-subscriber","title":"Step 1: Define Your Subscriber","text":"

In your FastStream application, define the subscriber using the @broker.subscriber(...) decorator. Ensure that you configure the msg object as a list and set the batch parameter to True. This configuration tells the subscriber to handle message consumption in batches.

@broker.subscriber(\"test_batch\", batch=True)\n
","boost":10},{"location":"kafka/Subscriber/batch_subscriber/#step-2-implement-your-consuming-function","title":"Step 2: Implement Your Consuming Function","text":"

Create a consuming function that accepts the list of messages. The @broker.subscriber(...) decorator will take care of collecting and grouping messages into batches based on the partition.

@broker.subscriber(\"test_batch\", batch=True)\nasync def handle_batch(msg: List[HelloWorld], logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"kafka/Subscriber/batch_subscriber/#example-of-consuming-in-batches","title":"Example of Consuming in Batches","text":"

Let's illustrate how to consume messages in batches from the \"test_batch\" topic with a practical example:

from typing import List\n\nfrom pydantic import BaseModel, Field\n\nfrom faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\nclass HelloWorld(BaseModel):\n    msg: str = Field(\n        ...,\n        examples=[\"Hello\"],\n        description=\"Demo hello world message\",\n    )\n\n\n@broker.subscriber(\"test_batch\", batch=True)\nasync def handle_batch(msg: List[HelloWorld], logger: Logger):\n    logger.info(msg)\n

In this example, the subscriber is configured to process messages in batches, and the consuming function is designed to handle these batches efficiently.

Consuming messages in batches is a valuable technique when you need to optimize the processing of high volumes of data in your Kafka-based applications. It allows for more efficient resource utilization and can enhance the overall performance of your data pipelines.

","boost":10},{"location":"nats/","title":"NATS","text":"

FastStream NATS support is implemented on top of nats-py. You can always get access to objects of it if you need to use some low-level methods not represented in FastStream.

","boost":10},{"location":"nats/#advantages-and-disadvantages","title":"Advantages and Disadvantages","text":"

NATS is an easy-to-use, high-performance message broker written in Golang. If your application does not require complex routing logic, can cope with high loads, scales, and does not require large hardware costs, NATS will be an excellent choice for you.

Also NATS has a zero-cost new entities creation (to be honest, all subjects are just routing fields), so it can be used as a RPC over MQ tool.

Note

More information about NATS can be found on the official website.

However, NATS has disadvantages that you should be aware of:

","boost":10},{"location":"nats/#nats-jetstream","title":"NATS JetStream","text":"

These shortcomings are corrected by using the persistent level - JetStream. If you need strict guarantees for the delivery and processing of messages at the small detriment of speed and resources consumed, you can use NatsJS.

Also, NatsJS supports some high-level features like Key-Value and Object storages (with subscription to changes on it) and provides you with rich abilities to build your logic on top of it.

","boost":10},{"location":"nats/#routing-rules","title":"Routing Rules","text":"

NATS does not have the ability to configure complex routing rules. The only entity in NATS is subject, which can be subscribed to either directly by name or by a regular expression pattern.

Both examples are discussed a little further.

In order to support the ability to scale consumers horizontally, NATS supports the queue group functionality: a message sent to subject will be processed by a random consumer from the queue group subscribed to this subject. This approach allows you to increase the processing speed of subject by N times when starting N consumers with one group.

","boost":10},{"location":"nats/message/","title":"Access to Message Information","text":"

As you know, FastStream serializes a message body and provides you access to it through function arguments. But sometimes you need to access message_id, headers, or other meta-information.

","boost":10},{"location":"nats/message/#message-access","title":"Message Access","text":"

You can get it in a simple way: just acces the message object in the Context.

It contains the required information such as:

It is a FastStream wrapper around a native broker library message (nats.aio.msg.Msg in the NATS' case) that you can access with raw_message.

from faststream.nats import NatsMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    msg: NatsMessage,\n):\n    print(msg.correlation_id)\n

Also, if you can't find the information you require, you can get access directly to the wrapped nats.aio.msg.Msg, which contains complete message information.

from nats.aio.msg import Msg\nfrom faststream.nats import NatsMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(body: str, msg: NatsMessage):\n    raw: Msg = msg.raw_message\n    print(raw)\n
","boost":10},{"location":"nats/message/#message-fields-access","title":"Message Fields Access","text":"

But in most cases, you don't need all message fields; you need to access some of them. You can use Context Fields access feature for this reason.

For example, you can access the correlation_id like this:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: str = Context(\"message.correlation_id\"),\n):\n    print(cor_id)\n

Or even directly from the raw message:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: str = Context(\"message.raw_message.correlation_id\"),\n):\n    print(cor_id)\n

But this code is too long to reuse everywhere. In this case, you can use a Python Annotated feature:

python 3.9+python 3.6+
from types import Annotated\nfrom faststream import Context\n\nCorrelationId = Annotated[str, Context(\"message.correlation_id\")]\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: CorrelationId,\n):\n    print(cor_id)\n
from typing_extensions import Annotated\nfrom faststream import Context\n\nCorrelationId = Annotated[str, Context(\"message.correlation_id\")]\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: CorrelationId,\n):\n    print(cor_id)\n
","boost":10},{"location":"nats/message/#headers-access","title":"Headers Access","text":"

Sure, you can get access to a raw message and get the headers dict itself, but more often you just need a single header field. So, you can easily access it using the Context:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Context(\"message.headers.user\"),\n):\n    ...\n

Using the special Header class is more convenient, as it also validates the header value using Pydantic. It works the same way as Context, but it is just a shorcut to Context with a default setup. So, you already know how to use it:

from faststream import Header\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Header(),\n):\n    ...\n
","boost":10},{"location":"nats/message/#subject-pattern-access","title":"Subject Pattern Access","text":"

As you know, NATS allows you to use a pattern like this \"logs.*\" to subscriber to subjects. Getting access to the real * value is an often-used scenario, and FastStream provide it to you with the Path object (which is a shortcut to Context(\"message.path.*\")).

To use it, you just need to replace your * with {variable-name} and use Path as a regular Context object:

from faststream import Path\n\n@broker.subscriber(\"logs.{level}\")\nasync def base_handler(\n    body: str,\n    level: str = Path(),\n):\n    ...\n
","boost":10},{"location":"nats/rpc/","title":"RPC over NATS","text":"

Because NATS has zero cost for creating new subjects, we can easily set up a new subject consumer just for the one response message. This way, your request message will be published to one topic, and the response message will be consumed from another one (temporary subject), which allows you to use regular FastStream RPC syntax in the NATS case too.

Tip

FastStream RPC over NATS works in both the NATS-Core and NATS-JS cases as well, but in the NATS-JS case, you have to specify the expected stream as a publish argument.

","boost":10},{"location":"nats/rpc/#blocking-request","title":"Blocking Request","text":"

FastStream provides you with the ability to send a blocking RPC request over NATS in a very simple way.

Just send a message like a regular one and get a response synchronously.

It is very close to the common requests syntax:

msg = await broker.publish(\n    \"Hi!\",\n    subject=\"test\",\n    rpc=True,\n)\n

Also, you have two extra options to control this behavior:

","boost":10},{"location":"nats/rpc/#reply-to","title":"Reply-To","text":"

Also, if you want to create a permanent request-reply data flow, probably, you should create a permanent subject to consume responses.

So, if you have such one, you can specify it with the reply_to argument. This way, FastStream will send a response to this subject automatically.

@broker.subscriber(\"response-subject\")\nasync def consume_responses(msg):\n    ...\n\nmsg = await broker.publish(\n    \"Hi!\",\n    subject=\"test\",\n    reply_to=\"response-subject\",\n)\n
","boost":10},{"location":"nats/examples/direct/","title":"Direct","text":"

The Direct Subject is the basic way to route messages in NATS. Its essence is very simple: a subject sends messages to all consumers subscribed to it.

","boost":10},{"location":"nats/examples/direct/#scaling","title":"Scaling","text":"

If one subject is being listened to by several consumers with the same queue group, the message will go to a random consumer each time.

Thus, NATS can independently balance the load on queue consumers. You can increase the processing speed of the message flow from the queue by simply launching additional instances of the consumer service. You don't need to make changes to the current infrastructure configuration: NATS will take care of how to distribute messages between your services.

","boost":10},{"location":"nats/examples/direct/#example","title":"Example","text":"

The Direct Subject is the type used in FastStream by default: you can simply declare it as follows

@broker.handler(\"test_subject\")\nasync def handler():\n...\n

Full example:

from faststream import FastStream, Logger\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n@broker.subscriber(\"test-subj-1\", \"workers\")\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n@broker.subscriber(\"test-subj-1\", \"workers\")\nasync def base_handler2(logger: Logger):  \n    logger.info(\"base_handler2\")\n\n@broker.subscriber(\"test-subj-2\", \"workers\")\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(\"\", \"test-subj-1\")  # handlers: 1 or 2\n    await broker.publish(\"\", \"test-subj-1\")  # handlers: 1 or 2\n    await broker.publish(\"\", \"test-subj-2\")  # handlers: 3\n
","boost":10},{"location":"nats/examples/direct/#consumer-announcement","title":"Consumer Announcement","text":"

To begin with, we have declared several consumers for two subjects: \"test-subj-1\" and \"test-subj-2\":

@broker.subscriber(\"test-subj-1\", \"workers\")\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n@broker.subscriber(\"test-subj-1\", \"workers\")\nasync def base_handler2(logger: Logger):  \n    logger.info(\"base_handler2\")\n\n@broker.subscriber(\"test-subj-2\", \"workers\")\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n

Note

Note that all consumers are subscribed using the same queue_group. Within the same service, this does not make sense, since messages will come to these handlers in turn. Here, we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"nats/examples/direct/#message-distribution","title":"Message Distribution","text":"

Now the distribution of messages between these consumers will look like this:

await broker.publish(\"\", \"test-subj-1\")  # handlers: 1 or 2\n

The message 1 will be sent to handler1 or handler2 because they are listening to one \"test-subj-1\" subject within one queue group.

await broker.publish(\"\", \"test-subj-1\")  # handlers: 1 or 2\n

Message 2 will be sent similarly to message 1.

await broker.publish(\"\", \"test-subj-2\")  # handlers: 3\n

The message 3 will be sent to handler3 because it is the only one listening to \"test-subj-2\".

","boost":10},{"location":"nats/examples/pattern/","title":"Pattern","text":"

Pattern Subject is a powerful NATS routing engine. This type of subject routes messages to consumers based on the pattern specified when they connect to the subject and a message key.

","boost":10},{"location":"nats/examples/pattern/#scaling","title":"Scaling","text":"

If one subject is being listened to by several consumers with the same queue group, the message will go to a random consumer each time.

Thus, NATS can independently balance the load on queue consumers. You can increase the processing speed of the message flow from the queue by simply launching additional instances of the consumer service. You don't need to make changes to the current infrastructure configuration: NATS will take care of how to distribute messages between your services.

","boost":10},{"location":"nats/examples/pattern/#example","title":"Example","text":"
from faststream import FastStream, Logger\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n@broker.subscriber(\"*.info\", \"workers\")\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n@broker.subscriber(\"*.info\", \"workers\")\nasync def base_handler2(logger: Logger):  \n    logger.info(\"base_handler2\")\n\n@broker.subscriber(\"*.error\", \"workers\")\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(\"\", \"logs.info\")  # handlers: 1 or 2\n    await broker.publish(\"\", \"logs.info\")  # handlers: 1 or 2\n    await broker.publish(\"\", \"logs.error\") # handlers: 3\n
","boost":10},{"location":"nats/examples/pattern/#consumer-announcement","title":"Consumer Announcement","text":"

To begin with, we have announced several consumers for two subjects: \"*.info\" and \"*.error\":

@broker.subscriber(\"*.info\", \"workers\")\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n@broker.subscriber(\"*.info\", \"workers\")\nasync def base_handler2(logger: Logger):  \n    logger.info(\"base_handler2\")\n\n@broker.subscriber(\"*.error\", \"workers\")\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n

At the same time, in the subject of our consumers, we specify the pattern that will be processed by these consumers.

Note

Note that all consumers are subscribed using the same queue_group. Within the same service, this does not make sense, since messages will come to these handlers in turn. Here, we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"nats/examples/pattern/#message-distribution","title":"Message Distribution","text":"

Now the distribution of messages between these consumers will look like this:

await broker.publish(\"\", \"logs.info\")  # handlers: 1 or 2\n

The message 1 will be sent to handler1 or handler2 because they listen to the same subject template within the same queue group.

await broker.publish(\"\", \"logs.info\")  # handlers: 1 or 2\n

Message 2 will be sent similarly to message 1.

await broker.publish(\"\", \"logs.error\") # handlers: 3\n

The message 3 will be sent to handler3 because it is the only one listening to the pattern \"*.error\".

","boost":10},{"location":"nats/jetstream/","title":"NATS JetStream","text":"

The default NATS usage is suitable for scenarios where:

If you need stricter restrictions, like:

You should use the NATS JetStream extension.

In fact, the JetStream extension is the same as NATS, with the addition of a persistent layer above the file system. Therefore, all interfaces for publishing and consuming messages are similar to regular NATS usage.

However, the JetStream layer has many possibilities for configuration, from the policy of deleting old messages to the maximum stored messages number limit. You can find out more about all JetStream features in the official documentation.

If you have worked with other message brokers, then you should know that the logic of JS is closer to Kafka than to RabbitMQ: messages, after confirmation, are not deleted from the queue but remain there until the queue is full, and it will start deleting old messages (or in accordance with other logic that you can configure yourself).

When connecting a consumer (and, especially, when reconnecting), you must determine for yourself according to what logic it will consume messages: from the subject beginning, starting with some message, starting from some time, only new ones, etc. Don't be surprised if a connection is restored, and your consumer starts to process all messages received earlier again - you haven't defined the rule.

Also, NATS JetStream has built-in key-value (similar to Redis) and object (similar to Minio) storages, which, in addition to the interface for put/get, have the ability to subscribe to events, which can be extremely useful in various scenarios.

FastStream does not provide access to this functionality directly, but it is covered by the nats-py library used. You can access the JS object from the application context:

from faststream import FastStream, Logger\nfrom faststream.nats import JStream, NatsBroker\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\nstream = JStream(name=\"stream\")\n\n@broker.subscriber(\n    \"js-subject\",\n    stream=stream,\n    deliver_policy=\"new\",\n)\nasync def handler(msg: str, logger: Logger):\n    logger.info(msg)\n\n@app.after_startup\nasync def test_send():\n    await broker.publish(\"Hi!\", \"js-subject\")\n    # publish with stream verification\n    await broker.publish(\"Hi!\", \"js-subject\", stream=\"stream\")\n

Tip

Using JStream object FastStream is trying to create/update stream with the object settings. To prevent this behavior and just get already created stream, please use JStream(..., declare=False) option.

","boost":10},{"location":"nats/jetstream/ack/","title":"Consuming Acknowledgements","text":"

As you may know, Nats employs a rather extensive Acknowledgement policy.

In most cases, FastStream automatically acknowledges (acks) messages on your behalf. When your function executes correctly, including sending all responses, a message will be acknowledged (and rejected in case of an exception).

However, there are situations where you might want to use different acknowledgement logic.

","boost":10},{"location":"nats/jetstream/ack/#retries","title":"Retries","text":"

If you prefer to use a nack instead of a reject when there's an error in message processing, you can specify the retry flag in the @broker.subscriber(...) method, which is responsible for error handling logic.

By default, this flag is set to False, indicating that if an error occurs during message processing, the message can still be retrieved from the queue:

@broker.subscriber(\"test\", retry=False) # don't handle exceptions\nasync def base_handler(body: str):\n    ...\n

If this flag is set to True, the message will be nacked and placed back in the queue each time an error occurs. In this scenario, the message can be processed by another consumer (if there are several of them) or by the same one:

@broker.subscriber(\"test\", retry=True)  # try again indefinitely\nasync def base_handler(body: str):\n    ...\n

Tip

For more complex error handling cases, you can use tenacity

","boost":10},{"location":"nats/jetstream/ack/#manual-acknowledgement","title":"Manual Acknowledgement","text":"

If you want to acknowledge a message manually, you can get access directy to the message object via the Context and call the method.

from faststream.nats.annotations import NatsMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(body: str, msg: NatsMessage):\n    await msg.ack()\n    # or\n    await msg.nack()\n    # or\n    await msg.reject()\n

FastStream will see that the message was already acknowledged and will do nothing at the end of the process.

","boost":10},{"location":"nats/jetstream/ack/#interrupt-process","title":"Interrupt Process","text":"

If you want to interrupt message processing at any call stack, you can raise faststream.exceptions.AckMessage

from faststream import FastStream\nfrom faststream.exceptions import AckMessage\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\", stream=\"test-stream\")\nasync def handle(body):\n    smth_processing(body)\n\n\ndef smth_processing(body):\n    if True:\n        raise AckMessage()\n\n\n@app.after_startup\nasync def test_publishing():\n    await broker.publish(\"Hello!\", \"test-subject\")\n

This way, FastStream interrupts the current message proccessing and acknowledges it immediately. Also, you can raise NackMessage and RejectMessage too.

Tip

If you want to disable FastStream Acknowledgement logic at all, you can use @broker.subscriber(..., no_ack=True) option. This way you should always process a message (ack/nack/terminate/etc) by yourself.

","boost":10},{"location":"nats/jetstream/key-value/","title":"Key-Value Storage","text":"","boost":10},{"location":"nats/jetstream/key-value/#overview","title":"Overview","text":"

Key-Value storage is just a high-level interface on top of NatsJS.

It is a regular JetStream, where the KV key is a subject.

Put/Update an object to KV by key - it's like publishing a new message to the corresponding subject in the stream.

Thus, the Get command returns not only the current key value but the latest one with an offset of it. Additionally, you can ask for a specific value based on its offset in the KV stream.

This interface provides you with rich abilities to use it like a regular KV storage (ignoring offset) + subscribe to KV key changes + ask for an old KV value revision. So you can use this feature in your application in a really different way. You can find some examples on the NATS developers' official YouTube channel

","boost":10},{"location":"nats/jetstream/key-value/#faststream-details","title":"FastStream Details","text":"

FastStream has no native interfaces to this NatsJS functionality (yet), but it allows you to get access into the inner JetStream object to create it manually.

First of all, you need to create a Key-Value storage object and pass it into the context:

from faststream import Context, FastStream, Logger\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import ContextRepo\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n@app.on_startup\nasync def setup_broker(context: ContextRepo):\n    await broker.connect()\n\n    kv = await broker.stream.create_key_value(bucket=\"bucket\")\n    context.set_global(\"kv\", kv)\n

Tip

We placed this code in @app.on_startup hook because @app.after_startup will be triggered AFTER your handlers start consuming messages. So, if you need to have access to any custom context objects, you should set them up in the @app.on_startup hook.

Also, we call await broker.connect() method manually to establish the connection to be able to create a storage.

Next, we are ready to use this object right in our handlers.

Let's create an annotated object to shorten context object access:

from nats.js.kv import KeyValue as KV\nfrom typing_extensions import Annotated\n\nKeyValue = Annotated[KV, Context(\"kv\")]\n

And just use it in a handler:

from faststream import Logger\n\n@broker.subscriber(\"subject\")\nasync def handler(msg: str, kv: KeyValue, logger: Logger):\n    logger.info(msg)\n    kv_data = await kv.get(\"key\")\n    assert kv_data.value == b\"Hello!\"\n

Finally, let's test our code behavior by putting something into the KV storage and sending a message:

@app.after_startup\nasync def test_send(kv: KeyValue):\n    await kv.put(\"key\", b\"Hello!\")\n    await broker.publish(\"Hi!\", \"subject\")\n
Full listing
from nats.js.kv import KeyValue as KV\nfrom typing_extensions import Annotated\n\nfrom faststream import Logger\nfrom faststream import Context, FastStream, Logger\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import ContextRepo\n\nKeyValue = Annotated[KV, Context(\"kv\")]\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\"subject\")\nasync def handler(msg: str, kv: KeyValue, logger: Logger):\n    logger.info(msg)\n    kv_data = await kv.get(\"key\")\n    assert kv_data.value == b\"Hello!\"\n\n\n@app.on_startup\nasync def setup_broker(context: ContextRepo):\n    await broker.connect()\n\n    kv = await broker.stream.create_key_value(bucket=\"bucket\")\n    context.set_global(\"kv\", kv)\n\n\n@app.after_startup\nasync def test_send(kv: KeyValue):\n    await kv.put(\"key\", b\"Hello!\")\n    await broker.publish(\"Hi!\", \"subject\")\n
","boost":10},{"location":"nats/jetstream/object/","title":"Object Storage","text":"

Object storage is almost identical to the Key-Value stroge concept, so you can reuse the guide.

","boost":10},{"location":"nats/jetstream/object/#overview","title":"Overview","text":"

Object Storage is just a high-level interface on top of NatsJS.

It is a regular JetStream, where the Object key is a subject.

The main difference between KV and Object storages is that in the Object storage, you can store files greater than 1MB (a limitation of KV). It has no limit on the maximum object size and stores it in chunks (each message is an object chunk), so you can literally stream huge objects through NATS.

","boost":10},{"location":"nats/jetstream/object/#faststream-details","title":"FastStream Details","text":"

FastStream has no native interfaces to this NatsJS functionality (yet), but it allows you to access the inner JetStream object to create in manually.

First of all, you need to create an Object storage object and pass in to the context:

from faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import ContextRepo\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n@app.on_startup\nasync def setup_broker(context: ContextRepo):\n    await broker.connect()\n\n    os = await broker.stream.create_object_store(\"bucket\")\n    context.set_global(\"OS\", os)\n

Tip

We placed this code in the @app.on_startup hook because @app.after_startup will be triggered AFTER your handlers start consuming messages. So, if you need to have access to any custom context objects, you should set them up in the @app.on_startup hook.

Also, we call await broker.connect() method manually to establish the connection to be able to create a storage.

Next, we are ready to use this object right in the our handlers.

Let's create an Annotated object to shorten Context object access:

from nats.js.object_store import ObjectStore as OS\nfrom typing_extensions import Annotated\n\nObjectStorage = Annotated[OS, Context(\"OS\")]\n

And just use it in a handler:

from io import BytesIO\n\nfrom faststream import Logger\n\n@broker.subscriber(\"subject\")\nasync def handler(msg: str, os: ObjectStorage, logger: Logger):\n    logger.info(msg)\n    obj = await os.get(\"file\")\n    assert obj.data == b\"File mock\"\n

Finally, let's test our code behavior by putting something into the Object storage and sending a message:

@app.after_startup\nasync def test_send(os: ObjectStorage):\n    await os.put(\"file\", BytesIO(b\"File mock\"))\n    await broker.publish(\"Hi!\", \"subject\")\n

Tip

BytesIO - is a Readable object used to emulate a file opened for reading.

Full listing
from io import BytesIO\n\nfrom nats.js.object_store import ObjectStore as OS\nfrom typing_extensions import Annotated\n\nfrom faststream import Logger\nfrom faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import ContextRepo\n\nObjectStorage = Annotated[OS, Context(\"OS\")]\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\"subject\")\nasync def handler(msg: str, os: ObjectStorage, logger: Logger):\n    logger.info(msg)\n    obj = await os.get(\"file\")\n    assert obj.data == b\"File mock\"\n\n\n@app.on_startup\nasync def setup_broker(context: ContextRepo):\n    await broker.connect()\n\n    os = await broker.stream.create_object_store(\"bucket\")\n    context.set_global(\"OS\", os)\n\n\n@app.after_startup\nasync def test_send(os: ObjectStorage):\n    await os.put(\"file\", BytesIO(b\"File mock\"))\n    await broker.publish(\"Hi!\", \"subject\")\n
","boost":10},{"location":"nats/jetstream/pull/","title":"Pull Subscriber","text":"","boost":10},{"location":"nats/jetstream/pull/#overview","title":"Overview","text":"

NATS JetStream supports two various way to consume messages: Push and Pull consumers.

The Push consumer is used by default to consume messages with the FastStream. It means that the NATS server delivers messages to your consumer as far as possible by itself. However, it also means that NATS should control all current consumer connections and increase server load.

Thus, the Pull consumer is the recommended way to consume JetStream messages by the NATS TEAM. Using it, you simply ask NATS for new messages at some interval. It may sound a little less convenient than automatic message delivery, but it provides several advantages, such as:

So, if you want to consume a large flow of messages without strict time limitations, the Pull consumer is the right choice for you.

","boost":10},{"location":"nats/jetstream/pull/#faststream-details","title":"FastStream Details","text":"

The Pull consumer is just a regular Stream consumer, but with the pull_sub argument, which controls consuming messages with batch size and block interval.

from faststream import FastStream, Logger\nfrom faststream.nats import NatsBroker, PullSub\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    subject=\"test\",\n    stream=\"stream\",\n    pull_sub=PullSub(batch_size=10),\n)\nasync def handle(msg, logger: Logger):\n    logger.info(msg)\n

The batch size doesn't mean that your msg argument is a list of messages, but it means that you consume up to 10 messages for one request to NATS and call your handler for each message in an asyncio.gather pool.

Tip

If you want to consume list of messages, just set the batch=True in PullSub class.

So, your subject will be processed much faster, without blocking for each message processing. However, if your subject has fewer than 10 messages, your request to NATS will be blocked for timeout (5 seconds by default) while trying to collect the required number of messages. Therefor, you should choose batch_size and timeout accurately to optimize your consumer efficiency.

","boost":10},{"location":"nats/publishing/","title":"Publishing","text":"

FastStream NatsBroker supports all regular publishing usecases. You can use them without any changes.

However, if you wish to further customize the publishing logic, you should take a deeper look at specific NatsBroker parameters.

","boost":10},{"location":"nats/publishing/#nats-publishing","title":"NATS Publishing","text":"

NatsBroker also uses the unified publish method (from a publisher object) to send messages.

import asyncio\nfrom faststream.nats import NatsBroker\n\nasync def pub():\n    async with NatsBroker() as broker:\n        await broker.publish(\n            \"Hi!\",\n            subject=\"test\",\n        )\n\nasyncio.run(pub())\n
","boost":10},{"location":"nats/publishing/#basic-arguments","title":"Basic Arguments","text":"

The publish method accepts the following arguments:

","boost":10},{"location":"nats/publishing/#message-parameters","title":"Message Parameters","text":"","boost":10},{"location":"nats/publishing/#natsjs-parameters","title":"NatsJS Parameters","text":"","boost":10},{"location":"rabbit/","title":"Rabbit Routing","text":"

FastStream RabbitMQ support is implemented on top of aio-pika. You can always get access to objects of it, if you need to use some low-level methods, not represented in FastStream.

","boost":10},{"location":"rabbit/#advantages","title":"Advantages","text":"

The advantage of RabbitMQ is the ability to configure flexible and complex message routing scenarios.

RabbitMQ covers the whole range of routing: from one queue - one consumer, to a queue retrieved from several sources, including message prioritization.

Note

For more information about RabbitMQ, please visit the official documentation

It supports the ability to successfully process messages, mark them as processed with an error, remove them from the queue (it is also impossible to re-receive processed messages, unlike Kafka), lock it for the processing duration, and monitor its current status.

Having to keep track of the current status of all messages is a cause of the RabbitMQ performance issues. With really large message volumes, RabbitMQ starts to degrade. However, if this was a \"one-time influx\", then consumers will free the queue of messages and the \"health\" of RabbitMQ will be stable.

If your scenario is not based on processing millions of messages and also requires building complex routing logic, RabbitMQ will be the right choice.

","boost":10},{"location":"rabbit/#basic-concepts","title":"Basic Concepts","text":"

If you want to totally understand how RabbitMQ works, you should visit their official website. There you will find top-level comments about the basic concepts and usage examples.

","boost":10},{"location":"rabbit/#entities","title":"Entities","text":"

RabbitMQ works with three main entities:

","boost":10},{"location":"rabbit/#routing-rules","title":"Routing Rules","text":"

The rules for delivering messages to consumers depend on the type of exchange and binding parameters. All the main options will be discussed at examples.

In general, the message path looks so:

  1. Publisher sends a message to exchange, specify its routing_key and headers according to which routing will take place.
  2. Exchange, depending on the message parameters, determines which of the subscribed bindings to send the message to.
  3. Binding delivers the message to queue or another exchange (in this case it will send it further by its own rules).
  4. Queue, after receiving a message, sends it to one of subscribed consumers (PUSH API).

Tip

By default, all queues have a binding to the default exchange (Direct type) with a routing key corresponding to their name. In FastStream, queues are connected to this exchange, and messages are sent by default unless another exchange is explicitly specified.

Connecting the queue to any other exchange will still leave it subscribed to the `default exchange'. Be careful with this.

At this stage, the message gets into your application - and you start processing it.

","boost":10},{"location":"rabbit/#message-statuses","title":"Message Statuses","text":"

RabbitMQ requires confirmation of message processing: only after that, it will be removed from the queue.

Confirmation can be either positive (Acknowledgment - ack) if the message was successfully processed or negative (Negative Acknowledgment - nack) if the message was processed with an error.

At the same time, in case of an error, the message can also be extracted from the queue (reject); otherwise, after a negative confirmation, it will be requeued for processing again.

In most cases, FastStream performs all the necessary actions by itself. However, if you want to manage the message lifecycle directly, you can access the message object itself and call the appropriate methods directly. This can be useful if you want to implement an \"at most once\" policy and you need to confirm the consuming of the message before it is actually processed.

","boost":10},{"location":"rabbit/#faststream-specific","title":"FastStream Specific","text":"

FastStream omits the ability to create bindings directly, since in most cases, you do not need to subscribe one queue to several exchanges or subscribe exchanges to each other. On the contrary, this practice leads to over-complication of the message routing scheme, which makes it difficult to maintain and further develop the entire infrastructure of services.

FastStream suggests you adhere to the scheme exchange:queue as 1:N, which will greatly simplify the scheme of interaction between your services. It is better to create an additional queue for a new exchange than to subscribe to an existing one.

However, if you want to reduce the number of entities in your RabbitMQ, and thereby optimize its performance (or you know exactly what you are doing), FastStream leaves you the option to create bindings directly. In other cases, the connection parameters are an integral part of the entities RabbitQueue and RabbitExchange in FastStream.

","boost":10},{"location":"rabbit/ack/","title":"Consuming Acknowledgements","text":"

As you may know, RabbitMQ employs a rather extensive Acknowledgement policy.

In most cases, FastStream automatically acknowledges (acks) messages on your behalf. When your function executes correctly, including sending all responses, a message will be acknowledged (and rejected in case of an exception).

However, there are situations where you might want to use a different acknowledgement logic.

","boost":10},{"location":"rabbit/ack/#retries","title":"Retries","text":"

If you prefer to use a nack instead of a reject when there's an error in message processing, you can specify the retry flag in the @broker.subscriber(...) method, which is responsible for error handling logic.

By default, this flag is set to False, indicating that if an error occurs during message processing, the message can still be retrieved from the queue:

@broker.subscriber(\"test\", retry=False) # don't handle exceptions\nasync def base_handler(body: str):\n    ...\n

If this flag is set to True, the message will be nacked and placed back in the queue each time an error occurs. In this scenario, the message can be processed by another consumer (if there are several of them) or by the same one:

@broker.subscriber(\"test\", retry=True)  # try again indefinitely\nasync def base_handler(body: str):\n    ...\n

If the retry flag is set to an int, the message will be placed back in the queue, and the number of retries will be limited to this number:

@broker.subscriber(\"test\", retry=3)     # make up to 3 attempts\nasync def base_handler(body: str):\n    ...\n

Bug

At the moment, attempts are counted only by the current consumer. If the message goes to another consumer, it will have its own counter. Subsequently, this logic will be reworked.

Tip

For more complex error handling cases, you can use tenacity

","boost":10},{"location":"rabbit/ack/#manual-acknowledgement","title":"Manual acknowledgement","text":"

If you want to acknowledge a message manually, you can get access directy to the message object via the Context and call the method.

from faststream.rabbit.annotations import RabbitMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(body: str, msg: RabbitMessage):\n    await msg.ack()\n    # or\n    await msg.nack()\n    # or\n    await msg.reject()\n

FastStream will see that the message was already acknowledged and will do nothing at process end.

","boost":10},{"location":"rabbit/ack/#interrupt-process","title":"Interrupt Process","text":"

If you want to interrupt message processing at any call stack, you can raise faststream.exceptions.AckMessage

from faststream import FastStream\nfrom faststream.exceptions import AckMessage\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(body):\n    smth_processing(body)\n\n\ndef smth_processing(body):\n    if True:\n        raise AckMessage()\n\n\n@app.after_startup\nasync def test_publishing():\n    await broker.publish(\"Hello!\", \"test-queue\")\n

This way, FastStream interrupts the current message proccessing and acknowledges it immediately. Also, you can raise NackMessage and RejectMessage too.

Tip

If you want to disable FastStream Acknowledgement logic at all, you can use @broker.subscriber(..., no_ack=True) option. This way you should always process a message (ack/nack/terminate/etc) by yourself.

","boost":10},{"location":"rabbit/declare/","title":"RabbitMQ Queue/Exchange Declaration","text":"

FastStream declares and validates all exchanges and queues using publishers and subscribers RabbitMQ objects, but sometimes you need to declare them manually.

RabbitBroker provides a way to achieve this easily.

from faststream import FastStream\nfrom faststream.rabbit import (\n    ExchangeType,\n    RabbitBroker,\n    RabbitExchange,\n    RabbitQueue,\n)\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\n\n@app.after_startup\nasync def declare_smth():\n    await broker.declare_exchange(\n        RabbitExchange(\n            name=\"some-exchange\",\n            type=ExchangeType.FANOUT,\n        )\n    )\n\n    await broker.declare_queue(\n        RabbitQueue(\n            name=\"some-queue\",\n            durable=True,\n        )\n    )\n

These methods require just one argument (RabbitQueue/RabbitExchange) containing information about your RabbitMQ required objects. They declare/validate RabbitMQ objects and return low-level aio-pika robust objects to interact with.

Tip

Also, these methods are idempotent, so you can call them with the same arguments multiple times, but the objects will be created once; next time the method will return an already stored object. This way you can get access to any queue/exchange created automatically.

","boost":10},{"location":"rabbit/message/","title":"Access to Message Information","text":"

As you know, FastStream serializes a message body and provides you access to it through function arguments. But sometimes you need access to a message_id, headers, or other meta-information.

","boost":10},{"location":"rabbit/message/#message-access","title":"Message Access","text":"

You can get it in a simple way: just acces the message object in the Context.

This message contains the required information such as:

Also, it is a FastStream wrapper around a native broker library message (aio_pika.IncomingMessage in the RabbitMQ case) that you can access with raw_message.

from faststream.rabbit import RabbitMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    msg: RabbitMessage,\n):\n    print(msg.correlation_id)\n

Also, if you can't find the information you require, you can get access directly to the wrapped aio_pika.IncomingMessage, which contains complete message information.

from aio_pika import IncomingMessage\nfrom faststream.rabbit import RabbitMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(body: str, msg: RabbitMessage):\n    raw: IncomingMessage = msg.raw_message\n    print(raw)\n
","boost":10},{"location":"rabbit/message/#message-fields-access","title":"Message Fields Access","text":"

But in most cases, you don't need all message fields; you need to access some of them. You can use Context Fields access feature for this reason.

For example, you can access the correlation_id like this:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: str = Context(\"message.correlation_id\"),\n):\n    print(cor_id)\n

Or even directly from the raw message:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: str = Context(\"message.raw_message.correlation_id\"),\n):\n    print(cor_id)\n

But this code is too long to be reused everywhere. In this case, you can use a Python Annotated feature:

python 3.9+python 3.6+
from types import Annotated\nfrom faststream import Context\n\nCorrelationId = Annotated[str, Context(\"message.correlation_id\")]\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: CorrelationId,\n):\n    print(cor_id)\n
from typing_extensions import Annotated\nfrom faststream import Context\n\nCorrelationId = Annotated[str, Context(\"message.correlation_id\")]\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: CorrelationId,\n):\n    print(cor_id)\n
","boost":10},{"location":"rabbit/message/#headers-access","title":"Headers Access","text":"

Sure, you can get access to a raw message and get the headers dict itself, but more often you just need a single header field. So, you can easily access it using the Context:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Context(\"message.headers.user\"),\n):\n    ...\n

Using the special Header class is more convenient, as it also validates the header value using Pydantic. It works the same way as Context, but it is just a shorcut to Context with a default setup. So, you already know how to use it:

from faststream import Header\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Header(),\n):\n    ...\n
","boost":10},{"location":"rabbit/message/#topic-pattern-access","title":"Topic Pattern Access","text":"

As you know, Rabbit allows you to use a pattern like this \"logs.*\" with a Topic exchange. Getting access to the real * value is an often-used scenario and FastStream provide it to you with the Path object (which is a shortcut to Context(\"message.path.*\")).

To use it, you just need to replace your * with {variable-name} and use Path as a regular Context object:

from faststream import Path\nfrom faststream import RabbitQueue, RabbitExchane, ExchangeType\n\n@broker.subscriber(\n    RabbitQueue(\n        \"test-queue\",\n        routing_key=\"logs.{level}\",\n    ),\n    RabbitExchange(\n        \"test-exchange\",\n        type=ExchangeType.TOPIC,\n    )\n)\nasync def base_handler(\n    body: str,\n    level: str = Path(),\n):\n    ...\n
","boost":10},{"location":"rabbit/publishing/","title":"Publishing","text":"

FastStream RabbitBroker supports all regular publishing usecases. you can use them without any changes.

However, if you wish to further customize the publishing logic further, you should take a more deep-dive look at specific RabbitBroker parameters.

","boost":10},{"location":"rabbit/publishing/#rabbit-publishing","title":"Rabbit Publishing","text":"

RabbitBroker also uses the unified publish method (from a publisher object) to send messages.

However, in this case, an object of the aio_pika.Message class (if necessary) can be used as a message (in addition to python primitives and pydantic.BaseModel).

You can specify queue (used as a routing_key) and exchange (optionally) to send by their name.

import asyncio\nfrom faststream.rabbit import RabbitBroker\n\nasync def pub():\n    async with RabbitBroker() as broker:\n        await broker.publish(\n            \"Hi!\",\n            queue=\"test\",\n            exchange=\"test\"\n        )\n\nasyncio.run(pub())\n

If you don't specify any exchange, the message will be send to the default one.

Also, you are able to use special RabbitQueue and RabbitExchange objects as queue and exchange arguments:

from faststream.rabbit import RabbitExchange, RabbitQueue\n\nawait broker.publish(\n    \"Hi!\",\n    queue=RabbitQueue(\"test\"),\n    exchange=RabbitExchange(\"test\")\n)\n

If you specify exchange that doesn't exist, RabbitBroker will create a required one and then publish a message to it.

Tip

Be accurate with it: if you have already created an Exchange with specific parameters and try to send a message by exchange name to it, the broker will try to create it. So, Exchange parameters conflict will occur.

If you are trying to send a message to a specific Exchange, sending it with a defined RabbitExchange object is the preffered way.

","boost":10},{"location":"rabbit/publishing/#basic-arguments","title":"Basic Arguments","text":"

The publish method takes the following arguments:

","boost":10},{"location":"rabbit/publishing/#message-parameters","title":"Message Parameters","text":"

You can read more about all the available flags in the RabbitMQ documentation

","boost":10},{"location":"rabbit/publishing/#send-flags","title":"Send Flags","text":"

Arguments for sending a message:

","boost":10},{"location":"rabbit/rpc/","title":"RPC over RMQ","text":"","boost":10},{"location":"rabbit/rpc/#blocking-request","title":"Blocking Request","text":"

FastStream provides you with the ability to send a blocking RPC request over RabbitMQ in a very simple way.

It uses the Direct Reply-To RabbitMQ feature, so you don't need to create any queues to consume a response.

Just send a message like a regular one and get a response synchronously.

It is very close to common requests syntax:

msg = await broker.publish(\n    \"Hi!\",\n    queue=\"test\",\n    rpc=True,\n)\n

Also, you have two extra options to control this behavior:

","boost":10},{"location":"rabbit/rpc/#reply-to","title":"Reply-To","text":"

Also, if you want to create a permanent request-reply data flow, probably, you should create a permanent queue to consume responses.

So, if you have such one, you can specify it with the reply_to argument. This way, FastStream will send a response to this queue automatically.

@broker.subscriber(\"response-queue\")\nasync def consume_responses(msg):\n    ...\n\nmsg = await broker.publish(\n    \"Hi!\",\n    queue=\"test\",\n    reply_to=\"response-queue\",\n)\n
","boost":10},{"location":"rabbit/security/","title":"FastStream RabbitMQ Security","text":"

This chapter discusses the security options available in FastStream and how to use them.

","boost":10},{"location":"rabbit/security/#security-objects","title":"Security Objects","text":"

FastStream allows you to enhance the security of applications by using security objects when creating brokers. These security objects encapsulate security-related configurations and mechanisms. Security objects supported in FastStream for RabbitMQ are:

","boost":10},{"location":"rabbit/security/#1-basesecurity-object","title":"1. BaseSecurity Object","text":"

Purpose: The BaseSecurity object wraps ssl.SSLContext object and is used to enable SSL/TLS encryption for secure communication between FastStream services and external components such as message brokers.

Usage:

import ssl\n\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.security import BaseSecurity\n\nssl_context = ssl.create_default_context()\nsecurity = BaseSecurity(ssl_context=ssl_context)\n\nbroker = RabbitBroker(security=security)\n
","boost":10},{"location":"rabbit/security/#2-saslplaintext-object-with-ssltls","title":"2. SASLPlaintext Object with SSL/TLS","text":"

Purpose: The SASLPlaintext object is used for authentication in SASL (Simple Authentication and Security Layer) plaintext mode. It allows you to provide a username and password for authentication.

Usage:

import ssl\n\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.security import SASLPlaintext\n\nssl_context = ssl.create_default_context()\nsecurity = SASLPlaintext(\n    ssl_context=ssl_context,\n    username=\"admin\",\n    password=\"password\", \n)\n\nbroker = RabbitBroker(security=security)\n
","boost":10},{"location":"rabbit/examples/","title":"Basic Subscriber","text":"

If you know nothing about RabbitMQ and how it works, you will still able to use FastStream RabbitBroker.

Just use the @broker.subscriber(...) method with a string as a routing key.

from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\"routing_key\")  # handle messages by routing key\nasync def handle(msg):\n    print(msg)\n\n\n@app.after_startup\nasync def test_publish():\n    await broker.publish(\n        \"message\",\n        \"routing_key\",  # publish message with routing key\n    )\n

This is the principle all FastStream brokers work by: you don't need to learn them in-depth if you want to just send a message.

","boost":10},{"location":"rabbit/examples/#rabbitmq-details","title":"RabbitMQ Details","text":"

If you are already familiar with RabbitMQ logic, you should also be acquainted with the inner workings of the example mentioned above.

In this case, FastStream either creates or validates a queue with a specified routing_key and binds it to the default RabbitMQ exchange.

If you want to specify a queue-exchange pair with additional arguments, FastStream provides you with the ability to do so. You can use special RabbitQueue and RabbitExchange objects to configure RabbitMQ queues, exchanges, and binding properties. For examples of using various types of exchanges, please refer to the following articles.

","boost":10},{"location":"rabbit/examples/direct/","title":"Direct Exchange","text":"

The Direct Exchange is the basic way to route messages in RabbitMQ. Its core is very simple: the exchange sends messages to those queues whose routing_key matches the routing_key of the message being sent.

Note

The Default Exchange, to which all queues in RabbitMQ are subscribed, has the Direct type by default.

","boost":10},{"location":"rabbit/examples/direct/#scaling","title":"Scaling","text":"

If several consumers are listening to the same queue, messages will be distributed to one of them (round-robin). This behavior is common for all types of exchange because it refers to the queue itself. The type of exchange affects which queues the message gets into.

Thus, RabbitMQ can independently balance the load on queue consumers. You can increase the processing speed of the message flow from the queue by launching additional instances of a consumer service. You don't need to make changes to the current infrastructure configuration: RabbitMQ will take care of how to distribute messages between your services.

","boost":10},{"location":"rabbit/examples/direct/#example","title":"Example","text":"

Tip

The Direct Exchange is the type used in FastStream by default. You can simply declare it as follows:

@broker.subscriber(\"test_queue\", \"test_exchange\")\nasync def handler():\n    ...\n

The argument auto_delete=True in this and subsequent examples is used only to clear the state of RabbitMQ after example runs.

from faststream import FastStream, Logger\nfrom faststream.rabbit import RabbitBroker, RabbitExchange, RabbitQueue\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\nexch = RabbitExchange(\"exchange\", auto_delete=True)\n\nqueue_1 = RabbitQueue(\"test-q-1\", auto_delete=True)\nqueue_2 = RabbitQueue(\"test-q-2\", auto_delete=True)\n\n\n@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 1\n    await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 2\n    await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 1\n    await broker.publish(queue=\"test-q-2\", exchange=exch)  # handlers: 3\n
","boost":10},{"location":"rabbit/examples/direct/#consumer-announcement","title":"Consumer Announcement","text":"

First, we announce our Direct exchange and several queues that will listen to it:

exch = RabbitExchange(\"exchange\", auto_delete=True)\n\nqueue_1 = RabbitQueue(\"test-q-1\", auto_delete=True)\nqueue_2 = RabbitQueue(\"test-q-2\", auto_delete=True)\n

Then we sign up several consumers using the advertised queues to the exchange we created:

@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n

Note

handler1 and handler2 are subscribed to the same exchange using the same queue: within a single service, this does not make sense, since messages will come to these handlers in turn. Here we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"rabbit/examples/direct/#message-distribution","title":"Message Distribution","text":"

Now, the distribution of messages between these consumers will look like this:

await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 1\n

Message 1 will be sent to handler1 because it listens to the \"exchange\" using a queue with the routing key \"test-q-1\".

await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 2\n

Message 2 will be sent to handler2 because it listens to the \"exchange\" using the same queue, but handler1 is busy.

await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 1\n

Message 3 will be sent to handler1 again because it is currently free.

await broker.publish(queue=\"test-q-2\", exchange=exch)  # handlers: 3\n

Message 4 will be sent to handler3 because it is the only one listening to the \"exchange\" using a queue with the routing key \"test-q-2\".

","boost":10},{"location":"rabbit/examples/fanout/","title":"Fanout Exchange","text":"

The Fanout Exchange is an even simpler, but slightly less popular way of routing in RabbitMQ. This type of exchange sends messages to all queues subscribed to it, ignoring any arguments of the message.

At the same time, if the queue listens to several consumers, messages will also be distributed among them.

","boost":10},{"location":"rabbit/examples/fanout/#example","title":"Example","text":"
from faststream import FastStream, Logger\nfrom faststream.rabbit import ExchangeType, RabbitBroker, RabbitExchange, RabbitQueue\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\nexch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.FANOUT)\n\nqueue_1 = RabbitQueue(\"test-q-1\", auto_delete=True)\nqueue_2 = RabbitQueue(\"test-q-2\", auto_delete=True)\n\n\n@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(exchange=exch)  # handlers: 1, 2, 3\n    await broker.publish(exchange=exch)  # handlers: 1, 2, 3\n    await broker.publish(exchange=exch)  # handlers: 1, 2, 3\n    await broker.publish(exchange=exch)  # handlers: 1, 2, 3\n
","boost":10},{"location":"rabbit/examples/fanout/#consumer-announcement","title":"Consumer Announcement","text":"

To begin with, we announced our Fanout exchange and several queues that will listen to it:

exch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.FANOUT)\n\nqueue_1 = RabbitQueue(\"test-q-1\", auto_delete=True)\nqueue_2 = RabbitQueue(\"test-q-2\", auto_delete=True)\n

Then we signed up several consumers using the advertised queues to the exchange we created:

@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n

Note

handler1 and handler2 are subscribed to the same exchange using the same queue: within a single service, this does not make sense, since messages will come to these handlers in turn. Here we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"rabbit/examples/fanout/#message-distribution","title":"Message Distribution","text":"

Now the all messages will be send to all subscribers due they are binded to the same FANOUT exchange:

await broker.publish(exchange=exch)  # handlers: 1, 2, 3\nawait broker.publish(exchange=exch)  # handlers: 1, 2, 3\nawait broker.publish(exchange=exch)  # handlers: 1, 2, 3\nawait broker.publish(exchange=exch)  # handlers: 1, 2, 3\n

Note

When sending messages to Fanout exchange, it makes no sense to specify the arguments queue or routing_key, because they will be ignored.

","boost":10},{"location":"rabbit/examples/headers/","title":"Header Exchange","text":"

The Header Exchange is the most complex and flexible way to route messages in RabbitMQ. This exchange type sends messages to queues according by matching the queue binding arguments with message headers.

At the same time, if several consumers are subscribed to the queue, messages will also be distributed among them.

","boost":10},{"location":"rabbit/examples/headers/#example","title":"Example","text":"
from faststream import FastStream, Logger\nfrom faststream.rabbit import ExchangeType, RabbitBroker, RabbitExchange, RabbitQueue\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\nexch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.HEADERS)\n\nqueue_1 = RabbitQueue(\n    \"test-queue-1\",\n    auto_delete=True,\n    bind_arguments={\"key\": 1},\n)\nqueue_2 = RabbitQueue(\n    \"test-queue-2\",\n    auto_delete=True,\n    bind_arguments={\"key\": 2, \"key2\": 2, \"x-match\": \"any\"},\n)\nqueue_3 = RabbitQueue(\n    \"test-queue-3\",\n    auto_delete=True,\n    bind_arguments={\"key\": 2, \"key2\": 2, \"x-match\": \"all\"},\n)\n\n\n@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n\n@broker.subscriber(queue_3, exch)\nasync def base_handler4(logger: Logger):\n    logger.info(\"base_handler4\")\n\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 1\n    await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 2\n    await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 1\n    await broker.publish(exchange=exch, headers={\"key\": 2})  # handlers: 3\n    await broker.publish(exchange=exch, headers={\"key2\": 2})  # handlers: 3\n    await broker.publish(\n        exchange=exch, headers={\"key\": 2, \"key2\": 2.0}\n    )  # handlers: 3, 4\n
","boost":10},{"location":"rabbit/examples/headers/#consumer-announcement","title":"Consumer Announcement","text":"

First, we announce our Header exchange and several queues that will listen to it:

exch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.HEADERS)\n\nqueue_1 = RabbitQueue(\n    \"test-queue-1\",\n    auto_delete=True,\n    bind_arguments={\"key\": 1},\n)\nqueue_2 = RabbitQueue(\n    \"test-queue-2\",\n    auto_delete=True,\n    bind_arguments={\"key\": 2, \"key2\": 2, \"x-match\": \"any\"},\n)\nqueue_3 = RabbitQueue(\n    \"test-queue-3\",\n    auto_delete=True,\n    bind_arguments={\"key\": 2, \"key2\": 2, \"x-match\": \"all\"},\n)\n

The x-match argument indicates whether the arguments should match the message headers in whole or in part.

Then we signed up several consumers using the advertised queues to the exchange we created:

@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n\n@broker.subscriber(queue_3, exch)\nasync def base_handler4(logger: Logger):\n    logger.info(\"base_handler4\")\n

Note

handler1 and handler2 are subscribed to the same exchange using the same queue: within a single service, this does not make sense, since messages will come to these handlers in turn. Here we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"rabbit/examples/headers/#message-distribution","title":"Message Distribution","text":"

Now the distribution of messages between these consumers will look like this:

await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 1\n

Message 1 will be sent to handler1 because it listens to a queue whose \"key\" header matches the \"key\" header of the message.

await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 2\n

Message 2 will be sent to handler2 because it listens to exchange using the same queue, but handler1 is busy.

await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 1\n

Message 3 will be sent to handler1 again because it is currently free.

await broker.publish(exchange=exch, headers={\"key\": 2})  # handlers: 3\n

Message 4 will be sent to handler3 because it listens to a queue whose \"key\" header coincided with the \"key\" header of the message.

await broker.publish(exchange=exch, headers={\"key2\": 2})  # handlers: 3\n

Message 5 will be sent to handler3 because it listens to a queue whose header \"key2\" coincided with the header \"key2\" of the message.

await broker.publish(\n    exchange=exch, headers={\"key\": 2, \"key2\": 2.0}\n)  # handlers: 3, 4\n

Message 6 will be sent to handler3 and handler4 because the message headers completely match the queue keys.

Note

When sending messages to Header exchange, it makes no sense to specify the arguments queue or routing_key, because they will be ignored

Warning

For incredibly complex routes, you can use the option to bind an exchange to another exchange. In this case, all the same rules apply as for queues subscribed to exchange. The only difference is that the signed exchange can further distribute messages according to its own rules.

So, for example, you can combine Topic and Header exchange types.

","boost":10},{"location":"rabbit/examples/stream/","title":"RabbitMQ Streams","text":"

RabbitMQ has a Streams feature, which is closely related to Kafka topics.

The main difference from regular RabbitMQ queues is that the messages are not deleted after consuming.

And FastStream supports this feature as well!

from faststream import FastStream, Logger\nfrom faststream.rabbit import RabbitBroker, RabbitQueue\n\nbroker = RabbitBroker(max_consumers=10)\napp = FastStream(broker)\n\nqueue = RabbitQueue(\n    name=\"test-stream\",\n    durable=True,\n    arguments={\n        \"x-queue-type\": \"stream\",\n    },\n)\n\n\n@broker.subscriber(\n    queue,\n    consume_args={\"x-stream-offset\": \"first\"},\n)\nasync def handle(msg, logger: Logger):\n    logger.info(msg)\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"Hi!\", queue)\n
","boost":10},{"location":"rabbit/examples/topic/","title":"Topic Exchange","text":"

The Topic Exchange is a powerful RabbitMQ routing tool. This type of exchange sends messages to the queue in accordance with the pattern specified when they are connected to exchange and the routing_key of the message itself.

At the same time, if several consumers are subscribed to the queue, messages will be distributed among them.

","boost":10},{"location":"rabbit/examples/topic/#example","title":"Example","text":"
from faststream import FastStream, Logger\nfrom faststream.rabbit import ExchangeType, RabbitBroker, RabbitExchange, RabbitQueue\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\nexch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.TOPIC)\n\nqueue_1 = RabbitQueue(\"test-queue-1\", auto_delete=True, routing_key=\"*.info\")\nqueue_2 = RabbitQueue(\"test-queue-2\", auto_delete=True, routing_key=\"*.debug\")\n\n\n@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 1\n    await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 2\n    await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 1\n    await broker.publish(routing_key=\"logs.debug\", exchange=exch)  # handlers: 3\n
","boost":10},{"location":"rabbit/examples/topic/#consumer-announcement","title":"Consumer Announcement","text":"

First, we announce our Topic exchange and several queues that will listen to it:

exch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.TOPIC)\n\nqueue_1 = RabbitQueue(\"test-queue-1\", auto_delete=True, routing_key=\"*.info\")\nqueue_2 = RabbitQueue(\"test-queue-2\", auto_delete=True, routing_key=\"*.debug\")\n

At the same time, in the routing_key of our queues, we specify the pattern of routing keys that will be processed by this queue.

Then we sign up several consumers using the advertised queues to the exchange we created:

@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n

Note

handler1 and handler2 are subscribed to the same exchange using the same queue: within a single service, this does not make sense, since messages will come to these handlers in turn. Here we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"rabbit/examples/topic/#message-distribution","title":"Message Distribution","text":"

Now the distribution of messages between these consumers will look like this:

await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 1\n

Message 1 will be sent to handler1 because it listens to \"exchange\" using a queue with the routing key \"*.info\".

await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 2\n

Message 2 will be sent to handler2 because it listens to \"exchange\" using the same queue, but handler1 is busy.

await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 1\n

Message 3 will be sent to handler1 again because it is currently free.

await broker.publish(routing_key=\"logs.debug\", exchange=exch)  # handlers: 3\n

Message 4 will be sent to handler3 because it is the only one listening to \"exchange\" using a queue with the routing key \"*.debug\".

","boost":10},{"location":"redis/","title":"Redis Broker","text":"","boost":10},{"location":"redis/#redis-overview","title":"Redis Overview","text":"","boost":10},{"location":"redis/#what-is-redis","title":"What is Redis?","text":"

Redis is an open-source, in-memory data structure store, used as a database, cache, and message broker. It supports various data structures such as strings, hashes, lists, sets, sorted sets, bitmaps, hyperloglogs, and geospatial indexes with radius queries. Redis has built-in replication, Lua scripting, LRU eviction, transactions, and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.

","boost":10},{"location":"redis/#key-redis-concepts","title":"Key Redis Concepts","text":"

Redis is not just a key-value store; it is a data structures server, supporting different kinds of values. This makes Redis flexible and suitable for a wide range of problems. It offers versatile approaches for message handling through Pub/Sub, List, and Stream structures.

","boost":10},{"location":"redis/#1-pubsub","title":"1. Pub/Sub","text":"

Redis Pub/Sub implements the Publish/Subscribe messaging paradigm where senders (publishers) are not programmed to send their messages to specific receivers (subscribers). Instead, published messages are characterized into channels, without knowledge of what (if any) subscribers there may be.

","boost":10},{"location":"redis/#2-list","title":"2. List","text":"

In contrast, Redis List capitalizes on a straightforward list data structure. Messages, pushed by producers, form a first-in, first-out (FIFO) queue. Consumers, in turn, retrieve messages from this ordered list, providing a simplified mechanism for sequential message processing.

","boost":10},{"location":"redis/#3-streams","title":"3. Streams","text":"

Redis Streams introduce a more advanced concept, embracing an append-only log-like structure. Messages, organized as entries, allow for nuanced features like consumer groups, enabling parallel processing, and acknowledgment for precise message handling. Streams excel in scenarios demanding scalability, persistence, and ordered message processing.

Ultimately, the choice between Pub/Sub, List, or Streams hinges on the specific needs of the application. Redis Pub/Sub suits real-time communication, List offers simplicity in ordered processing, while Streams cater to complex, scalable, and ordered message handling, each providing tailored solutions based on distinct use case requirements.

","boost":10},{"location":"redis/#redis-in-faststream","title":"Redis in FastStream","text":"","boost":10},{"location":"redis/#faststream-redisbroker","title":"FastStream RedisBroker","text":"

The FastStream RedisBroker is a key component of the FastStream framework that enables seamless integration with Redis. With the RedisBroker, developers can easily connect to Redis instances, publish messages to Redis channels, and subscribe to Redis channels within their FastStream applications.

","boost":10},{"location":"redis/#establishing-a-connection","title":"Establishing a Connection","text":"

To connect to Redis using the FastStream RedisBroker module, follow these steps:

  1. Initialize the RedisBroker instance: Start by initializing a RedisBroker instance with the necessary configuration, including Redis server address and port.

  2. Create your processing logic: Write a function that will consume the incoming messages from the subscribed channel and optionally publish a response to another channel.

  3. Decorate your processing function: To connect your processing function to the desired Redis channels, you need to decorate it with @broker.subscriber(...) and @broker.publisher(...) decorators. Now, after you start your application, your processing function will be called whenever a new message in the subscribed channel is available and produce the function return value to the channel defined in the publisher decorator.

Here's a simplified code example demonstrating how to establish a connection to Redis using FastStream's RedisBroker module:

from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-channel\")\n@broker.publisher(\"out-channel\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n

This minimal example illustrates how FastStream simplifies the process of connecting to Redis and performing basic message processing from the in-channel to the out-channel. Depending on your specific use case and requirements, you can further customize your Redis integration with FastStream to build efficient and responsive applications.

For more advanced configuration options and detailed usage instructions, please refer to the FastStream Redis documentation and the official Redis documentation.

","boost":10},{"location":"redis/message/","title":"Accessing Redis Message Information with FastStream","text":"

In FastStream, messages passed through a Redis broker are serialized and can be interacted with just like function parameters. However, you might occasionally need to access more than just the message content, such as metadata and other attributes.

","boost":10},{"location":"redis/message/#redis-message-access","title":"Redis Message Access","text":"

When dealing with Redis broker in FastStream, you can easily access message details by using the RedisMessage object which wraps the underlying message with additional context information. This object is specifically tailored for Redis and contains relevant message attributes:

For instance, if you need to retrieve headers from an incoming Redis message, here\u2019s how you might do it:

from faststream.redis import RedisMessage\n\n@broker.subscriber(\"test-stream\")\nasync def stream_handler(msg: str, message: RedisMessage):\n    print(message.headers)\n
","boost":10},{"location":"redis/message/#targeted-message-fields-access","title":"Targeted Message Fields Access","text":"

It's common to require only specific elements of the message rather than the entire data structure. For this purpose, FastStream allows you to access individual message fields by specifying the field you are interested in as an argument in your handler function.

For example, if you want to access the headers directly, you might do it as follows:

from faststream import Context\n\n@broker.subscriber(\"test-stream\")\nasync def stream_handler(\n    msg: str,\n    headers: AnyDict = Context(\"message.headers\"),\n):\n    print(headers)\n

The Context object lets you reference message attributes directly, making your handler functions neater and reducing the amount of boilerplate code needed.

","boost":10},{"location":"redis/rpc/","title":"Redis RPC with FastStream","text":"

FastStream RedisBroker provides the powerful capability to perform Remote Procedure Calls (RPC) using Redis. This feature enables you to send a message and await a response, effectively creating a synchronous request-response pattern over the inherently asynchronous Redis messaging system. Below is the guide to set up and utilize the Redis RPC publishing feature with FastStream.

Note

The RPC feature is implemented over Redis Pub/Sub indepenently of the original subscriber type.

","boost":10},{"location":"redis/rpc/#rpc-with-redis-overview","title":"RPC with Redis Overview","text":"

In a traditional publish/subscribe setup, the publishing party sends messages without expecting any direct response from the subscribers. However, with RPC, the publisher sends a message and waits for a response from the subscriber, which can then be used for subsequent operations or processing.

FastStream allows you to define RPC-style communication channels, lists, or streams by using the RedisBroker's publishing function with the rpc flag set to True.

","boost":10},{"location":"redis/rpc/#implementing-redis-rpc-in-faststream","title":"Implementing Redis RPC in FastStream","text":"

To implement Redis RPC with RedisBroker in FastStream, follow the steps below:

  1. Initiate your FastStream application with RedisBroker

    broker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n
  2. Define subscriber handlers for various Redis data types (e.g., channel, list, stream) that can process incoming messages and return responses.

    @broker.subscriber(channel=\"test-channel\")\nasync def handle_channel(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n\n\n@broker.subscriber(list=\"test-list\")\nasync def handle_list(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n\n\n@broker.subscriber(stream=\"test-stream\")\nasync def handle_stream(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n
  3. Send RPC messages through RedisBroker and await responses on the correct data type.

    After your application has started and the subscribers are ready to receive messages, you can publish messages with the rpc option enabled. Additionally, you can set an rpc_timeout to decide how long the publisher should wait for a response before timing out.

    @app.after_startup\nasync def t():\n    msg = \"Hi!\"\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        channel=\"test-channel\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        list=\"test-list\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        stream=\"test-stream\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n

In this example, we assert that the msg sent is the same as the response received from the subscriber, demonstrating an operational RPC pattern over three different Redis data types.

","boost":10},{"location":"redis/rpc/#full-example-of-redis-rpc-with-faststream","title":"Full Example of Redis RPC with FastStream","text":"

Combining all the code snippets above, here is the complete example of how to set up Redis RPC with FastStream RedisBroker:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(channel=\"test-channel\")\nasync def handle_channel(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n\n\n@broker.subscriber(list=\"test-list\")\nasync def handle_list(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n\n\n@broker.subscriber(stream=\"test-stream\")\nasync def handle_stream(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n\n\n@app.after_startup\nasync def t():\n    msg = \"Hi!\"\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        channel=\"test-channel\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        list=\"test-list\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        stream=\"test-stream\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n

By embracing Redis RPC with FastStream, you can build sophisticated message-based architectures that require direct feedback from message processors. This feature is particularly suitable for cases where immediate processing is necessary or calling functions across different services is essential.

","boost":10},{"location":"redis/security/","title":"FastStream Redis Security","text":"

This chapter discusses the security options available in FastStream and how to use them.

","boost":10},{"location":"redis/security/#security-objects","title":"Security Objects","text":"

FastStream allows you to enhance the security of applications by using security objects when creating brokers. These security objects encapsulate security-related configurations and mechanisms. Security objects supported in FastStream for Redis are:

","boost":10},{"location":"redis/security/#1-basesecurity-object","title":"1. BaseSecurity Object","text":"

Purpose: The BaseSecurity object wraps ssl.SSLContext object and is used to enable SSL/TLS encryption for secure communication between FastStream services and external components such as message brokers.

Usage:

import ssl\n\nfrom faststream.redis import RedisBroker\nfrom faststream.security import BaseSecurity\n\nssl_context = ssl.create_default_context()\nsecurity = BaseSecurity(ssl_context=ssl_context)\n\nbroker = RedisBroker(security=security)\n
","boost":10},{"location":"redis/security/#2-saslplaintext-object-with-ssltls","title":"2. SASLPlaintext Object with SSL/TLS","text":"

Purpose: The SASLPlaintext object is used for authentication in SASL (Simple Authentication and Security Layer) plaintext mode. It allows you to provide a username and password for authentication.

Usage:

import ssl\n\nfrom faststream.redis import RedisBroker\nfrom faststream.security import SASLPlaintext\n\nssl_context = ssl.create_default_context()\nsecurity = SASLPlaintext(\n    ssl_context=ssl_context,\n    username=\"admin\",\n    password=\"password\", \n)\n\nbroker = RedisBroker(security=security)\n
","boost":10},{"location":"redis/list/","title":"Redis Lists","text":"

Redis Lists are a simple and flexible data structure that function as ordered collections of strings. They are similar to lists in programming languages, and Redis provides commands to perform a variety of operations such as adding, retrieving, and removing elements from either end of the list.

Redis Lists are particularly useful for scenarios such as implementing queues, effectively using the list as a FIFO (First-In-First-Out) structure.

","boost":10},{"location":"redis/list/batch/","title":"Redis List Batch Subscriber","text":"

If you want to consume data in batches from a Redis list, the @broker.subscriber(...) decorator makes it possible. By defining your consumed msg object as a list of messages and setting the batch parameter to True within the ListSub object, the subscriber will call your consuming function with a batch of messages. Let's walk through how to achieve this with the FastStream library.

","boost":10},{"location":"redis/list/batch/#using-the-subscriber-with-batching","title":"Using the Subscriber with Batching","text":"

To consume messages in batches from a Redis list, follow these steps:

","boost":10},{"location":"redis/list/batch/#step-1-define-your-subscriber","title":"Step 1: Define Your Subscriber","text":"

In your FastStream application, define the subscriber using the @broker.subscriber(...) decorator. Ensure that you pass a ListSub object with the batch parameter set to True. This configuration tells the subscriber to handle message consumption in batches from the specified Redis list.

@broker.subscriber(list=ListSub(\"test-list\", batch=True))\n
","boost":10},{"location":"redis/list/batch/#step-2-implement-your-consuming-function","title":"Step 2: Implement Your Consuming Function","text":"

Create a consuming function that accepts the list of messages. The @broker.subscriber(...) decorator will take care of collecting and grouping messages into batches.

@broker.subscriber(list=ListSub(\"test-list\", batch=True))\nasync def handle(msg: list[str], logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/list/batch/#example-of-consuming-in-batches","title":"Example of Consuming in Batches","text":"

Let's illustrate how to consume messages in batches from the \"test-list\" Redis list with a practical example:

from faststream import FastStream, Logger\nfrom faststream.redis import ListSub, RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(list=ListSub(\"test-list\", batch=True))\nasync def handle(msg: list[str], logger: Logger):\n    logger.info(msg)\n

In this example, the subscriber is configured to process messages in batches from the Redis list, and the consuming function is designed to handle these batches efficiently.

Consuming messages in batches is a valuable technique when you need to optimize the processing of high volumes of data in your Redis-based applications. It allows for more efficient resource utilization and can enhance the overall performance of your data processing tasks.

","boost":10},{"location":"redis/list/batch/#batch-publishing","title":"Batch publishing","text":"

Also, Redis List is the only data structure supporting publishing in batches with FastStream. To send multiple messages in a single request, you just need to:

","boost":10},{"location":"redis/list/publishing/","title":"Redis List Publishing with FastStream","text":"

Utilizing the FastStream library, you can effectively publish data to Redis lists, which act as queues in Redis-based messaging systems.

","boost":10},{"location":"redis/list/publishing/#understanding-redis-list-publishing","title":"Understanding Redis List Publishing","text":"

Just like with Redis streams, messages can be published to Redis lists. FastStream utilizes the @broker.publisher(...) decorator, along with a list's name, to push messages onto the list.

  1. Instantiate your RedisBroker

    broker = RedisBroker(\"localhost:6379\")\n
  2. Create your FastStream application with the instantiated RedisBroker

    app = FastStream(broker)\n
  3. Define a Pydantic model for your data

    class Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n
  4. Implement a data processing function for publishing to Redis lists

    Use the @broker.publisher(list=\"...\") decorator alongside the @broker.subscriber(list=\"...\") decorator to create a function that processes incoming messages and pushes the results to an output list in Redis.

    @broker.subscriber(list=\"input-list\")\n@broker.publisher(list=\"output-list\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n

In this pattern, the function stands as a subscriber to the \"input-list\" and publishes the processed data as a new message to the \"output-list\". By using decorators, you establish a pipeline that reads messages from one Redis list, applies some logic, and then pushes outputs to another list.

","boost":10},{"location":"redis/list/publishing/#full-example-of-redis-list-publishing","title":"Full Example of Redis List Publishing","text":"

Here's an example that demonstrates Redis list publishing in action using decorators with FastStream:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = RedisBroker(\"localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(list=\"input-list\")\n@broker.publisher(list=\"output-list\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n

The provided example illustrates the ease of setting up publishing mechanisms to interact with Redis lists. In this environment, messages are dequeued from the input list, processed, and enqueued onto the output list seamlessly, empowering developers to leverage Redis lists as messaging queues.

By following these simple steps, you can perform list-based publish/subscribe operations in a Redis environment using the FastStream library, capitalizing on Redis' fast, in-memory data structure store capabilities.

","boost":10},{"location":"redis/list/subscription/","title":"Redis List Basic Subscriber","text":"

To start consuming from a Redis list, simply decorate your consuming function with the @broker.subscriber(...) decorator, passing a string as the list key.

In the following example, we will create a simple FastStream app that will consume messages from a \"test-list\" Redis list.

The full app code looks like this:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(list=\"test-list\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/list/subscription/#import-faststream-and-redisbroker","title":"Import FastStream and RedisBroker","text":"

To use the @broker.subscriber(...) decorator, first, we need to import the base FastStream app and RedisBroker to create our broker.

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n
","boost":10},{"location":"redis/list/subscription/#create-a-redisbroker","title":"Create a RedisBroker","text":"

Next, we will create a RedisBroker object and wrap it into the FastStream object so that we can start our app using CLI later.

broker = RedisBroker()\napp = FastStream(broker)\n
","boost":10},{"location":"redis/list/subscription/#create-a-function-that-will-consume-messages-from-a-redis-list","title":"Create a Function that will Consume Messages from a Redis list","text":"

Let\u2019s create a consumer function that will consume messages from \"test-list\" Redis list and log them.

@broker.subscriber(list=\"test-list\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n

The function decorated with the @broker.subscriber(...) decorator will be called when a message is pushed to the Redis list.

The message will then be injected into the typed msg argument of the function, and its type will be used to parse the message.

In this example case, when the message is pushed to a \"test-list\" list, it will be received by the handle function, and the logger will log the message content.

","boost":10},{"location":"redis/pubsub/","title":"Redis Channels","text":"

Redis Pub/Sub Channels are a feature of Redis that enables messaging between clients through a publish/subscribe (pub/sub) pattern. A Redis channel is essentially a medium through which messages are transmitted. Different clients can subscribe to these channels to listen for messages, while other clients can publish messages to these channels.

When a message is published to a Redis channel, all subscribers to that channel receive the message instantly. This makes Redis channels suitable for a variety of real-time applications such as chat rooms, notifications, live updates, and many more use cases where messages must be broadcast promptly to multiple clients.

","boost":10},{"location":"redis/pubsub/#limitations","title":"Limitations","text":"

Redis Pub/Sub Channels, while powerful for real-time communication in scenarios like chat rooms and live updates, have certain limitations when compared to Redis List and Redis Streams.

In summary, while Redis Pub/Sub excels in simplicity and real-time broadcast scenarios, Redis List and Redis Streams provide additional features such as message persistence, ordered processing, and scalability, making them better suited for certain use cases with specific requirements. The choice between these Redis features depends on the nature of the application and its messaging needs.

","boost":10},{"location":"redis/pubsub/publishing/","title":"Publishing","text":"

The FastStream RedisBroker supports all standard publishing use cases similar to the KafkaBroker, allowing you to publish messages to Redis channels with ease.

Below you will find guidance on how to utilize the RedisBroker for publishing messages, including creating publisher objects and using decorators for streamlined publishing workflows.

","boost":10},{"location":"redis/pubsub/publishing/#basic-redis-channel-publishing","title":"Basic Redis Channel Publishing","text":"

The RedisBroker allows you to publish messages directly to Redis channels. You can use Python primitives and pydantic.BaseModel to define the content of the message.

To publish a message to a Redis channel, follow these steps:

  1. Create your RedisBroker instance

    broker = RedisBroker(\"redis://localhost:6379\")\n
  2. Publish a message using the publish method

    await broker.publish(msg, \"input_data\")\n

This is the most straightforward way to use the RedisBroker to publish messages to Redis channels.

","boost":10},{"location":"redis/pubsub/publishing/#creating-a-publisher-object","title":"Creating a publisher object","text":"

For a more structured approach and to include your publishers in the AsyncAPI documentation, it's recommended to create publisher objects. Here's how to do it:

  1. Create your RedisBroker instance

    broker = RedisBroker(\"redis://localhost:6379\")\n
  2. Create a publisher instance for a specific channel

    prepared_publisher = broker.publisher(\"input_data\")\n
  3. Publish a message using the publish method of the prepared publisher

    await prepared_publisher.publish(msg)\n

When you encapsulate your broker within a FastStream object, the publisher will be documented in your service's AsyncAPI documentation.

","boost":10},{"location":"redis/pubsub/publishing/#decorating-your-publishing-functions","title":"Decorating your publishing functions","text":"

Decorators in FastStream provide a convenient way to define the data flow within your application. The RedisBroker allows you to use decorators to publish messages to Redis channels, similar to the KafkaBroker.

By decorating a function with both @broker.subscriber(...) and @broker.publisher(...), you create a DataPipeline unit that processes incoming messages and publishes the results to another channel. The order of decorators does not matter, but they must be applied to a function that has already been decorated by a @broker.subscriber(...).

The decorated function should have a return type annotation to ensure the correct interpretation of the return value before it's published.

Here's an example of using decorators with RedisBroker:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\nto_output_data = broker.publisher(\"output_data\")\n\n\n@to_output_data\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
  1. Initialize the RedisBroker instance: Start by creating a RedisBroker instance.

    broker = RedisBroker(\"redis://localhost:6379\")\n
  2. Prepare your publisher object to be used as a decorator:

    to_output_data = broker.publisher(\"output_data\")\n
  3. Create your processing logic: Implement a function that will process incoming messages and produce a response to be published to another Redis channel.

    async def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
  4. Decorate your processing function: Apply the @broker.subscriber(...) and @broker.publisher(...) decorators to your function to define the input channel and the output channel, respectively. Once your application is running, this decorated function will be triggered whenever a new message arrives on the \"input_data\" channel, and it will publish the result to the \"output_data\" channel.

    @to_output_data\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
","boost":10},{"location":"redis/pubsub/subscription/","title":"Channel Subscription","text":"","boost":10},{"location":"redis/pubsub/subscription/#basic-channel-subscription","title":"Basic Channel Subscription","text":"

Redis Pub/Sub is the default subscriber type in FastStream, so you can simply create a regular @broker.subscriber(\"channel_name\") with a channel name and it creates a subscriber using Redis Pub/Sub.

In this example, we will build a FastStream application that listens to messages from the Redis channel named \"test\".

The complete application code is presented below:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/pubsub/subscription/#import-faststream-and-redisbroker","title":"Import FastStream and RedisBroker","text":"

To utilize the @broker.subscriber(...) decorator for Redis channel subscription, you must first import FastStream and RedisBroker.

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n
","boost":10},{"location":"redis/pubsub/subscription/#create-a-redisbroker-instance","title":"Create a RedisBroker Instance","text":"

Create a RedisBroker object and pass it to the FastStream object. This setup prepares the application for launch using the FastStream CLI.

broker = RedisBroker()\napp = FastStream(broker)\n
","boost":10},{"location":"redis/pubsub/subscription/#define-the-message-handler-function","title":"Define the Message Handler Function","text":"

Construct a function that will act as the consumer of messages from the \"test\" channel and use the logger to output the message content.

@broker.subscriber(\"test\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n

When a message is published to the Redis channel \"test\", it will trigger the invocation of the decorated function. The message will be passed to the function's msg parameter, while the logger will be available for logging purposes.

","boost":10},{"location":"redis/pubsub/subscription/#pattern-channel-subscription","title":"Pattern Channel Subscription","text":"

For subscribing to multiple Redis channels matching a pattern, use the @broker.subscriber(channel=PubSub(\"pattern\", pattern=True)) decorator, where the channel argument receives a PubSub object with the pattern and pattern flag set to True.

Here's how to create a FastStream application that subscribes to all channels matching the \"test.*\" pattern:

from faststream import FastStream, Logger\nfrom faststream.redis import PubSub, RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(channel=PubSub(\"test.*\", pattern=True))\nasync def handle_test(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/pubsub/subscription/#use-pubsub-for-pattern-matching","title":"Use PubSub for Pattern Matching","text":"

Import the PubSub class from faststream.redis along with other necessary modules.

from faststream import FastStream, Logger\nfrom faststream.redis import PubSub, RedisBroker\n
","boost":10},{"location":"redis/pubsub/subscription/#specify-the-pattern-for-channel-subscription","title":"Specify the Pattern for Channel Subscription","text":"

To define the pattern subscription, create a PubSub object with the desired pattern (\"test.*\" in this case) and indicate that it's a pattern subscription by setting pattern=True.

@broker.subscriber(channel=PubSub(\"test.*\", pattern=True))\n
","boost":10},{"location":"redis/pubsub/subscription/#create-the-pattern-message-handler-function","title":"Create the Pattern Message Handler Function","text":"

Decide on a function that will act as the subscriber of messages from channels matching the specified pattern. Logging the messages is handled similarly as with basic channel subscription.

@broker.subscriber(channel=PubSub(\"test.*\", pattern=True))\nasync def handle_test(msg: str, logger: Logger):\n    logger.info(msg)\n

With pattern channel subscription, when a message is published to a channel that matches the specified pattern (\"test.*\"), our handler function will be invoked. The message is delivered to the msg argument of the function, similar to how it works in basic channel subscriptions.

","boost":10},{"location":"redis/pubsub/subscription/#pattern-data-access","title":"Pattern data access","text":"

You can also use the Redis Pub/Sub pattern feature to encode some data directly in the channel name. With FastStream you can easily access this data using the following code:

from faststream import FastStream, Logger, Path\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test.{data}\")\nasync def handle_test(\n    msg: str,\n    logger: Logger,\n    data: str = Path(),\n):\n    logger.info(f\"Channel `{data=}`, body `{msg=}`\")\n
","boost":10},{"location":"redis/streams/","title":"Redis Streams","text":"

Redis Streams are a data structure introduced in Redis 5.0 that offer a reliable and highly scalable way to handle streams of data. They are similar to logging systems like Apache Kafka, where data is stored in a log structure and can be consumed by multiple clients. Streams provide a sequence of ordered messages, and they are designed to handle a high volume of data by allowing partitioning and multiple consumers.

A Redis Stream is a collection of entries, each having an ID (which includes a timestamp) and a set of key-value pairs representing the message data. Clients can add to a stream by generating a new entry and can read from a stream to consume its messages.

Streams have unique features such as:

","boost":10},{"location":"redis/streams/ack/","title":"Stream Acknowledgement","text":"

When working with Redis streams in the FastStream library, it's important to manage message acknowledgements carefully to ensure that messages are not lost and that they have been processed as intended.

By default, when using the FastStream with a Redis stream, the library will automatically acknowledge (ack) that a message has been processed. This follows the at most once processing guarantee.

","boost":10},{"location":"redis/streams/ack/#manual-acknowledgement","title":"Manual Acknowledgement","text":"

In cases where you want explicit control over when a message is acknowledged, you can manually acknowledge a message by accessing the ack and nack methods provided:

from faststream.redis.annotations import RedisMessage, Redis\n\n# Setup broker and faststream app\n...\n\n@broker.subscriber(StreamSub(\"test-stream\", group=\"test-group\", consumer=\"1\"))\nasync def base_handler(body: dict, msg: RedisMessage, redis: Redis):\n    # Process the message\n    ...\n\n    # Manually acknowledge the message\n    await msg.ack(redis)\n    # or, if processing fails and you want to reprocess later\n    await msg.nack()\n

Using ack will mark the message as processed in the stream, while nack is useful for situations where you might need to reprocess a message due to a handling failure.

","boost":10},{"location":"redis/streams/ack/#interrupt-process","title":"Interrupt Process","text":"

If the need arises to instantly interrupt message processing at any point in the call stack and acknowledge the message, you can achieve this by raising the faststream.exceptions.AckMessage exception:

from faststream import FastStream\nfrom faststream.exceptions import AckMessage\nfrom faststream.redis import RedisBroker, StreamSub\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(stream=StreamSub(\"test-stream\", group=\"test-group\", consumer=\"1\"))\nasync def handle(body):\n    processing_logic(body)\n\n\ndef processing_logic(body):\n    if True:\n        raise AckMessage()\n\n\n@app.after_startup\nasync def test_publishing():\n    await broker.publish(\"Hello World!\", stream=\"test-stream\")\n

By raising AckMessage, FastStream will halt the current message processing routine and immediately acknowledge it. Analogously, raising NackMessage would prevent the message from being acknowledged and could lead to its subsequent reprocessing by the same or a different consumer.

Tip

If you want to disable FastStream Acknowledgement logic at all, you can use @broker.subscriber(..., no_ack=True) option. This way you should always process a message (ack/nack/terminate/etc) by yourself.

","boost":10},{"location":"redis/streams/batch/","title":"Redis Stream Batch Subscriber","text":"

If you want to consume data in batches from a Redis stream, the @broker.subscriber(...) decorator makes it possible. By defining your consumed msg object as a list of messages and setting the batch parameter to True within the StreamSub object, the subscriber will call your consuming function with a batch of messages. Let's walk through how to achieve this with the FastStream library.

","boost":10},{"location":"redis/streams/batch/#using-the-subscriber-with-batching","title":"Using the Subscriber with Batching","text":"

To consume messages in batches from a Redis stream, follow these steps:

","boost":10},{"location":"redis/streams/batch/#step-1-define-your-subscriber","title":"Step 1: Define Your Subscriber","text":"

In your FastStream application, define the subscriber using the @broker.subscriber(...) decorator. Ensure that you pass a StreamSub object with the batch parameter set to True. This configuration tells the subscriber to handle message consumption in batches from the specified Redis stream.

@broker.subscriber(stream=StreamSub(\"test-stream\", batch=True))\n
","boost":10},{"location":"redis/streams/batch/#step-2-implement-your-consuming-function","title":"Step 2: Implement Your Consuming Function","text":"

Create a consuming function that accepts the list of messages. The @broker.subscriber(...) decorator will take care of collecting and grouping messages into batches.

@broker.subscriber(stream=StreamSub(\"test-stream\", batch=True))\nasync def handle(msg: list[str], logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/streams/batch/#example-of-consuming-in-batches","title":"Example of Consuming in Batches","text":"

Let's illustrate how to consume messages in batches from the \"test-stream\" Redis stream with a practical example:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker, StreamSub\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(stream=StreamSub(\"test-stream\", batch=True))\nasync def handle(msg: list[str], logger: Logger):\n    logger.info(msg)\n

In this example, the subscriber is configured to process messages in batches from the Redis stream, and the consuming function is designed to handle these batches efficiently.

Consuming messages in batches is a valuable technique when you need to optimize the processing of high volumes of data in your Redis-based applications. It allows for more efficient resource utilization and can enhance the overall performance of your data processing tasks.

","boost":10},{"location":"redis/streams/groups/","title":"Redis Stream Consumer Groups","text":"

Consuming messages from a Redis stream can be accomplished by using a Consumer Group. This allows multiple consumers to divide the workload of processing messages in a stream and provides a form of message acknowledgment, ensuring that messages are not processed repeatedly.

Consumer Groups in Redis enable a group of clients to cooperatively consume different portions of the same stream of messages. When using group=\"...\" (which internally uses XREADGROUP), messages are distributed among different consumers in a group and are not delivered to any other consumer in that group again, unless they are not acknowledged (i.e., the client fails to process and does not call msg.ack() or XACK). This is in contrast to a normal consumer (also known as XREAD), where every consumer sees all the messages. XREAD is useful for broadcasting to multiple consumers, while XREADGROUP is better suited for workload distribution.

In the following example, we will create a simple FastStream app that utilizes a Redis stream with a Consumer Group. It will consume messages sent to the \"test-stream\" as part of the \"test-group\" consumer group.

The full app code is as follows:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker, StreamSub\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(stream=StreamSub(\"test-stream\", group=\"test-group\", consumer=\"1\"))\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n\n\n@app.after_startup\nasync def t():\n    await broker.publish(\"Hi!\", stream=\"test-stream\")\n
","boost":10},{"location":"redis/streams/groups/#import-faststream-and-redisbroker","title":"Import FastStream and RedisBroker","text":"

First, import the FastStream class and the RedisBroker from the faststream.redis module to define our broker.

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker, StreamSub\n
","boost":10},{"location":"redis/streams/groups/#create-a-redisbroker","title":"Create a RedisBroker","text":"

To establish a connection to Redis, instantiate a RedisBroker object and pass it to the FastStream app.

broker = RedisBroker()\napp = FastStream(broker)\n
","boost":10},{"location":"redis/streams/groups/#define-a-consumer-group-subscription","title":"Define a Consumer Group Subscription","text":"

Define a subscription to a Redis stream with a specific Consumer Group using the StreamSub object and the @broker.subscriber(...) decorator. Then, define a function that will be triggered when new messages are sent to the \"test-stream\" Redis stream. This function is decorated with @broker.subscriber(...) and will process the messages as part of the \"test-group\" consumer group.

@broker.subscriber(stream=StreamSub(\"test-stream\", group=\"test-group\", consumer=\"1\"))\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/streams/groups/#publishing-a-message","title":"Publishing a message","text":"

Publishing a message is the same as what's defined on Stream Publishing.

await broker.publish(\"Hi!\", stream=\"test-stream\")\n

By following the steps and code examples provided above, you can create a FastStream application that consumes messages from a Redis stream using a Consumer Group for distributed message processing.

","boost":10},{"location":"redis/streams/publishing/","title":"Redis Stream Publishing with FastStream","text":"","boost":10},{"location":"redis/streams/publishing/#publishing-data-to-redis-stream","title":"Publishing Data to Redis Stream","text":"

To publish messages to a Redis Stream, you implement a function that processes the incoming data and applies the @broker.publisher(...) decorator along with the Redis stream name to it. The function will then publish its return value to the specified stream.

  1. Create your RedisBroker instance

    broker = RedisBroker(\"redis://localhost:6379\")\n
  2. Initiate your FastStream application with the RedisBroker

    app = FastStream(broker)\n
  3. Define your data model

    class Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n
  4. Set up the function for data processing and publishing

    Using the @broker.publisher(...) decorator in conjunction with the @broker.subscriber(...) decorator allows seamless message processing and republishing to a different stream.

    @broker.subscriber(stream=\"input-stream\")\n@broker.publisher(stream=\"output-stream\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n

    By decorating a function with @broker.publisher(...), we tell FastStream to publish the function's returned data to the designated \"output stream\". The defined function also serves as a subscriber to the \"input-stream\", thereby setting up a straightforward data pipeline within Redis streams.

Here's the complete example that showcases the use of decorators for both subscribing and publishing to Redis streams:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(stream=\"input-stream\")\n@broker.publisher(stream=\"output-stream\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
","boost":10},{"location":"redis/streams/subscription/","title":"Redis Stream Basic Subscriber","text":"

To start consuming from a Redis stream, simply decorate your consuming function with the @broker.subscriber(...) decorator, passing a string as the stream key.

In the following example, we will create a simple FastStream app that will consume messages from a \"test-stream\" Redis stream.

The full app code looks like this:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(stream=\"test-stream\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/streams/subscription/#import-faststream-and-redisbroker","title":"Import FastStream and RedisBroker","text":"

To use the @broker.subscriber(...) decorator, first, we need to import the base FastStream app and RedisBroker to create our broker.

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n
","boost":10},{"location":"redis/streams/subscription/#create-a-redisbroker","title":"Create a RedisBroker","text":"

Next, we will create a RedisBroker object and wrap it into the FastStream object so that we can start our app using CLI later.

broker = RedisBroker()\napp = FastStream(broker)\n
","boost":10},{"location":"redis/streams/subscription/#create-a-function-that-will-consume-messages-from-a-redis-stream","title":"Create a Function that will Consume Messages from a Redis stream","text":"

Let\u2019s create a consumer function that will consume messages from \"test-stream\" Redis stream and log them.

@broker.subscriber(stream=\"test-stream\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n

The function decorated with the @broker.subscriber(...) decorator will be called when a message is produced to the Redis stream.

The message will then be injected into the typed msg argument of the function, and its type will be used to parse the message.

In this example case, when the message is sent to a \"test-stream\" stream, it will be received by the handle function, and the logger will log the message content.

","boost":10}]} \ No newline at end of file diff --git a/0.3/sitemap.xml.gz b/0.3/sitemap.xml.gz index 1729056846b2f75e04485cec93407ef4713aa689..ed66140119c59bc532398ce01262c5a1a26dfb57 100644 GIT binary patch delta 15 WcmbQEIY*OCzMF&NnBPXWX(9k7Tm--X delta 15 WcmbQEIY*OCzMF$1)p8@-G!XzJtprK{ diff --git a/latest/release/index.html b/latest/release/index.html index 4426df72cc..a1b3f09c95 100644 --- a/latest/release/index.html +++ b/latest/release/index.html @@ -9,7 +9,7 @@ body[data-md-color-scheme="slate"] .gdesc-inner { background: var(--md-default-bg-color);} body[data-md-color-scheme="slate"] .gslide-title { color: var(--md-default-fg-color);} body[data-md-color-scheme="slate"] .gslide-desc { color: var(--md-default-fg-color);} -
Skip to content

Release Notes#

0.3.8#

What's Changed#

Full Changelog: #0.3.7...0.3.8

0.3.7#

What's Changed#

Support regular FastStream Context with FastAPI plugin

from fastapi import FastAPI
+                  

Release Notes#

0.3.9#

What's Changed#

Bug fixes:#

  • fix (#1082): correct NatsTestClient stream publisher by @Lancetnik in #1083

Chore:#

Full Changelog: #0.3.8...0.3.9

0.3.8#

What's Changed#

Full Changelog: #0.3.7...0.3.8

0.3.7#

What's Changed#

Support regular FastStream Context with FastAPI plugin

from fastapi import FastAPI
 from faststream.redis.fastapi import RedisRouter, Logger
 
 router = RedisRouter()
@@ -20,7 +20,7 @@
 
 app = FastAPI(lifespan=router.lifespan_context)
 app.include_router(router)
-

Full Changelog: #0.3.6...0.3.7

0.3.6#

What's Changed#

  • chore: correct update release CI by @Lancetnik in #1050
  • Update Release Notes for main by @faststream-release-notes-updater in #1051
  • chore: fix building docs script by @davorrunje in #1055
  • 0.3.6 by @Lancetnik in #1056
  • bug: remove packaging dependency
  • bug: correct FastAPI batch consuming
  • docs: add search meta to all pages
  • docs: polish all pages styles, fix typos
  • chore: add ruff rule to check print

Full Changelog: #0.3.5...0.3.6

0.3.5#

What's Changed#

A large update by @Lancetnik in #1048

Provides with the ability to setup graceful_timeout to wait for consumed messages processed correctly before apllication shutdown - Broker(graceful_timeout=30.0) (waits up to 30 seconds)

  • allows to get acces to context.get_local("message") from FastAPI plugin
  • docs: fix Avro custom serialization example
  • docs: add KafkaBroker publish_batch notice
  • docs: add RabbitMQ security page
  • fix: respect retry attempts with NackMessage exception
  • test Kafka nack and reject behavior
  • bug: fix import error with anyio version 4.x by @davorrunje in #1049

Full Changelog: #0.3.4...0.3.5

0.3.4#

What's Changed#

Features:#

Documentation#

Chore#

Full Changelog: #0.3.3...0.3.4

0.3.3#

What's Changed#

Features:

Chores:

Full Changelog: #0.3.2...0.3.3

0.3.2#

What's Changed#

New features:#

Chore:#

Full Changelog: #0.3.1...0.3.2

0.3.1#

What's Changed#

Features:

Bug fixes:

  • fix: non-payload information injected included in AsyncAPI docs by @Lancetnik in #1015

Documentation:

New Contributors#

Full Changelog: #0.3.0...0.3.1

0.3.0#

What's Changed#

The main feature of the 0.3.0 release is added Redis support by @Lancetnik in #1003

You can install it by the following command:

pip install "faststream[redis]"
+

Full Changelog: #0.3.6...0.3.7

0.3.6#

What's Changed#

  • chore: correct update release CI by @Lancetnik in #1050
  • Update Release Notes for main by @faststream-release-notes-updater in #1051
  • chore: fix building docs script by @davorrunje in #1055
  • 0.3.6 by @Lancetnik in #1056
  • bug: remove packaging dependency
  • bug: correct FastAPI batch consuming
  • docs: add search meta to all pages
  • docs: polish all pages styles, fix typos
  • chore: add ruff rule to check print

Full Changelog: #0.3.5...0.3.6

0.3.5#

What's Changed#

A large update by @Lancetnik in #1048

Provides with the ability to setup graceful_timeout to wait for consumed messages processed correctly before apllication shutdown - Broker(graceful_timeout=30.0) (waits up to 30 seconds)

  • allows to get acces to context.get_local("message") from FastAPI plugin
  • docs: fix Avro custom serialization example
  • docs: add KafkaBroker publish_batch notice
  • docs: add RabbitMQ security page
  • fix: respect retry attempts with NackMessage exception
  • test Kafka nack and reject behavior
  • bug: fix import error with anyio version 4.x by @davorrunje in #1049

Full Changelog: #0.3.4...0.3.5

0.3.4#

What's Changed#

Features:#

Documentation#

Chore#

Full Changelog: #0.3.3...0.3.4

0.3.3#

What's Changed#

Features:

Chores:

Full Changelog: #0.3.2...0.3.3

0.3.2#

What's Changed#

New features:#

Chore:#

Full Changelog: #0.3.1...0.3.2

0.3.1#

What's Changed#

Features:

Bug fixes:

  • fix: non-payload information injected included in AsyncAPI docs by @Lancetnik in #1015

Documentation:

New Contributors#

Full Changelog: #0.3.0...0.3.1

0.3.0#

What's Changed#

The main feature of the 0.3.0 release is added Redis support by @Lancetnik in #1003

You can install it by the following command:

pip install "faststream[redis]"
 

Here is a little code example

from faststream import FastStream, Logger
 from faststream.redis import RedisBroker
 
@@ -34,8 +34,8 @@
 )
 async def handle(msg: str, logger: Logger):
     logger.info(msg)
-

Other features#

  • feat: show reload directories with --reload flag by @Lancetnik in #981
  • feat: implement validate and no_ack subscriber options (#926) by @mihail8531 in #988
  • other features by @Lancetnik in #1003
    • Improve error logs (missing CLI arguments, undefined starting)
    • Add faststream docs serve --reload ... option for documentation hotreload
    • Add faststream run --reload-extension .env option to watch by changes in such files
    • Support faststream run -k 1 -k 2 ... as k=["1", "2"] extra options
    • Add subscriber, publisher and router include_in_schema: bool argument to disable AsyncAPI render
    • remove watchfiles from default distribution
    • Allow create broker.publisher(...) with already running broker
    • FastAPI-like lifespan FastStream application context manager
    • automatic TestBroker(connect_only=...) argument based on AST
    • add NatsMessage.in_progress() method

Testing#

Documentation#

Chore#

New Contributors#

Full Changelog: #0.2.15...0.3.0

0.3.0rc0#

What's Changed#

The main feature of the 0.3.x release is added Redis support by @Lancetnik in #1003

You can install it manually:

pip install faststream==0.3.0rc0 && pip install "faststream[redis]"
-

Other features#

  • feat: show reload directories with --reload flag by @Lancetnik in #981
  • Improve error logs (missing CLI arguments, undefined starting)
  • Add faststream docs serve --reload ... option for documentation hotreload
  • Add faststream run --reload-extension .env option to watch by changes in such files
  • Support faststream run -k 1 -k 2 ... as k=["1", "2"] extra options
  • Add subscriber, publisher and router include_in_schema: bool argument to disable AsyncAPI render
  • remove watchfiles from default distribution
  • Allow create @broker.publisher(...) with already running broker
  • FastAPI-like lifespan FastStream application context manager
  • automatic TestBroker(connect_only=...) argument based on AST
  • add NatsMessage.in_progress() method

Testing#

Documentation#

Chore#

New Contributors#

Full Changelog: #0.2.15...0.3.0rc0

0.2.15#

What's Changed#

Bug fixes#

Documentation#

Misc#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.14...0.2.15

0.2.14#

What's Changed#

Bug fixes#

Documentation#

Misc#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.13...0.2.14

0.2.13#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.12...0.2.13

0.2.12#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.11...0.2.12

0.2.11#

What's Changed#

Bug fixes#

Documentation#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.10...0.2.11

Documentation#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.10...0.2.11

0.2.10#

What's Changed#

Now, you can hide your connection secrets in the AsyncAPI schema by manually setting up the server URL:

broker = RabbitBroker(
+

Other features#

  • feat: show reload directories with --reload flag by @Lancetnik in #981
  • feat: implement validate and no_ack subscriber options (#926) by @mihail8531 in #988
  • other features by @Lancetnik in #1003
    • Improve error logs (missing CLI arguments, undefined starting)
    • Add faststream docs serve --reload ... option for documentation hotreload
    • Add faststream run --reload-extension .env option to watch by changes in such files
    • Support faststream run -k 1 -k 2 ... as k=["1", "2"] extra options
    • Add subscriber, publisher and router include_in_schema: bool argument to disable AsyncAPI render
    • remove watchfiles from default distribution
    • Allow create broker.publisher(...) with already running broker
    • FastAPI-like lifespan FastStream application context manager
    • automatic TestBroker(connect_only=...) argument based on AST
    • add NatsMessage.in_progress() method

Testing#

Documentation#

Chore#

New Contributors#

Full Changelog: #0.2.15...0.3.0

0.3.0rc0#

What's Changed#

The main feature of the 0.3.x release is added Redis support by @Lancetnik in #1003

You can install it manually:

pip install faststream==0.3.0rc0 && pip install "faststream[redis]"
+

Other features#

  • feat: show reload directories with --reload flag by @Lancetnik in #981
  • Improve error logs (missing CLI arguments, undefined starting)
  • Add faststream docs serve --reload ... option for documentation hotreload
  • Add faststream run --reload-extension .env option to watch by changes in such files
  • Support faststream run -k 1 -k 2 ... as k=["1", "2"] extra options
  • Add subscriber, publisher and router include_in_schema: bool argument to disable AsyncAPI render
  • remove watchfiles from default distribution
  • Allow create @broker.publisher(...) with already running broker
  • FastAPI-like lifespan FastStream application context manager
  • automatic TestBroker(connect_only=...) argument based on AST
  • add NatsMessage.in_progress() method

Testing#

Documentation#

Chore#

New Contributors#

Full Changelog: #0.2.15...0.3.0rc0

0.2.15#

What's Changed#

Bug fixes#

Documentation#

Misc#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.14...0.2.15

0.2.14#

What's Changed#

Bug fixes#

Documentation#

Misc#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.13...0.2.14

0.2.13#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.12...0.2.13

0.2.12#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.11...0.2.12

0.2.11#

What's Changed#

Bug fixes#

Documentation#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.10...0.2.11

Documentation#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.10...0.2.11

0.2.10#

What's Changed#

Now, you can hide your connection secrets in the AsyncAPI schema by manually setting up the server URL:

broker = RabbitBroker(
     "amqp://guest:guest@localhost:5672/",  # Connection URL
     asyncapi_url="amqp://****:****@localhost:5672/",  # Public schema URL
 )
@@ -45,7 +45,7 @@
 )
 
 # amqp://guest:guest@127.0.0.1:5672/ - The final URL
-
* A more suitable faststream.security import instead of faststream.broker.security * chore: add release notes for 0.2.9 by @kumaranvpl in https://github.com/airtai/faststream/pull/894 * chore: upgrade packages by @davorrunje in https://github.com/airtai/faststream/pull/901 * chore: use js redirect and redirect to version by @kumaranvpl in https://github.com/airtai/faststream/pull/902 * feat: add asyncapi_url broker arg by @Lancetnik in https://github.com/airtai/faststream/pull/903

Full Changelog: https://github.com/airtai/faststream/compare/0.2.9...0.2.10

0.2.9#

What's Changed#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.8...0.2.9

0.2.8#

What's Changed#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.7...0.2.8

0.2.7#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.6...0.2.7

0.2.6#

What's Changed#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.5...0.2.6

0.2.5#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.4...0.2.5

0.2.4#

New Functionalities#

Now, Context provides access to inner dict keys too:

# headers is a `dict`
+
* A more suitable faststream.security import instead of faststream.broker.security * chore: add release notes for 0.2.9 by @kumaranvpl in https://github.com/airtai/faststream/pull/894 * chore: upgrade packages by @davorrunje in https://github.com/airtai/faststream/pull/901 * chore: use js redirect and redirect to version by @kumaranvpl in https://github.com/airtai/faststream/pull/902 * feat: add asyncapi_url broker arg by @Lancetnik in https://github.com/airtai/faststream/pull/903

Full Changelog: https://github.com/airtai/faststream/compare/0.2.9...0.2.10

0.2.9#

What's Changed#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.8...0.2.9

0.2.8#

What's Changed#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.7...0.2.8

0.2.7#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.6...0.2.7

0.2.6#

What's Changed#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.5...0.2.6

0.2.5#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.4...0.2.5

0.2.4#

New Functionalities#

Now, Context provides access to inner dict keys too:

# headers is a `dict`
 async def handler(
   user_id: int = Context("message.headers.user_id", cast=True),
 ): ...
@@ -58,4 +58,4 @@
 async def handler(
   level: str = Path(),
 )
-

Also, the original message Context annotation was copied from faststream.[broker].annotations.[Broker]Message to faststream.[broker].[Broker]Message to provide you with faster access to the most commonly used object (NATS example).

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.3...0.2.4

0.2.3#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.2...0.2.3

0.2.2#

What's Changed#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.1...0.2.2

0.2.1#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.0...0.2.1

0.2.0#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.1.6...0.2.0

0.1.6#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.1.5...0.1.6

0.1.4#

What's Changed#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.1.3...0.1.4

0.1.3#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.1.1...0.1.3

0.1.1#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/commits/0.1.1

0.1.0#

FastStream is a new package based on the ideas and experiences gained from FastKafka and Propan. By joining our forces, we picked up the best from both packages and created the unified way to write services capable of processing streamed data regardless of the underlying protocol. We'll continue to maintain both packages, but new development will be in this project. If you are starting a new service, this package is the recommended way to do it.

Features#

FastStream simplifies the process of writing producers and consumers for message queues, handling all the parsing, networking and documentation generation automatically.

Making streaming microservices has never been easier. Designed with junior developers in mind, FastStream simplifies your work while keeping the door open for more advanced use-cases. Here's a look at the core features that make FastStream a go-to framework for modern, data-centric microservices.

  • Multiple Brokers: FastStream provides a unified API to work across multiple message brokers (Kafka, RabbitMQ support)

  • Pydantic Validation: Leverage Pydantic's validation capabilities to serialize and validates incoming messages

  • Automatic Docs: Stay ahead with automatic AsyncAPI documentation.

  • Intuitive: full typed editor support makes your development experience smooth, catching errors before they reach runtime

  • Powerful Dependency Injection System: Manage your service dependencies efficiently with FastStream's built-in DI system.

  • Testable: supports in-memory tests, making your CI/CD pipeline faster and more reliable

  • Extendable: use extensions for lifespans, custom serialization and middlewares

  • Integrations: FastStream is fully compatible with any HTTP framework you want (FastAPI especially)

  • Built for Automatic Code Generation: FastStream is optimized for automatic code generation using advanced models like GPT and Llama

That's FastStream in a nutshell—easy, efficient, and powerful. Whether you're just starting with streaming microservices or looking to scale, FastStream has got you covered.

\ No newline at end of file +

Also, the original message Context annotation was copied from faststream.[broker].annotations.[Broker]Message to faststream.[broker].[Broker]Message to provide you with faster access to the most commonly used object (NATS example).

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.3...0.2.4

0.2.3#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.2...0.2.3

0.2.2#

What's Changed#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.1...0.2.2

0.2.1#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.2.0...0.2.1

0.2.0#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.1.6...0.2.0

0.1.6#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.1.5...0.1.6

0.1.4#

What's Changed#

New Contributors#

Full Changelog: https://github.com/airtai/faststream/compare/0.1.3...0.1.4

0.1.3#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/compare/0.1.1...0.1.3

0.1.1#

What's Changed#

Full Changelog: https://github.com/airtai/faststream/commits/0.1.1

0.1.0#

FastStream is a new package based on the ideas and experiences gained from FastKafka and Propan. By joining our forces, we picked up the best from both packages and created the unified way to write services capable of processing streamed data regardless of the underlying protocol. We'll continue to maintain both packages, but new development will be in this project. If you are starting a new service, this package is the recommended way to do it.

Features#

FastStream simplifies the process of writing producers and consumers for message queues, handling all the parsing, networking and documentation generation automatically.

Making streaming microservices has never been easier. Designed with junior developers in mind, FastStream simplifies your work while keeping the door open for more advanced use-cases. Here's a look at the core features that make FastStream a go-to framework for modern, data-centric microservices.

  • Multiple Brokers: FastStream provides a unified API to work across multiple message brokers (Kafka, RabbitMQ support)

  • Pydantic Validation: Leverage Pydantic's validation capabilities to serialize and validates incoming messages

  • Automatic Docs: Stay ahead with automatic AsyncAPI documentation.

  • Intuitive: full typed editor support makes your development experience smooth, catching errors before they reach runtime

  • Powerful Dependency Injection System: Manage your service dependencies efficiently with FastStream's built-in DI system.

  • Testable: supports in-memory tests, making your CI/CD pipeline faster and more reliable

  • Extendable: use extensions for lifespans, custom serialization and middlewares

  • Integrations: FastStream is fully compatible with any HTTP framework you want (FastAPI especially)

  • Built for Automatic Code Generation: FastStream is optimized for automatic code generation using advanced models like GPT and Llama

That's FastStream in a nutshell—easy, efficient, and powerful. Whether you're just starting with streaming microservices or looking to scale, FastStream has got you covered.

\ No newline at end of file diff --git a/latest/search/search_index.json b/latest/search/search_index.json index 7060df4656..f336ed3ebc 100644 --- a/latest/search/search_index.json +++ b/latest/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"separator":"[\\s\\-,:!=\\[\\]()\"`/]+|\\.(?!\\d)|&[lg]t;|(?!\\b)(?=[A-Z][a-z])","pipeline":["stopWordFilter"]},"docs":[{"location":"release/","title":"Release Notes","text":"","boost":2},{"location":"release/#038","title":"0.3.8","text":"","boost":2},{"location":"release/#whats-changed","title":"What's Changed","text":"

Full Changelog: #0.3.7...0.3.8

","boost":2},{"location":"release/#037","title":"0.3.7","text":"","boost":2},{"location":"release/#whats-changed_1","title":"What's Changed","text":"

Support regular FastStream Context with FastAPI plugin

from fastapi import FastAPI\nfrom faststream.redis.fastapi import RedisRouter, Logger\n\nrouter = RedisRouter()\n\n@router.subscriber(\"test\")\nasync def handler(msg, logger: Logger):\n    logger.info(msg)\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n

Full Changelog: #0.3.6...0.3.7

","boost":2},{"location":"release/#036","title":"0.3.6","text":"","boost":2},{"location":"release/#whats-changed_2","title":"What's Changed","text":"

Full Changelog: #0.3.5...0.3.6

","boost":2},{"location":"release/#035","title":"0.3.5","text":"","boost":2},{"location":"release/#whats-changed_3","title":"What's Changed","text":"

A large update by @Lancetnik in #1048

Provides with the ability to setup graceful_timeout to wait for consumed messages processed correctly before apllication shutdown - Broker(graceful_timeout=30.0) (waits up to 30 seconds)

Full Changelog: #0.3.4...0.3.5

","boost":2},{"location":"release/#034","title":"0.3.4","text":"","boost":2},{"location":"release/#whats-changed_4","title":"What's Changed","text":"","boost":2},{"location":"release/#features","title":"Features:","text":"","boost":2},{"location":"release/#documentation","title":"Documentation","text":"","boost":2},{"location":"release/#chore","title":"Chore","text":"

Full Changelog: #0.3.3...0.3.4

","boost":2},{"location":"release/#033","title":"0.3.3","text":"","boost":2},{"location":"release/#whats-changed_5","title":"What's Changed","text":"

Features:

Chores:

Full Changelog: #0.3.2...0.3.3

","boost":2},{"location":"release/#032","title":"0.3.2","text":"","boost":2},{"location":"release/#whats-changed_6","title":"What's Changed","text":"","boost":2},{"location":"release/#new-features","title":"New features:","text":"","boost":2},{"location":"release/#chore_1","title":"Chore:","text":"

Full Changelog: #0.3.1...0.3.2

","boost":2},{"location":"release/#031","title":"0.3.1","text":"","boost":2},{"location":"release/#whats-changed_7","title":"What's Changed","text":"

Features:

Bug fixes:

Documentation:

","boost":2},{"location":"release/#new-contributors","title":"New Contributors","text":"

Full Changelog: #0.3.0...0.3.1

","boost":2},{"location":"release/#030","title":"0.3.0","text":"","boost":2},{"location":"release/#whats-changed_8","title":"What's Changed","text":"

The main feature of the 0.3.0 release is added Redis support by @Lancetnik in #1003

You can install it by the following command:

pip install \"faststream[redis]\"\n

Here is a little code example

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n@broker.subscriber(\n    channel=\"test\",  # or\n    # list=\"test\",     or\n    # stream=\"test\",\n)\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":2},{"location":"release/#other-features","title":"Other features","text":"","boost":2},{"location":"release/#testing","title":"Testing","text":"","boost":2},{"location":"release/#documentation_1","title":"Documentation","text":"","boost":2},{"location":"release/#chore_2","title":"Chore","text":"","boost":2},{"location":"release/#new-contributors_1","title":"New Contributors","text":"

Full Changelog: #0.2.15...0.3.0

","boost":2},{"location":"release/#030rc0","title":"0.3.0rc0","text":"","boost":2},{"location":"release/#whats-changed_9","title":"What's Changed","text":"

The main feature of the 0.3.x release is added Redis support by @Lancetnik in #1003

You can install it manually:

pip install faststream==0.3.0rc0 && pip install \"faststream[redis]\"\n
","boost":2},{"location":"release/#other-features_1","title":"Other features","text":"","boost":2},{"location":"release/#testing_1","title":"Testing","text":"","boost":2},{"location":"release/#documentation_2","title":"Documentation","text":"","boost":2},{"location":"release/#chore_3","title":"Chore","text":"","boost":2},{"location":"release/#new-contributors_2","title":"New Contributors","text":"

Full Changelog: #0.2.15...0.3.0rc0

","boost":2},{"location":"release/#0215","title":"0.2.15","text":"","boost":2},{"location":"release/#whats-changed_10","title":"What's Changed","text":"","boost":2},{"location":"release/#bug-fixes","title":"Bug fixes","text":"","boost":2},{"location":"release/#documentation_3","title":"Documentation","text":"","boost":2},{"location":"release/#misc","title":"Misc","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.14...0.2.15

","boost":2},{"location":"release/#0214","title":"0.2.14","text":"","boost":2},{"location":"release/#whats-changed_11","title":"What's Changed","text":"","boost":2},{"location":"release/#bug-fixes_1","title":"Bug fixes","text":"","boost":2},{"location":"release/#documentation_4","title":"Documentation","text":"","boost":2},{"location":"release/#misc_1","title":"Misc","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.13...0.2.14

","boost":2},{"location":"release/#0213","title":"0.2.13","text":"","boost":2},{"location":"release/#whats-changed_12","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.12...0.2.13

","boost":2},{"location":"release/#0212","title":"0.2.12","text":"","boost":2},{"location":"release/#whats-changed_13","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.11...0.2.12

","boost":2},{"location":"release/#0211","title":"0.2.11","text":"","boost":2},{"location":"release/#whats-changed_14","title":"What's Changed","text":"","boost":2},{"location":"release/#bug-fixes_2","title":"Bug fixes","text":"","boost":2},{"location":"release/#documentation_5","title":"Documentation","text":"","boost":2},{"location":"release/#new-contributors_3","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.10...0.2.11

","boost":2},{"location":"release/#documentation_6","title":"Documentation","text":"","boost":2},{"location":"release/#new-contributors_4","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.10...0.2.11

","boost":2},{"location":"release/#0210","title":"0.2.10","text":"","boost":2},{"location":"release/#whats-changed_15","title":"What's Changed","text":"

Now, you can hide your connection secrets in the AsyncAPI schema by manually setting up the server URL:

broker = RabbitBroker(\n    \"amqp://guest:guest@localhost:5672/\",  # Connection URL\n    asyncapi_url=\"amqp://****:****@localhost:5672/\",  # Public schema URL\n)\n

Additionally, the RabbitMQ AsyncAPI schema has been improved, adding support for faststream.security, and the connection scheme is now defined automatically.

RabbitMQ connection parameters are now merged, allowing you to define the main connection data as a URL string and customize it using kwargs:

broker = RabbitBroker(\n    \"amqp://guest:guest@localhost:5672/\",\n    host=\"127.0.0.1\",\n)\n\n# amqp://guest:guest@127.0.0.1:5672/ - The final URL\n
* A more suitable faststream.security import instead of faststream.broker.security * chore: add release notes for 0.2.9 by @kumaranvpl in https://github.com/airtai/faststream/pull/894 * chore: upgrade packages by @davorrunje in https://github.com/airtai/faststream/pull/901 * chore: use js redirect and redirect to version by @kumaranvpl in https://github.com/airtai/faststream/pull/902 * feat: add asyncapi_url broker arg by @Lancetnik in https://github.com/airtai/faststream/pull/903

Full Changelog: https://github.com/airtai/faststream/compare/0.2.9...0.2.10

","boost":2},{"location":"release/#029","title":"0.2.9","text":"","boost":2},{"location":"release/#whats-changed_16","title":"What's Changed","text":"","boost":2},{"location":"release/#new-contributors_5","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.8...0.2.9

","boost":2},{"location":"release/#028","title":"0.2.8","text":"","boost":2},{"location":"release/#whats-changed_17","title":"What's Changed","text":"","boost":2},{"location":"release/#new-contributors_6","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.7...0.2.8

","boost":2},{"location":"release/#027","title":"0.2.7","text":"","boost":2},{"location":"release/#whats-changed_18","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.6...0.2.7

","boost":2},{"location":"release/#026","title":"0.2.6","text":"","boost":2},{"location":"release/#whats-changed_19","title":"What's Changed","text":"","boost":2},{"location":"release/#new-contributors_7","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.5...0.2.6

","boost":2},{"location":"release/#025","title":"0.2.5","text":"","boost":2},{"location":"release/#whats-changed_20","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.4...0.2.5

","boost":2},{"location":"release/#024","title":"0.2.4","text":"","boost":2},{"location":"release/#new-functionalities","title":"New Functionalities","text":"

Now, Context provides access to inner dict keys too:

# headers is a `dict`\nasync def handler(\n  user_id: int = Context(\"message.headers.user_id\", cast=True),\n): ...\n

Added Header object as a shortcut to Context(\"message.headers.\") inner fields (NATS example):

# the same with the previous example\nasync def handler(\n  user_id: int = Header(),\n  u_id: int = Header(\"user_id\"),  # with custom name\n): ...\n

Added Path object to get access to NATS wildcard subject or RabbitMQ topic routing key (a shortcut to access Context(\"message.path.\") as well):

@nats_broker.subscriber(\"logs.{level}\")\nasync def handler(\n  level: str = Path(),\n)\n

Also, the original message Context annotation was copied from faststream.[broker].annotations.[Broker]Message to faststream.[broker].[Broker]Message to provide you with faster access to the most commonly used object (NATS example).

","boost":2},{"location":"release/#whats-changed_21","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.3...0.2.4

","boost":2},{"location":"release/#023","title":"0.2.3","text":"","boost":2},{"location":"release/#whats-changed_22","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.2...0.2.3

","boost":2},{"location":"release/#022","title":"0.2.2","text":"","boost":2},{"location":"release/#whats-changed_23","title":"What's Changed","text":"","boost":2},{"location":"release/#new-contributors_8","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.1...0.2.2

","boost":2},{"location":"release/#021","title":"0.2.1","text":"","boost":2},{"location":"release/#whats-changed_24","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.0...0.2.1

","boost":2},{"location":"release/#020","title":"0.2.0","text":"","boost":2},{"location":"release/#whats-changed_25","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.1.6...0.2.0

","boost":2},{"location":"release/#016","title":"0.1.6","text":"","boost":2},{"location":"release/#whats-changed_26","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.1.5...0.1.6

","boost":2},{"location":"release/#014","title":"0.1.4","text":"","boost":2},{"location":"release/#whats-changed_27","title":"What's Changed","text":"","boost":2},{"location":"release/#new-contributors_9","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.1.3...0.1.4

","boost":2},{"location":"release/#013","title":"0.1.3","text":"","boost":2},{"location":"release/#whats-changed_28","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.1.1...0.1.3

","boost":2},{"location":"release/#011","title":"0.1.1","text":"","boost":2},{"location":"release/#whats-changed_29","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/commits/0.1.1

","boost":2},{"location":"release/#010","title":"0.1.0","text":"

FastStream is a new package based on the ideas and experiences gained from FastKafka and Propan. By joining our forces, we picked up the best from both packages and created the unified way to write services capable of processing streamed data regardless of the underlying protocol. We'll continue to maintain both packages, but new development will be in this project. If you are starting a new service, this package is the recommended way to do it.

","boost":2},{"location":"release/#features_1","title":"Features","text":"

FastStream simplifies the process of writing producers and consumers for message queues, handling all the parsing, networking and documentation generation automatically.

Making streaming microservices has never been easier. Designed with junior developers in mind, FastStream simplifies your work while keeping the door open for more advanced use-cases. Here's a look at the core features that make FastStream a go-to framework for modern, data-centric microservices.

That's FastStream in a nutshell\u2014easy, efficient, and powerful. Whether you're just starting with streaming microservices or looking to scale, FastStream has got you covered.

","boost":2},{"location":"scheduling/","title":"Tasks Scheduling","text":"

FastStream is a framework for asynchronous service development. It allows you to build disturbed event-based systems in an easy way. Tasks scheduling is a pretty often usecase in such systems.

Unfortunatelly, this functional conflicts with the original FastStream ideology and can't be implemented as a part of the framework. But, you can integrate scheduling in your FastStream application by using some extra dependencies. And we have some reciepts how to make it.

","boost":10},{"location":"scheduling/#taskiq-faststream","title":"Taskiq-FastStream","text":"

Taskiq is an asynchronous distributed task queue for python. This project takes inspiration from big projects such as Celery and Dramatiq.

As a Celery replacement, Taskiq should support tasks sheduling and delayied publishing, of course. And it does!

By the way, you can easely integrate FastStream with the Taskiq. It allows you to create cron or delayied tasks to publish messages and trigger some functions this way.

We have a helpful project to provide you with this feature - Taskiq-FastStream.

You can install it by the following command

pip install taskiq-faststream\n

It has two hepfull classes BrokerWrapper and AppWrapper to make your FastStream App and Broker objects taskiq-compatible.

Let's take a look at the code example.

At first, we should create a regular FastStream application.

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-topic\")\n@broker.publisher(\"out-topic\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-queue\")\n@broker.publisher(\"out-queue\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-subject\")\n@broker.publisher(\"out-subject\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-channel\")\n@broker.publisher(\"out-channel\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n
","boost":10},{"location":"scheduling/#broker-wrapper","title":"Broker Wrapper","text":"

Now, if you want to make it just working, we should wrap our Broker to special BrokerWrapper object:

from taskiq_faststream import BrokerWrapper\n\ntaskiq_broker = BrokerWrapper(broker)\n

It creates a taskiq-compatible object, that can be used as an object to create a regular taskiq scheduler.

KafkaRabbitMQNATSRedis
from taskiq_faststream import StreamScheduler\nfrom taskiq.schedule_sources import LabelScheduleSource\n\ntaskiq_broker.task(\n    message={\"user\": \"John\", \"user_id\": 1},\n    topic=\"in-topic\",\n    schedule=[{\n        \"cron\": \"* * * * *\",\n    }],\n)\n\nscheduler = StreamScheduler(\n    broker=taskiq_broker,\n    sources=[LabelScheduleSource(taskiq_broker)],\n)\n
from taskiq_faststream import StreamScheduler\nfrom taskiq.schedule_sources import LabelScheduleSource\n\ntaskiq_broker.task(\n    message={\"user\": \"John\", \"user_id\": 1},\n    queue=\"in-queue\",\n    schedule=[{\n        \"cron\": \"* * * * *\",\n    }],\n)\n\nscheduler = StreamScheduler(\n    broker=taskiq_broker,\n    sources=[LabelScheduleSource(taskiq_broker)],\n)\n
from taskiq_faststream import StreamScheduler\nfrom taskiq.schedule_sources import LabelScheduleSource\n\ntaskiq_broker.task(\n    message={\"user\": \"John\", \"user_id\": 1},\n    subject=\"in-subject\",\n    schedule=[{\n        \"cron\": \"* * * * *\",\n    }],\n)\n\nscheduler = StreamScheduler(\n    broker=taskiq_broker,\n    sources=[LabelScheduleSource(taskiq_broker)],\n)\n
from taskiq_faststream import StreamScheduler\nfrom taskiq.schedule_sources import LabelScheduleSource\n\ntaskiq_broker.task(\n    message={\"user\": \"John\", \"user_id\": 1},\n    channel=\"in-channel\",\n    schedule=[{\n        \"cron\": \"* * * * *\",\n    }],\n)\n\nscheduler = StreamScheduler(\n    broker=taskiq_broker,\n    sources=[LabelScheduleSource(taskiq_broker)],\n)\n

We patched the original TaskiqScheduler to support message generation callbacks, but its signature remains the same.

broker.task(...) has the same with the original broker.publish(...) signature and allows you to plan your publishing tasks usign the great taskiq schedule option (you can learn more about it here).

Finally, to run the scheduler, please use the taskiq CLI command:

taskiq scheduler module:scheduler\n
","boost":10},{"location":"scheduling/#application-wrapper","title":"Application Wrapper","text":"

If you don't wont to lost application AsyncAPI schema or/and lifespans, you can wrap not the broker, but application by itself using AppWrapper class.

from taskiq_faststream import AppWrapper\n\ntaskiq_broker = AppWrapper(app)\n

It allows you to use taskiq_broker the same way with the previous example, but saves all original FastStream features.

Tip

Creating a separated Scheduler service is a best way to make really disturbed and susteinable system. In this case, you can just create an empty FastStream broker and use Taskiq-FastStream integration to publish your messages (consuming by another services).

","boost":10},{"location":"scheduling/#generate-message-payload","title":"Generate message payload","text":"

Also, you able to determine message payload right before sending and do not use the final one. To make it, just replace message option from the final value to function (sync or async), that returns data to send:

async def collect_information_to_send():\n    return \"Message to send\"\n\ntaskiq_broker.task(\n    message=collect_information_to_send,\n    ...\n)\n

It allows you to collect some data from database, request an outer API, or use another ways to generate data to send right before sending.

More than, you can send not one, but multiple messages per one task using this feature. Just turn your message callback function to generator (sync or async) - and Taskiq-FastStream will iterates over your payload and publishes all of your messages!

async def collect_information_to_send():\n    \"\"\"Publish 10 messages per task call.\"\"\"\n    for i in range(10):\n        yield i\n\ntaskiq_broker.task(\n    message=collect_information_to_send,\n    ...\n)\n
","boost":10},{"location":"scheduling/#rocketry","title":"Rocketry","text":"

Also, you can integrate your FastStream application with any other libraries provides you with a scheduling functional.

As an example, you can use Rocketry:

import asyncio\n\nfrom rocketry import Rocketry\nfrom rocketry.args import Arg\n\nfrom faststream.nats import NatsBroker\n\napp = Rocketry(execution=\"async\")\n\nbroker = NatsBroker()      # regular broker\napp.params(broker=broker)\n\nasync def start_app():\n    async with broker:     # connect broker\n        await app.serve()  # run rocketry\n\n@app.task(\"every 1 second\", execution=\"async\")\nasync def publish(br: NatsBroker = Arg(\"broker\")):\n    await br.publish(\"Hi, Rocketry!\", \"test\")\n\nif __name__ == \"__main__\":\n    asyncio.run(start_app())\n
","boost":10},{"location":"api/","title":"Reference - Code API","text":"

Here's the reference or code API, the classes, functions, parameters, attributes, and all the FastAPI parts you can use in your applications.

If you want to learn FastStream you are much better off reading the FastStream Tutorial.

"},{"location":"api/faststream/BaseMiddleware/","title":"BaseMiddleware","text":"","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware","title":"faststream.BaseMiddleware","text":"
BaseMiddleware(msg: Any)\n

A base middleware class.

METHOD DESCRIPTION on_receive

Called when a message is received.

after_processed

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) -> Optional[bool]: Called after processing a message.

__aenter__

Called when entering a context.

__aexit__

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) -> Optional[bool]: Called when exiting a context.

on_consume

DecodedMessage) -> DecodedMessage: Called before consuming a message.

after_consume

Optional[Exception]) -> None: Called after consuming a message.

consume_scope

DecodedMessage) -> AsyncIterator[DecodedMessage]: Context manager for consuming a message.

on_publish

SendableMessage) -> SendableMessage: Called before publishing a message.

after_publish

Optional[Exception]) -> None: Asynchronous function to handle the after publish event.

Initialize the class.

PARAMETER DESCRIPTION msg

Any message to be stored.

TYPE: Any

Source code in faststream/broker/middlewares.py
def __init__(self, msg: Any) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        msg: Any message to be stored.\n    \"\"\"\n    self.msg = msg\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.msg","title":"msg instance-attribute","text":"
msg = msg\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.after_consume","title":"after_consume async","text":"
after_consume(err: Optional[Exception]) -> None\n

A function to handle the result of consuming a resource asynchronously.

PARAMETER DESCRIPTION err

Optional exception that occurred during consumption

RAISES DESCRIPTION err

If an exception occurred during consumption

Source code in faststream/broker/middlewares.py
async def after_consume(self, err: Optional[Exception]) -> None:\n    \"\"\"A function to handle the result of consuming a resource asynchronously.\n\n    Args:\n        err : Optional exception that occurred during consumption\n\n    Raises:\n        err : If an exception occurred during consumption\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.after_processed","title":"after_processed async","text":"
after_processed(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> Optional[bool]\n

Asynchronously called after processing.

PARAMETER DESCRIPTION exc_type

Optional exception type

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

Optional exception value

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

Optional traceback

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION Optional[bool]

Optional boolean value indicating whether the processing was successful or not.

Source code in faststream/broker/middlewares.py
async def after_processed(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> Optional[bool]:\n    \"\"\"Asynchronously called after processing.\n\n    Args:\n        exc_type: Optional exception type\n        exc_val: Optional exception value\n        exec_tb: Optional traceback\n\n    Returns:\n        Optional boolean value indicating whether the processing was successful or not.\n    \"\"\"\n    return False\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.after_publish","title":"after_publish async","text":"
after_publish(err: Optional[Exception]) -> None\n

Asynchronous function to handle the after publish event.

PARAMETER DESCRIPTION err

Optional exception that occurred during the publish

TYPE: Optional[Exception]

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION Exception

If an error occurred during the publish

Source code in faststream/broker/middlewares.py
async def after_publish(self, err: Optional[Exception]) -> None:\n    \"\"\"Asynchronous function to handle the after publish event.\n\n    Args:\n        err: Optional exception that occurred during the publish\n\n    Returns:\n        None\n\n    Raises:\n        Exception: If an error occurred during the publish\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.consume_scope","title":"consume_scope async","text":"
consume_scope(\n    msg: DecodedMessage,\n) -> AsyncIterator[DecodedMessage]\n

Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.

PARAMETER DESCRIPTION msg

The decoded message to consume.

TYPE: DecodedMessage

YIELDS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RETURNS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RAISES DESCRIPTION Exception

If an error occurs while consuming the message.

AsyncIterator

An asynchronous iterator that yields decoded messages.

Note

This function is an async function.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def consume_scope(self, msg: DecodedMessage) -> AsyncIterator[DecodedMessage]:\n    \"\"\"Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.\n\n    Args:\n        msg: The decoded message to consume.\n\n    Yields:\n        An asynchronous iterator of decoded messages.\n\n    Returns:\n        An asynchronous iterator of decoded messages.\n\n    Raises:\n        Exception: If an error occurs while consuming the message.\n\n    AsyncIterator:\n        An asynchronous iterator that yields decoded messages.\n\n    Note:\n        This function is an async function.\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_consume(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_consume(err)\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.on_consume","title":"on_consume async","text":"
on_consume(msg: DecodedMessage) -> DecodedMessage\n

Asynchronously consumes a message.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: DecodedMessage

RETURNS DESCRIPTION DecodedMessage

The consumed message.

Source code in faststream/broker/middlewares.py
async def on_consume(self, msg: DecodedMessage) -> DecodedMessage:\n    \"\"\"Asynchronously consumes a message.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The consumed message.\n    \"\"\"\n    return msg\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.on_publish","title":"on_publish async","text":"
on_publish(msg: SendableMessage) -> SendableMessage\n

Asynchronously handle a publish event.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

RETURNS DESCRIPTION SendableMessage

The published message.

Source code in faststream/broker/middlewares.py
async def on_publish(self, msg: SendableMessage) -> SendableMessage:\n    \"\"\"Asynchronously handle a publish event.\n\n    Args:\n        msg: The message to be published.\n\n    Returns:\n        The published message.\n    \"\"\"\n    return msg\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.on_receive","title":"on_receive async","text":"
on_receive() -> None\n
Source code in faststream/broker/middlewares.py
async def on_receive(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.publish_scope","title":"publish_scope async","text":"
publish_scope(\n    msg: SendableMessage,\n) -> AsyncIterator[SendableMessage]\n

Publish a message and return an async iterator.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

YIELDS DESCRIPTION AsyncIterator[SendableMessage]

A sendable message.

RETURNS DESCRIPTION AsyncIterator[SendableMessage]

An async iterator of sendable messages.

RAISES DESCRIPTION Exception

If an error occurs during publishing.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def publish_scope(\n    self, msg: SendableMessage\n) -> AsyncIterator[SendableMessage]:\n    \"\"\"Publish a message and return an async iterator.\n\n    Args:\n        msg: The message to be published.\n\n    Yields:\n        A sendable message.\n\n    Returns:\n        An async iterator of sendable messages.\n\n    Raises:\n        Exception: If an error occurs during publishing.\n\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_publish(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_publish(err)\n
","boost":0.5},{"location":"api/faststream/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/Context/#faststream.Context","title":"faststream.Context","text":"
Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n    )\n
","boost":0.5},{"location":"api/faststream/Depends/","title":"Depends","text":"","boost":0.5},{"location":"api/faststream/Depends/#fast_depends.use.Depends","title":"fast_depends.use.Depends","text":"
Depends(\n    dependency: Callable[P, T],\n    *,\n    use_cache: bool = True,\n    cast: bool = True\n) -> Any\n
Source code in fast_depends/use.py
def Depends(\n    dependency: Callable[P, T],\n    *,\n    use_cache: bool = True,\n    cast: bool = True,\n) -> Any:\n    return model.Depends(\n        dependency=dependency,\n        use_cache=use_cache,\n        cast=cast,\n    )\n
","boost":0.5},{"location":"api/faststream/FastStream/","title":"FastStream","text":"","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream","title":"faststream.FastStream","text":"
FastStream(\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    lifespan: Optional[Lifespan] = None,\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[\n        Union[License, LicenseDict, AnyDict]\n    ] = None,\n    contact: Optional[\n        Union[Contact, ContactDict, AnyDict]\n    ] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[\n        Sequence[Union[Tag, TagDict, AnyDict]]\n    ] = None,\n    external_docs: Optional[\n        Union[ExternalDocs, ExternalDocsDict, AnyDict]\n    ] = None,\n)\n

Bases: ABCApp

A class representing a FastStream application.

METHOD DESCRIPTION __init__

initializes the FastStream application

on_startup

adds a hook to run before the broker is connected

on_shutdown

adds a hook to run before the broker is disconnected

after_startup

adds a hook to run after the broker is connected

after_shutdown

adds a hook to run after the broker is disconnected

run

runs the FastStream application

_init_async_cycle

initializes the async cycle

_start

starts the FastStream application

_stop

stops the FastStream application

_startup

runs the startup hooks

_shutdown

runs the shutdown hooks

__exit

exits the FastStream application

Asyncronous FastStream Application class

stores and run broker, control hooks

PARAMETER DESCRIPTION broker

async broker to run (may be None, then specify by set_broker)

TYPE: Optional[BrokerAsyncUsecase[Any, Any]] DEFAULT: None

logger

logger object to log startup/shutdown messages (None to disable)

TYPE: Optional[Logger] DEFAULT: logger

title

application title - for AsyncAPI docs

TYPE: str DEFAULT: 'FastStream'

version

application version - for AsyncAPI docs

TYPE: str DEFAULT: '0.1.0'

description

application description - for AsyncAPI docs

TYPE: str DEFAULT: ''

Source code in faststream/app.py
def __init__(\n    self,\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    lifespan: Optional[Lifespan] = None,\n    # AsyncAPI args,\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[Union[License, LicenseDict, AnyDict]] = None,\n    contact: Optional[Union[Contact, ContactDict, AnyDict]] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[Sequence[Union[Tag, TagDict, AnyDict]]] = None,\n    external_docs: Optional[Union[ExternalDocs, ExternalDocsDict, AnyDict]] = None,\n) -> None:\n    \"\"\"Asyncronous FastStream Application class\n\n    stores and run broker, control hooks\n\n    Args:\n        broker: async broker to run (may be `None`, then specify by `set_broker`)\n        logger: logger object to log startup/shutdown messages (`None` to disable)\n        title: application title - for AsyncAPI docs\n        version: application version - for AsyncAPI docs\n        description: application description - for AsyncAPI docs\n    \"\"\"\n    super().__init__(\n        broker=broker,\n        logger=logger,\n        title=title,\n        version=version,\n        description=description,\n        terms_of_service=terms_of_service,\n        license=license,\n        contact=contact,\n        identifier=identifier,\n        tags=tags,\n        external_docs=external_docs,\n    )\n\n    self._stop_event = None\n\n    self.lifespan_context = (\n        apply_types(\n            func=lifespan,\n            wrap_model=drop_response_type,\n        )\n        if lifespan is not None\n        else fake_context\n    )\n\n    set_exit(lambda *_: self.__exit())\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = tags\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.contact","title":"contact instance-attribute","text":"
contact = contact\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.context","title":"context instance-attribute","text":"
context = context\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.external_docs","title":"external_docs instance-attribute","text":"
external_docs = external_docs\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.identifier","title":"identifier instance-attribute","text":"
identifier = identifier\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.license","title":"license instance-attribute","text":"
license = license\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context = (\n    apply_types(\n        func=lifespan, wrap_model=drop_response_type\n    )\n    if lifespan is not None\n    else fake_context\n)\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = terms_of_service\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.title","title":"title instance-attribute","text":"
title = title\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.version","title":"version instance-attribute","text":"
version = version\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.after_shutdown","title":"after_shutdown","text":"
after_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker disconnected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def after_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker disconnected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().after_shutdown(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.after_startup","title":"after_startup","text":"
after_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker connected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def after_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker connected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().after_startup(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.on_shutdown","title":"on_shutdown","text":"
on_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker disconnected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def on_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker disconnected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().on_shutdown(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.on_startup","title":"on_startup","text":"
on_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker connected

This hook also takes an extra CLI options as a kwargs

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def on_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker connected\n\n    This hook also takes an extra CLI options as a kwargs\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().on_startup(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.run","title":"run async","text":"
run(\n    log_level: int = logging.INFO,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n) -> None\n

Run FastStream Application

PARAMETER DESCRIPTION log_level

force application log level

TYPE: int DEFAULT: INFO

RETURNS DESCRIPTION None

Block an event loop until stopped

Source code in faststream/app.py
async def run(\n    self,\n    log_level: int = logging.INFO,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Run FastStream Application\n\n    Args:\n        log_level: force application log level\n\n    Returns:\n        Block an event loop until stopped\n    \"\"\"\n    assert self.broker, \"You should setup a broker\"  # nosec B101\n\n    self._init_async_cycle()\n    async with self.lifespan_context(**(run_extra_options or {})):\n        try:\n            async with anyio.create_task_group() as tg:\n                tg.start_soon(self._start, log_level, run_extra_options)\n                await self._stop(log_level)\n                tg.cancel_scope.cancel()\n        except ExceptionGroup as e:\n            for ex in e.exceptions:\n                raise ex from None\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.set_broker","title":"set_broker","text":"
set_broker(broker: BrokerAsyncUsecase[Any, Any]) -> None\n

Set already existed App object broker Usefull then you create/init broker in on_startup hook

Source code in faststream/app.py
def set_broker(self, broker: BrokerAsyncUsecase[Any, Any]) -> None:\n    \"\"\"Set already existed App object broker\n    Usefull then you create/init broker in `on_startup` hook\"\"\"\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/Header/","title":"Header","text":"","boost":0.5},{"location":"api/faststream/Header/#faststream.Header","title":"faststream.Header","text":"
Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.headers.\",\n    )\n
","boost":0.5},{"location":"api/faststream/Path/","title":"Path","text":"","boost":0.5},{"location":"api/faststream/Path/#faststream.Path","title":"faststream.Path","text":"
Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.path.\",\n    )\n
","boost":0.5},{"location":"api/faststream/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/TestApp/#faststream.TestApp","title":"faststream.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/TestApp/#faststream.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/apply_types/","title":"apply_types","text":"","boost":0.5},{"location":"api/faststream/apply_types/#fast_depends.use.inject","title":"fast_depends.use.inject","text":"
inject(\n    func: Optional[Callable[P, T]] = None,\n    *,\n    cast: bool = True,\n    extra_dependencies: Sequence[model.Depends] = (),\n    pydantic_config: Optional[ConfigDict] = None,\n    dependency_overrides_provider: Optional[\n        Any\n    ] = dependency_provider,\n    wrap_model: Callable[\n        [CallModel[P, T]], CallModel[P, T]\n    ] = lambda: x\n) -> Union[Callable[P, T], _InjectWrapper[P, T]]\n
Source code in fast_depends/use.py
def inject(\n    func: Optional[Callable[P, T]] = None,\n    *,\n    cast: bool = True,\n    extra_dependencies: Sequence[model.Depends] = (),\n    pydantic_config: Optional[ConfigDict] = None,\n    dependency_overrides_provider: Optional[Any] = dependency_provider,\n    wrap_model: Callable[[CallModel[P, T]], CallModel[P, T]] = lambda x: x,\n) -> Union[Callable[P, T], _InjectWrapper[P, T],]:\n    decorator = _wrap_inject(\n        dependency_overrides_provider=dependency_overrides_provider,\n        wrap_model=wrap_model,\n        extra_dependencies=extra_dependencies,\n        cast=cast,\n        pydantic_config=pydantic_config,\n    )\n\n    if func is None:\n        return decorator\n\n    else:\n        return decorator(func)\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/","title":"ABCApp","text":"","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp","title":"faststream.app.ABCApp","text":"
ABCApp(\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[\n        Union[License, LicenseDict, AnyDict]\n    ] = None,\n    contact: Optional[\n        Union[Contact, ContactDict, AnyDict]\n    ] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[\n        Sequence[Union[Tag, TagDict, AnyDict]]\n    ] = None,\n    external_docs: Optional[\n        Union[ExternalDocs, ExternalDocsDict, AnyDict]\n    ] = None,\n)\n

Bases: ABC

A class representing an ABC App.

METHOD DESCRIPTION set_broker

Set the broker object

on_startup

Add a hook to be run before the broker is connected

on_shutdown

Add a hook to be run before the broker is disconnected

after_startup

Add a hook to be run after the broker is connected

after_shutdown

Add a hook to be run after the broker is disconnected

_log

Log a message at a specified

Initialize an instance of the class.

PARAMETER DESCRIPTION broker

An optional instance of the BrokerAsyncUsecase class.

TYPE: Optional[BrokerAsyncUsecase[Any, Any]] DEFAULT: None

logger

An optional instance of the logging.Logger class.

TYPE: Optional[Logger] DEFAULT: logger

title

A string representing the title of the AsyncAPI.

TYPE: str DEFAULT: 'FastStream'

version

A string representing the version of the AsyncAPI.

TYPE: str DEFAULT: '0.1.0'

description

A string representing the description of the AsyncAPI.

TYPE: str DEFAULT: ''

terms_of_service

An optional URL representing the terms of service of the AsyncAPI.

TYPE: Optional[AnyHttpUrl] DEFAULT: None

license

An optional instance of the License class.

TYPE: Optional[Union[License, LicenseDict, AnyDict]] DEFAULT: None

contact

An optional instance of the Contact class.

TYPE: Optional[Union[Contact, ContactDict, AnyDict]] DEFAULT: None

identifier

An optional string representing the identifier of the AsyncAPI.

TYPE: Optional[str] DEFAULT: None

tags

An optional sequence of Tag instances.

TYPE: Optional[Sequence[Union[Tag, TagDict, AnyDict]]] DEFAULT: None

external_docs

An optional instance of the ExternalDocs class.

TYPE: Optional[Union[ExternalDocs, ExternalDocsDict, AnyDict]] DEFAULT: None

Source code in faststream/app.py
def __init__(\n    self,\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    # AsyncAPI information\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[Union[License, LicenseDict, AnyDict]] = None,\n    contact: Optional[Union[Contact, ContactDict, AnyDict]] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[Sequence[Union[Tag, TagDict, AnyDict]]] = None,\n    external_docs: Optional[Union[ExternalDocs, ExternalDocsDict, AnyDict]] = None,\n) -> None:\n    \"\"\"Initialize an instance of the class.\n\n    Args:\n        broker: An optional instance of the BrokerAsyncUsecase class.\n        logger: An optional instance of the logging.Logger class.\n        title: A string representing the title of the AsyncAPI.\n        version: A string representing the version of the AsyncAPI.\n        description: A string representing the description of the AsyncAPI.\n        terms_of_service: An optional URL representing the terms of service of the AsyncAPI.\n        license: An optional instance of the License class.\n        contact: An optional instance of the Contact class.\n        identifier: An optional string representing the identifier of the AsyncAPI.\n        tags: An optional sequence of Tag instances.\n        external_docs: An optional instance of the ExternalDocs class.\n    \"\"\"\n    self.broker = broker\n    self.logger = logger\n    self.context = context\n    context.set_global(\"app\", self)\n\n    self._on_startup_calling = []\n    self._after_startup_calling = []\n    self._on_shutdown_calling = []\n    self._after_shutdown_calling = []\n\n    # AsyncAPI information\n    self.title = title\n    self.version = version\n    self.description = description\n    self.terms_of_service = terms_of_service\n    self.license = license\n    self.contact = contact\n    self.identifier = identifier\n    self.asyncapi_tags = tags\n    self.external_docs = external_docs\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = tags\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.contact","title":"contact instance-attribute","text":"
contact = contact\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.context","title":"context instance-attribute","text":"
context = context\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.external_docs","title":"external_docs instance-attribute","text":"
external_docs = external_docs\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.identifier","title":"identifier instance-attribute","text":"
identifier = identifier\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.license","title":"license instance-attribute","text":"
license = license\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = terms_of_service\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.title","title":"title instance-attribute","text":"
title = title\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.version","title":"version instance-attribute","text":"
version = version\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.after_shutdown","title":"after_shutdown","text":"
after_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker disconnected

Source code in faststream/app.py
def after_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker disconnected\"\"\"\n    self._after_shutdown_calling.append(apply_types(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.after_startup","title":"after_startup","text":"
after_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker connected

Source code in faststream/app.py
def after_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker connected\"\"\"\n    self._after_startup_calling.append(apply_types(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.on_shutdown","title":"on_shutdown","text":"
on_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker disconnected

Source code in faststream/app.py
def on_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker disconnected\"\"\"\n    self._on_shutdown_calling.append(apply_types(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.on_startup","title":"on_startup","text":"
on_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker connected This hook also takes an extra CLI options as a kwargs

Source code in faststream/app.py
def on_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker connected\n    This hook also takes an extra CLI options as a kwargs\"\"\"\n    self._on_startup_calling.append(apply_types(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.set_broker","title":"set_broker","text":"
set_broker(broker: BrokerAsyncUsecase[Any, Any]) -> None\n

Set already existed App object broker Usefull then you create/init broker in on_startup hook

Source code in faststream/app.py
def set_broker(self, broker: BrokerAsyncUsecase[Any, Any]) -> None:\n    \"\"\"Set already existed App object broker\n    Usefull then you create/init broker in `on_startup` hook\"\"\"\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/app/FastStream/","title":"FastStream","text":"","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream","title":"faststream.app.FastStream","text":"
FastStream(\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    lifespan: Optional[Lifespan] = None,\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[\n        Union[License, LicenseDict, AnyDict]\n    ] = None,\n    contact: Optional[\n        Union[Contact, ContactDict, AnyDict]\n    ] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[\n        Sequence[Union[Tag, TagDict, AnyDict]]\n    ] = None,\n    external_docs: Optional[\n        Union[ExternalDocs, ExternalDocsDict, AnyDict]\n    ] = None,\n)\n

Bases: ABCApp

A class representing a FastStream application.

METHOD DESCRIPTION __init__

initializes the FastStream application

on_startup

adds a hook to run before the broker is connected

on_shutdown

adds a hook to run before the broker is disconnected

after_startup

adds a hook to run after the broker is connected

after_shutdown

adds a hook to run after the broker is disconnected

run

runs the FastStream application

_init_async_cycle

initializes the async cycle

_start

starts the FastStream application

_stop

stops the FastStream application

_startup

runs the startup hooks

_shutdown

runs the shutdown hooks

__exit

exits the FastStream application

Asyncronous FastStream Application class

stores and run broker, control hooks

PARAMETER DESCRIPTION broker

async broker to run (may be None, then specify by set_broker)

TYPE: Optional[BrokerAsyncUsecase[Any, Any]] DEFAULT: None

logger

logger object to log startup/shutdown messages (None to disable)

TYPE: Optional[Logger] DEFAULT: logger

title

application title - for AsyncAPI docs

TYPE: str DEFAULT: 'FastStream'

version

application version - for AsyncAPI docs

TYPE: str DEFAULT: '0.1.0'

description

application description - for AsyncAPI docs

TYPE: str DEFAULT: ''

Source code in faststream/app.py
def __init__(\n    self,\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    lifespan: Optional[Lifespan] = None,\n    # AsyncAPI args,\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[Union[License, LicenseDict, AnyDict]] = None,\n    contact: Optional[Union[Contact, ContactDict, AnyDict]] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[Sequence[Union[Tag, TagDict, AnyDict]]] = None,\n    external_docs: Optional[Union[ExternalDocs, ExternalDocsDict, AnyDict]] = None,\n) -> None:\n    \"\"\"Asyncronous FastStream Application class\n\n    stores and run broker, control hooks\n\n    Args:\n        broker: async broker to run (may be `None`, then specify by `set_broker`)\n        logger: logger object to log startup/shutdown messages (`None` to disable)\n        title: application title - for AsyncAPI docs\n        version: application version - for AsyncAPI docs\n        description: application description - for AsyncAPI docs\n    \"\"\"\n    super().__init__(\n        broker=broker,\n        logger=logger,\n        title=title,\n        version=version,\n        description=description,\n        terms_of_service=terms_of_service,\n        license=license,\n        contact=contact,\n        identifier=identifier,\n        tags=tags,\n        external_docs=external_docs,\n    )\n\n    self._stop_event = None\n\n    self.lifespan_context = (\n        apply_types(\n            func=lifespan,\n            wrap_model=drop_response_type,\n        )\n        if lifespan is not None\n        else fake_context\n    )\n\n    set_exit(lambda *_: self.__exit())\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = tags\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.contact","title":"contact instance-attribute","text":"
contact = contact\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.context","title":"context instance-attribute","text":"
context = context\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.external_docs","title":"external_docs instance-attribute","text":"
external_docs = external_docs\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.identifier","title":"identifier instance-attribute","text":"
identifier = identifier\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.license","title":"license instance-attribute","text":"
license = license\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context = (\n    apply_types(\n        func=lifespan, wrap_model=drop_response_type\n    )\n    if lifespan is not None\n    else fake_context\n)\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = terms_of_service\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.title","title":"title instance-attribute","text":"
title = title\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.version","title":"version instance-attribute","text":"
version = version\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.after_shutdown","title":"after_shutdown","text":"
after_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker disconnected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def after_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker disconnected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().after_shutdown(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.after_startup","title":"after_startup","text":"
after_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker connected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def after_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker connected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().after_startup(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.on_shutdown","title":"on_shutdown","text":"
on_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker disconnected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def on_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker disconnected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().on_shutdown(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.on_startup","title":"on_startup","text":"
on_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker connected

This hook also takes an extra CLI options as a kwargs

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def on_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker connected\n\n    This hook also takes an extra CLI options as a kwargs\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().on_startup(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.run","title":"run async","text":"
run(\n    log_level: int = logging.INFO,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n) -> None\n

Run FastStream Application

PARAMETER DESCRIPTION log_level

force application log level

TYPE: int DEFAULT: INFO

RETURNS DESCRIPTION None

Block an event loop until stopped

Source code in faststream/app.py
async def run(\n    self,\n    log_level: int = logging.INFO,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Run FastStream Application\n\n    Args:\n        log_level: force application log level\n\n    Returns:\n        Block an event loop until stopped\n    \"\"\"\n    assert self.broker, \"You should setup a broker\"  # nosec B101\n\n    self._init_async_cycle()\n    async with self.lifespan_context(**(run_extra_options or {})):\n        try:\n            async with anyio.create_task_group() as tg:\n                tg.start_soon(self._start, log_level, run_extra_options)\n                await self._stop(log_level)\n                tg.cancel_scope.cancel()\n        except ExceptionGroup as e:\n            for ex in e.exceptions:\n                raise ex from None\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.set_broker","title":"set_broker","text":"
set_broker(broker: BrokerAsyncUsecase[Any, Any]) -> None\n

Set already existed App object broker Usefull then you create/init broker in on_startup hook

Source code in faststream/app.py
def set_broker(self, broker: BrokerAsyncUsecase[Any, Any]) -> None:\n    \"\"\"Set already existed App object broker\n    Usefull then you create/init broker in `on_startup` hook\"\"\"\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/asyncapi/get_asyncapi_html/","title":"get_asyncapi_html","text":"","boost":0.5},{"location":"api/faststream/asyncapi/get_asyncapi_html/#faststream.asyncapi.get_asyncapi_html","title":"faststream.asyncapi.get_asyncapi_html","text":"
get_asyncapi_html(\n    schema: Schema,\n    sidebar: bool = True,\n    info: bool = True,\n    servers: bool = True,\n    operations: bool = True,\n    messages: bool = True,\n    schemas: bool = True,\n    errors: bool = True,\n    expand_message_examples: bool = True,\n    title: str = \"FastStream\",\n) -> str\n

Generate HTML for displaying an AsyncAPI document.

PARAMETER DESCRIPTION schema

The AsyncAPI schema object.

TYPE: Schema

sidebar

Whether to show the sidebar. Defaults to True.

TYPE: bool DEFAULT: True

info

Whether to show the info section. Defaults to True.

TYPE: bool DEFAULT: True

servers

Whether to show the servers section. Defaults to True.

TYPE: bool DEFAULT: True

operations

Whether to show the operations section. Defaults to True.

TYPE: bool DEFAULT: True

messages

Whether to show the messages section. Defaults to True.

TYPE: bool DEFAULT: True

schemas

Whether to show the schemas section. Defaults to True.

TYPE: bool DEFAULT: True

errors

Whether to show the errors section. Defaults to True.

TYPE: bool DEFAULT: True

expand_message_examples

Whether to expand message examples. Defaults to True.

TYPE: bool DEFAULT: True

title

The title of the HTML document. Defaults to \"FastStream\".

TYPE: str DEFAULT: 'FastStream'

RETURNS DESCRIPTION str

The generated HTML document.

TYPE: str

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/asyncapi/site.py
def get_asyncapi_html(\n    schema: \"Schema\",\n    sidebar: bool = True,\n    info: bool = True,\n    servers: bool = True,\n    operations: bool = True,\n    messages: bool = True,\n    schemas: bool = True,\n    errors: bool = True,\n    expand_message_examples: bool = True,\n    title: str = \"FastStream\",\n) -> str:\n    \"\"\"Generate HTML for displaying an AsyncAPI document.\n\n    Args:\n        schema (Schema): The AsyncAPI schema object.\n        sidebar (bool, optional): Whether to show the sidebar. Defaults to True.\n        info (bool, optional): Whether to show the info section. Defaults to True.\n        servers (bool, optional): Whether to show the servers section. Defaults to True.\n        operations (bool, optional): Whether to show the operations section. Defaults to True.\n        messages (bool, optional): Whether to show the messages section. Defaults to True.\n        schemas (bool, optional): Whether to show the schemas section. Defaults to True.\n        errors (bool, optional): Whether to show the errors section. Defaults to True.\n        expand_message_examples (bool, optional): Whether to expand message examples. Defaults to True.\n        title (str, optional): The title of the HTML document. Defaults to \"FastStream\".\n\n    Returns:\n        str: The generated HTML document.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    schema_json = schema.to_json()\n\n    config = {\n        \"schema\": schema_json,\n        \"config\": {\n            \"show\": {\n                \"sidebar\": sidebar,\n                \"info\": info,\n                \"servers\": servers,\n                \"operations\": operations,\n                \"messages\": messages,\n                \"schemas\": schemas,\n                \"errors\": errors,\n            },\n            \"expand\": {\n                \"messageExamples\": expand_message_examples,\n            },\n            \"sidebar\": {\n                \"showServers\": \"byDefault\",\n                \"showOperations\": \"byDefault\",\n            },\n        },\n    }\n\n    return (\n        \"\"\"\n    <!DOCTYPE html>\n    <html>\n        <head>\n    \"\"\"\n        f\"\"\"\n        <title>{title} AsyncAPI</title>\n    \"\"\"\n        \"\"\"\n        <link rel=\"icon\" href=\"https://www.asyncapi.com/favicon.ico\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"https://www.asyncapi.com/favicon-16x16.png\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"https://www.asyncapi.com/favicon-32x32.png\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"194x194\" href=\"https://www.asyncapi.com/favicon-194x194.png\">\n        <link rel=\"stylesheet\" href=\"https://unpkg.com/@asyncapi/react-component@1.0.0-next.46/styles/default.min.css\">\n        </head>\n\n        <style>\n        html {\n            font-family: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;\n            line-height: 1.5;\n        }\n        </style>\n\n        <body>\n        <div id=\"asyncapi\"></div>\n\n        <script src=\"https://unpkg.com/@asyncapi/react-component@1.0.0-next.47/browser/standalone/index.js\"></script>\n        <script>\n    \"\"\"\n        f\"\"\"\n            AsyncApiStandalone.render({json.dumps(config)}, document.getElementById('asyncapi'));\n    \"\"\"\n        \"\"\"\n        </script>\n        </body>\n    </html>\n    \"\"\"\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/base/AsyncAPIOperation/","title":"AsyncAPIOperation","text":"","boost":0.5},{"location":"api/faststream/asyncapi/base/AsyncAPIOperation/#faststream.asyncapi.base.AsyncAPIOperation","title":"faststream.asyncapi.base.AsyncAPIOperation dataclass","text":"

A class representing an asynchronous API operation.

METHOD DESCRIPTION schema

returns the schema of the API operation as a dictionary of channel names and channel objects

","boost":0.5},{"location":"api/faststream/asyncapi/base/AsyncAPIOperation/#faststream.asyncapi.base.AsyncAPIOperation.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/asyncapi/base/AsyncAPIOperation/#faststream.asyncapi.base.AsyncAPIOperation.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/asyncapi/base/AsyncAPIOperation/#faststream.asyncapi.base.AsyncAPIOperation.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_broker_channels/","title":"get_app_broker_channels","text":"","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_broker_channels/#faststream.asyncapi.generate.get_app_broker_channels","title":"faststream.asyncapi.generate.get_app_broker_channels","text":"
get_app_broker_channels(\n    app: Union[FastStream, StreamRouter[Any]]\n) -> Dict[str, Channel]\n

Get the broker channels for an application.

PARAMETER DESCRIPTION app

An instance of FastStream or StreamRouter.

TYPE: Union[FastStream, StreamRouter[Any]]

RETURNS DESCRIPTION Dict[str, Channel]

A dictionary of channel names and their corresponding Channel objects.

RAISES DESCRIPTION AssertionError

If the app does not have a broker.

Source code in faststream/asyncapi/generate.py
def get_app_broker_channels(\n    app: Union[FastStream, \"StreamRouter[Any]\"]\n) -> Dict[str, Channel]:\n    \"\"\"Get the broker channels for an application.\n\n    Args:\n        app: An instance of FastStream or StreamRouter.\n\n    Returns:\n        A dictionary of channel names and their corresponding Channel objects.\n\n    Raises:\n        AssertionError: If the app does not have a broker.\n\n    \"\"\"\n    channels = {}\n    assert app.broker  # nosec B101\n\n    for h in app.broker.handlers.values():\n        channels.update(h.schema())\n\n    for p in app.broker._publishers.values():\n        channels.update(p.schema())\n\n    return channels\n
","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_broker_server/","title":"get_app_broker_server","text":"","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_broker_server/#faststream.asyncapi.generate.get_app_broker_server","title":"faststream.asyncapi.generate.get_app_broker_server","text":"
get_app_broker_server(\n    app: Union[FastStream, StreamRouter[Any]]\n) -> Dict[str, Server]\n

Get the broker server for an application.

PARAMETER DESCRIPTION app

An instance of FastStream or StreamRouter representing the application.

TYPE: Union[FastStream, StreamRouter[Any]]

RETURNS DESCRIPTION Dict[str, Server]

A dictionary containing the broker servers. The keys are the server names and the values are instances of Server class.

RAISES DESCRIPTION AssertionError

If the broker attribute of the app is not present.

Note

This function is currently incomplete and the following fields in the broker_meta dictionary are not populated: \"security\", \"variables\", \"bindings\".

Source code in faststream/asyncapi/generate.py
def get_app_broker_server(\n    app: Union[FastStream, \"StreamRouter[Any]\"]\n) -> Dict[str, Server]:\n    \"\"\"Get the broker server for an application.\n\n    Args:\n        app: An instance of `FastStream` or `StreamRouter` representing the application.\n\n    Returns:\n        A dictionary containing the broker servers. The keys are the server names and the values are instances of `Server` class.\n\n    Raises:\n        AssertionError: If the `broker` attribute of the app is not present.\n\n    Note:\n        This function is currently incomplete and the following fields in the `broker_meta` dictionary are not populated: \"security\", \"variables\", \"bindings\".\n\n    \"\"\"\n    servers = {}\n\n    broker = app.broker\n    assert broker  # nosec B101\n\n    broker_meta: Dict[str, Any] = {\n        \"protocol\": broker.protocol,\n        \"protocolVersion\": broker.protocol_version,\n        \"description\": broker.description,\n        \"tags\": broker.tags,\n        # TODO\n        # \"variables\": \"\",\n        # \"bindings\": \"\",\n    }\n\n    if broker.security is not None:\n        broker_meta[\"security\"] = broker.security.get_requirement()\n\n    if isinstance(broker.url, str):\n        servers[\"development\"] = Server(\n            url=broker.url,\n            **broker_meta,\n        )\n\n    elif len(broker.url) == 1:\n        servers[\"development\"] = Server(\n            url=broker.url[0],\n            **broker_meta,\n        )\n\n    else:\n        for i, url in enumerate(broker.url, 1):\n            servers[f\"Server{i}\"] = Server(\n                url=url,\n                **broker_meta,\n            )\n\n    return servers\n
","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_schema/","title":"get_app_schema","text":"","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_schema/#faststream.asyncapi.generate.get_app_schema","title":"faststream.asyncapi.generate.get_app_schema","text":"
get_app_schema(\n    app: Union[FastStream, StreamRouter[Any]]\n) -> Schema\n

Get the application schema.

PARAMETER DESCRIPTION app

An instance of FastStream or StreamRouter.

TYPE: Union[FastStream, StreamRouter[Any]]

RETURNS DESCRIPTION Schema

The schema object.

Source code in faststream/asyncapi/generate.py
def get_app_schema(app: Union[FastStream, \"StreamRouter[Any]\"]) -> Schema:\n    \"\"\"Get the application schema.\n\n    Args:\n        app: An instance of FastStream or StreamRouter.\n\n    Returns:\n        The schema object.\n\n    \"\"\"\n    servers = get_app_broker_server(app)\n    channels = get_app_broker_channels(app)\n\n    messages: Dict[str, Message] = {}\n    payloads: Dict[str, Dict[str, Any]] = {}\n    for channel_name, ch in channels.items():\n        ch.servers = list(servers.keys())\n\n        if ch.subscribe is not None:\n            m = ch.subscribe.message\n\n            if isinstance(m, Message):  # pragma: no branch\n                ch.subscribe.message = _resolve_msg_payloads(\n                    m,\n                    channel_name,\n                    payloads,\n                    messages,\n                )\n\n        if ch.publish is not None:\n            m = ch.publish.message\n\n            if isinstance(m, Message):  # pragma: no branch\n                ch.publish.message = _resolve_msg_payloads(\n                    m,\n                    channel_name,\n                    payloads,\n                    messages,\n                )\n\n    broker = app.broker\n    if broker is None:  # pragma: no cover\n        raise RuntimeError()\n\n    schema = Schema(\n        info=Info(\n            title=app.title,\n            version=app.version,\n            description=app.description,\n            termsOfService=app.terms_of_service,\n            contact=app.contact,\n            license=app.license,\n        ),\n        defaultContentType=ContentTypes.json.value,\n        id=app.identifier,\n        tags=list(app.asyncapi_tags) if app.asyncapi_tags else None,\n        externalDocs=app.external_docs,\n        servers=servers,\n        channels=channels,\n        components=Components(\n            messages=messages,\n            schemas=payloads,\n            securitySchemes=None\n            if broker.security is None\n            else broker.security.get_schema(),\n        ),\n    )\n    return schema\n
","boost":0.5},{"location":"api/faststream/asyncapi/message/get_model_schema/","title":"get_model_schema","text":"","boost":0.5},{"location":"api/faststream/asyncapi/message/get_model_schema/#faststream.asyncapi.message.get_model_schema","title":"faststream.asyncapi.message.get_model_schema","text":"
get_model_schema(\n    call: Optional[Type[BaseModel]],\n    prefix: str = \"\",\n    exclude: Sequence[str] = (),\n) -> Optional[Dict[str, Any]]\n

Get the schema of a model.

PARAMETER DESCRIPTION call

The model class to get the schema for.

TYPE: Optional[Type[BaseModel]]

prefix

A prefix to add to the schema title.

TYPE: str DEFAULT: ''

exclude

A sequence of field names to exclude from the schema.

TYPE: Sequence[str] DEFAULT: ()

RETURNS DESCRIPTION Optional[Dict[str, Any]]

The schema of the model as a dictionary, or None if the model has no fields.

RAISES DESCRIPTION NotImplementedError

If the model is a silent animal.

Source code in faststream/asyncapi/message.py
def get_model_schema(\n    call: Optional[Type[BaseModel]],\n    prefix: str = \"\",\n    exclude: Sequence[str] = (),\n) -> Optional[Dict[str, Any]]:\n    \"\"\"Get the schema of a model.\n\n    Args:\n        call: The model class to get the schema for.\n        prefix: A prefix to add to the schema title.\n        exclude: A sequence of field names to exclude from the schema.\n\n    Returns:\n        The schema of the model as a dictionary, or None if the model has no fields.\n\n    Raises:\n        NotImplementedError: If the model is a silent animal.\n\n    \"\"\"\n    if call is None:\n        return None\n\n    params = {k: v for k, v in get_model_fields(call).items() if k not in exclude}\n    params_number = len(params)\n\n    if params_number == 0:\n        return None\n\n    model = None\n    use_original_model = False\n    if params_number == 1:\n        name, param = tuple(params.items())[0]\n\n        if (\n            param.annotation\n            and isclass(param.annotation)\n            and issubclass(param.annotation, BaseModel)  # NOTE: 3.7-3.10 compatibility\n        ):\n            model = param.annotation\n            use_original_model = True\n\n    if model is None:\n        model = call\n\n    body: Dict[str, Any] = model_schema(model)\n    body[\"properties\"] = body.get(\"properties\", {})\n    for i in exclude:\n        body[\"properties\"].pop(i, None)\n    if required := body.get(\"required\"):\n        body[\"required\"] = list(filter(lambda x: x not in exclude, required))\n\n    if params_number == 1 and not use_original_model:\n        param_body: Dict[str, Any] = body.get(\"properties\", {})\n        param_body = param_body[name]\n\n        if PYDANTIC_V2:\n            original_title = param.title\n        else:\n            original_title = param.field_info.title  # type: ignore[attr-defined]\n\n        if original_title:\n            use_original_model = True\n            param_body[\"title\"] = original_title\n        else:\n            param_body[\"title\"] = name\n\n        body = param_body\n\n    if not use_original_model:\n        body[\"title\"] = f\"{prefix}:Payload\"\n\n    return body\n
","boost":0.5},{"location":"api/faststream/asyncapi/message/get_response_schema/","title":"get_response_schema","text":"","boost":0.5},{"location":"api/faststream/asyncapi/message/get_response_schema/#faststream.asyncapi.message.get_response_schema","title":"faststream.asyncapi.message.get_response_schema","text":"
get_response_schema(\n    call: Optional[CallModel[Any, Any]], prefix: str = \"\"\n) -> Optional[Dict[str, Any]]\n

Get the response schema for a given call.

PARAMETER DESCRIPTION call

The call model.

TYPE: Optional[CallModel[Any, Any]]

prefix

A prefix to add to the schema keys.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION Optional[Dict[str, Any]]

The response schema as a dictionary.

Source code in faststream/asyncapi/message.py
def get_response_schema(\n    call: Optional[CallModel[Any, Any]],\n    prefix: str = \"\",\n) -> Optional[Dict[str, Any]]:\n    \"\"\"Get the response schema for a given call.\n\n    Args:\n        call: The call model.\n        prefix: A prefix to add to the schema keys.\n\n    Returns:\n        The response schema as a dictionary.\n\n    \"\"\"\n    return get_model_schema(\n        getattr(\n            call, \"response_model\", None\n        ),  # NOTE: FastAPI Dependant object compatibility\n        prefix=prefix,\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/message/parse_handler_params/","title":"parse_handler_params","text":"","boost":0.5},{"location":"api/faststream/asyncapi/message/parse_handler_params/#faststream.asyncapi.message.parse_handler_params","title":"faststream.asyncapi.message.parse_handler_params","text":"
parse_handler_params(\n    call: CallModel[Any, Any], prefix: str = \"\"\n) -> Dict[str, Any]\n

Parses the handler parameters.

PARAMETER DESCRIPTION call

The call model.

TYPE: CallModel[Any, Any]

prefix

The prefix for the model schema.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION Dict[str, Any]

A dictionary containing the parsed parameters.

Source code in faststream/asyncapi/message.py
def parse_handler_params(call: CallModel[Any, Any], prefix: str = \"\") -> Dict[str, Any]:\n    \"\"\"Parses the handler parameters.\n\n    Args:\n        call: The call model.\n        prefix: The prefix for the model schema.\n\n    Returns:\n        A dictionary containing the parsed parameters.\n\n    \"\"\"\n    body = get_model_schema(\n        call.model,\n        prefix=prefix,\n        exclude=tuple(call.custom_fields.keys()),\n    )\n\n    if body is None:\n        return {\"title\": \"EmptyPayload\", \"type\": \"null\"}\n\n    return body\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/","title":"Channel","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel","title":"faststream.asyncapi.schema.Channel","text":"

Bases: BaseModel

A class to represent a channel.

Configurations

model_config : configuration for the model (only applicable for Pydantic version 2) Config : configuration for the class (only applicable for Pydantic version 1)

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.parameters","title":"parameters class-attribute instance-attribute","text":"
parameters: Optional[Parameter] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.publish","title":"publish class-attribute instance-attribute","text":"
publish: Optional[Operation] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.servers","title":"servers class-attribute instance-attribute","text":"
servers: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.subscribe","title":"subscribe class-attribute instance-attribute","text":"
subscribe: Optional[Operation] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding","title":"faststream.asyncapi.schema.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/","title":"Components","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components","title":"faststream.asyncapi.schema.Components","text":"

Bases: BaseModel

A class to represent components in a system.

Note

The following attributes are not implemented yet: - servers - serverVariables - channels - securitySchemes - parameters - correlationIds - operationTraits - messageTraits - serverBindings - channelBindings - operationBindings - messageBindings

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.messages","title":"messages class-attribute instance-attribute","text":"
messages: Optional[Dict[str, Message]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.schemas","title":"schemas class-attribute instance-attribute","text":"
schemas: Optional[Dict[str, Dict[str, Any]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.securitySchemes","title":"securitySchemes class-attribute instance-attribute","text":"
securitySchemes: Optional[Dict[str, Dict[str, Any]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/","title":"Contact","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact","title":"faststream.asyncapi.schema.Contact","text":"

Bases: BaseModel

A class to represent a contact.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.email","title":"email class-attribute instance-attribute","text":"
email: Optional[EmailStr] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.url","title":"url class-attribute instance-attribute","text":"
url: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ContactDict/","title":"ContactDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ContactDict/#faststream.asyncapi.schema.ContactDict","title":"faststream.asyncapi.schema.ContactDict","text":"

Bases: TypedDict

A class to represent a dictionary of contact information.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/ContactDict/#faststream.asyncapi.schema.ContactDict.email","title":"email instance-attribute","text":"
email: EmailStr\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ContactDict/#faststream.asyncapi.schema.ContactDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ContactDict/#faststream.asyncapi.schema.ContactDict.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/","title":"CorrelationId","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId","title":"faststream.asyncapi.schema.CorrelationId","text":"

Bases: BaseModel

A class to represent a correlation ID.

Configurations

extra : allows extra fields in the correlation ID model

","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId.location","title":"location instance-attribute","text":"
location: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/","title":"ExternalDocs","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs","title":"faststream.asyncapi.schema.ExternalDocs","text":"

Bases: BaseModel

A class to represent external documentation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocsDict/","title":"ExternalDocsDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocsDict/#faststream.asyncapi.schema.ExternalDocsDict","title":"faststream.asyncapi.schema.ExternalDocsDict","text":"

Bases: TypedDict

A dictionary type for representing external documentation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocsDict/#faststream.asyncapi.schema.ExternalDocsDict.description","title":"description instance-attribute","text":"
description: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocsDict/#faststream.asyncapi.schema.ExternalDocsDict.url","title":"url instance-attribute","text":"
url: Required[AnyHttpUrl]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/","title":"Info","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info","title":"faststream.asyncapi.schema.Info","text":"

Bases: BaseModel

A class to represent information.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.contact","title":"contact class-attribute instance-attribute","text":"
contact: Optional[\n    Union[Contact, ContactDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.description","title":"description class-attribute instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.license","title":"license class-attribute instance-attribute","text":"
license: Optional[\n    Union[License, LicenseDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.termsOfService","title":"termsOfService class-attribute instance-attribute","text":"
termsOfService: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.title","title":"title instance-attribute","text":"
title: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.version","title":"version class-attribute instance-attribute","text":"
version: str = '1.0.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/","title":"License","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License","title":"faststream.asyncapi.schema.License","text":"

Bases: BaseModel

A class to represent a license.

Config

extra : allow additional attributes in the model (PYDANTIC_V2)

","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License.url","title":"url class-attribute instance-attribute","text":"
url: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/LicenseDict/","title":"LicenseDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/LicenseDict/#faststream.asyncapi.schema.LicenseDict","title":"faststream.asyncapi.schema.LicenseDict","text":"

Bases: TypedDict

A dictionary-like class to represent a license.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/LicenseDict/#faststream.asyncapi.schema.LicenseDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/LicenseDict/#faststream.asyncapi.schema.LicenseDict.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/","title":"Message","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message","title":"faststream.asyncapi.schema.Message","text":"

Bases: BaseModel

A class to represent a message.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.contentType","title":"contentType class-attribute instance-attribute","text":"
contentType: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.correlationId","title":"correlationId class-attribute instance-attribute","text":"
correlationId: Optional[CorrelationId] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.messageId","title":"messageId class-attribute instance-attribute","text":"
messageId: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.payload","title":"payload instance-attribute","text":"
payload: Dict[str, Any]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.summary","title":"summary class-attribute instance-attribute","text":"
summary: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[List[Union[Tag, Dict[str, Any]]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/","title":"Operation","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation","title":"faststream.asyncapi.schema.Operation","text":"

Bases: BaseModel

A class to represent an operation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.message","title":"message instance-attribute","text":"
message: Union[Message, Reference]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.operationId","title":"operationId class-attribute instance-attribute","text":"
operationId: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.security","title":"security class-attribute instance-attribute","text":"
security: Optional[Dict[str, List[str]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.summary","title":"summary class-attribute instance-attribute","text":"
summary: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding","title":"faststream.asyncapi.schema.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Reference/","title":"Reference","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Reference/#faststream.asyncapi.schema.Reference","title":"faststream.asyncapi.schema.Reference","text":"

Bases: BaseModel

A class to represent a reference.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Reference/#faststream.asyncapi.schema.Reference.ref","title":"ref class-attribute instance-attribute","text":"
ref: str = Field(..., alias='$ref')\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/","title":"Schema","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema","title":"faststream.asyncapi.schema.Schema","text":"

Bases: BaseModel

A class to represent a schema.

METHOD DESCRIPTION to_jsonable

Convert the schema to a JSON-serializable object.

to_json

Convert the schema to a JSON string.

to_yaml

Convert the schema to a YAML string.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.asyncapi","title":"asyncapi class-attribute instance-attribute","text":"
asyncapi: str = ASYNC_API_VERSION\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.channels","title":"channels instance-attribute","text":"
channels: Dict[str, Channel]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.components","title":"components class-attribute instance-attribute","text":"
components: Optional[Components] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.defaultContentType","title":"defaultContentType class-attribute instance-attribute","text":"
defaultContentType: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.id","title":"id class-attribute instance-attribute","text":"
id: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.info","title":"info instance-attribute","text":"
info: Info\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.servers","title":"servers class-attribute instance-attribute","text":"
servers: Optional[Dict[str, Server]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.to_json","title":"to_json","text":"
to_json() -> str\n
Source code in faststream/asyncapi/schema/main.py
def to_json(self) -> str:\n    return model_to_json(\n        self,\n        by_alias=True,\n        exclude_none=True,\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.to_jsonable","title":"to_jsonable","text":"
to_jsonable() -> Any\n
Source code in faststream/asyncapi/schema/main.py
def to_jsonable(self) -> Any:\n    return model_to_jsonable(\n        self,\n        by_alias=True,\n        exclude_none=True,\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.to_yaml","title":"to_yaml","text":"
to_yaml() -> str\n
Source code in faststream/asyncapi/schema/main.py
def to_yaml(self) -> str:\n    from io import StringIO\n\n    import yaml\n\n    io = StringIO(initial_value=\"\", newline=\"\\n\")\n    yaml.dump(self.to_jsonable(), io, sort_keys=False)\n    return io.getvalue()\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/","title":"SecuritySchemaComponent","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent","title":"faststream.asyncapi.schema.SecuritySchemaComponent","text":"

Bases: BaseModel

A class to represent a security schema component.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.bearerFormat","title":"bearerFormat class-attribute instance-attribute","text":"
bearerFormat: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.flows","title":"flows class-attribute instance-attribute","text":"
flows: Optional[OauthFlows] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.in_","title":"in_ class-attribute instance-attribute","text":"
in_: Optional[str] = Field(default=None, alias='in')\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.openIdConnectUrl","title":"openIdConnectUrl class-attribute instance-attribute","text":"
openIdConnectUrl: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.schema_","title":"schema_ class-attribute instance-attribute","text":"
schema_: Optional[str] = Field(default=None, alias=\"schema\")\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.type","title":"type instance-attribute","text":"
type: Literal[\n    \"userPassword\",\n    \"apikey\",\n    \"X509\",\n    \"symmetricEncryption\",\n    \"asymmetricEncryption\",\n    \"httpApiKey\",\n    \"http\",\n    \"oauth2\",\n    \"openIdConnect\",\n    \"plain\",\n    \"scramSha256\",\n    \"scramSha512\",\n    \"gssapi\",\n]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/","title":"Server","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server","title":"faststream.asyncapi.schema.Server","text":"

Bases: BaseModel

A class to represent a server.

Note

The attributes description, protocolVersion, tags, security, variables, and bindings are all optional.

Configurations

If PYDANTIC_V2 is True, the model configuration is set to allow extra attributes. Otherwise, the Config class is defined with the extra attribute set to \"allow\".

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[Union[ServerBinding, Reference]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.protocol","title":"protocol instance-attribute","text":"
protocol: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.protocolVersion","title":"protocolVersion class-attribute instance-attribute","text":"
protocolVersion: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.security","title":"security class-attribute instance-attribute","text":"
security: Optional[SecurityRequirement] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.variables","title":"variables class-attribute instance-attribute","text":"
variables: Optional[\n    Dict[str, Union[ServerVariable, Reference]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding","title":"faststream.asyncapi.schema.ServerBinding","text":"

Bases: BaseModel

A class to represent server bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/","title":"Tag","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag","title":"faststream.asyncapi.schema.Tag","text":"

Bases: BaseModel

A class to represent a tag.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/TagDict/","title":"TagDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/TagDict/#faststream.asyncapi.schema.TagDict","title":"faststream.asyncapi.schema.TagDict","text":"

Bases: TypedDict

A dictionary-like class for storing tags.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/TagDict/#faststream.asyncapi.schema.TagDict.description","title":"description instance-attribute","text":"
description: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/TagDict/#faststream.asyncapi.schema.TagDict.externalDocs","title":"externalDocs instance-attribute","text":"
externalDocs: Union[ExternalDocs, ExternalDocsDict]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/TagDict/#faststream.asyncapi.schema.TagDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding","title":"faststream.asyncapi.schema.bindings.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding","title":"faststream.asyncapi.schema.bindings.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding","title":"faststream.asyncapi.schema.bindings.ServerBinding","text":"

Bases: BaseModel

A class to represent server bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/#faststream.asyncapi.schema.bindings.amqp.ChannelBinding","title":"faststream.asyncapi.schema.bindings.amqp.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/#faststream.asyncapi.schema.bindings.amqp.ChannelBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.2.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/#faststream.asyncapi.schema.bindings.amqp.ChannelBinding.exchange","title":"exchange class-attribute instance-attribute","text":"
exchange: Optional[Exchange] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/#faststream.asyncapi.schema.bindings.amqp.ChannelBinding.is_","title":"is_ class-attribute instance-attribute","text":"
is_: Literal[\"queue\", \"routingKey\"] = Field(..., alias=\"is\")\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/#faststream.asyncapi.schema.bindings.amqp.ChannelBinding.queue","title":"queue class-attribute instance-attribute","text":"
queue: Optional[Queue] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/","title":"Exchange","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange","title":"faststream.asyncapi.schema.bindings.amqp.Exchange","text":"

Bases: BaseModel

A class to represent an exchange.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange.autoDelete","title":"autoDelete class-attribute instance-attribute","text":"
autoDelete: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange.durable","title":"durable class-attribute instance-attribute","text":"
durable: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange.type","title":"type instance-attribute","text":"
type: Literal[\n    \"default\", \"direct\", \"topic\", \"fanout\", \"headers\"\n]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange.vhost","title":"vhost class-attribute instance-attribute","text":"
vhost: str = '/'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding","title":"faststream.asyncapi.schema.bindings.amqp.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.ack","title":"ack class-attribute instance-attribute","text":"
ack: bool = True\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.2.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.cc","title":"cc class-attribute instance-attribute","text":"
cc: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.deliveryMode","title":"deliveryMode class-attribute instance-attribute","text":"
deliveryMode: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.priority","title":"priority class-attribute instance-attribute","text":"
priority: Optional[PositiveInt] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.replyTo","title":"replyTo class-attribute instance-attribute","text":"
replyTo: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/","title":"Queue","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue","title":"faststream.asyncapi.schema.bindings.amqp.Queue","text":"

Bases: BaseModel

A class to represent a queue.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue.autoDelete","title":"autoDelete instance-attribute","text":"
autoDelete: bool\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue.durable","title":"durable instance-attribute","text":"
durable: bool\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue.exclusive","title":"exclusive instance-attribute","text":"
exclusive: bool\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue.vhost","title":"vhost class-attribute instance-attribute","text":"
vhost: str = '/'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ServerBinding/#faststream.asyncapi.schema.bindings.amqp.ServerBinding","title":"faststream.asyncapi.schema.bindings.amqp.ServerBinding","text":"

Bases: BaseModel

A class to represent a server binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ServerBinding/#faststream.asyncapi.schema.bindings.amqp.ServerBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.2.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/#faststream.asyncapi.schema.bindings.kafka.ChannelBinding","title":"faststream.asyncapi.schema.bindings.kafka.ChannelBinding","text":"

Bases: BaseModel

A class to represent a channel binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/#faststream.asyncapi.schema.bindings.kafka.ChannelBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.4.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/#faststream.asyncapi.schema.bindings.kafka.ChannelBinding.partitions","title":"partitions class-attribute instance-attribute","text":"
partitions: Optional[PositiveInt] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/#faststream.asyncapi.schema.bindings.kafka.ChannelBinding.replicas","title":"replicas class-attribute instance-attribute","text":"
replicas: Optional[PositiveInt] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/#faststream.asyncapi.schema.bindings.kafka.ChannelBinding.topic","title":"topic class-attribute instance-attribute","text":"
topic: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/#faststream.asyncapi.schema.bindings.kafka.OperationBinding","title":"faststream.asyncapi.schema.bindings.kafka.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/#faststream.asyncapi.schema.bindings.kafka.OperationBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.4.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/#faststream.asyncapi.schema.bindings.kafka.OperationBinding.clientId","title":"clientId class-attribute instance-attribute","text":"
clientId: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/#faststream.asyncapi.schema.bindings.kafka.OperationBinding.groupId","title":"groupId class-attribute instance-attribute","text":"
groupId: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/#faststream.asyncapi.schema.bindings.kafka.OperationBinding.replyTo","title":"replyTo class-attribute instance-attribute","text":"
replyTo: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ServerBinding/#faststream.asyncapi.schema.bindings.kafka.ServerBinding","title":"faststream.asyncapi.schema.bindings.kafka.ServerBinding","text":"

Bases: BaseModel

A class to represent a server binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ServerBinding/#faststream.asyncapi.schema.bindings.kafka.ServerBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.4.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding","title":"faststream.asyncapi.schema.bindings.main.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding","title":"faststream.asyncapi.schema.bindings.main.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding","title":"faststream.asyncapi.schema.bindings.main.ServerBinding","text":"

Bases: BaseModel

A class to represent server bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ChannelBinding/#faststream.asyncapi.schema.bindings.nats.ChannelBinding","title":"faststream.asyncapi.schema.bindings.nats.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ChannelBinding/#faststream.asyncapi.schema.bindings.nats.ChannelBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ChannelBinding/#faststream.asyncapi.schema.bindings.nats.ChannelBinding.queue","title":"queue class-attribute instance-attribute","text":"
queue: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ChannelBinding/#faststream.asyncapi.schema.bindings.nats.ChannelBinding.subject","title":"subject instance-attribute","text":"
subject: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/OperationBinding/#faststream.asyncapi.schema.bindings.nats.OperationBinding","title":"faststream.asyncapi.schema.bindings.nats.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/OperationBinding/#faststream.asyncapi.schema.bindings.nats.OperationBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/OperationBinding/#faststream.asyncapi.schema.bindings.nats.OperationBinding.replyTo","title":"replyTo class-attribute instance-attribute","text":"
replyTo: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ServerBinding/#faststream.asyncapi.schema.bindings.nats.ServerBinding","title":"faststream.asyncapi.schema.bindings.nats.ServerBinding","text":"

Bases: BaseModel

A class to represent a server binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ServerBinding/#faststream.asyncapi.schema.bindings.nats.ServerBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding","title":"faststream.asyncapi.schema.bindings.redis.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding.channel","title":"channel instance-attribute","text":"
channel: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding.consumer_name","title":"consumer_name class-attribute instance-attribute","text":"
consumer_name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding.group_name","title":"group_name class-attribute instance-attribute","text":"
group_name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding.method","title":"method class-attribute instance-attribute","text":"
method: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/OperationBinding/#faststream.asyncapi.schema.bindings.redis.OperationBinding","title":"faststream.asyncapi.schema.bindings.redis.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/OperationBinding/#faststream.asyncapi.schema.bindings.redis.OperationBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/OperationBinding/#faststream.asyncapi.schema.bindings.redis.OperationBinding.replyTo","title":"replyTo class-attribute instance-attribute","text":"
replyTo: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ServerBinding/#faststream.asyncapi.schema.bindings.redis.ServerBinding","title":"faststream.asyncapi.schema.bindings.redis.ServerBinding","text":"

Bases: BaseModel

A class to represent a server binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ServerBinding/#faststream.asyncapi.schema.bindings.redis.ServerBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ChannelBinding/#faststream.asyncapi.schema.bindings.sqs.ChannelBinding","title":"faststream.asyncapi.schema.bindings.sqs.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ChannelBinding/#faststream.asyncapi.schema.bindings.sqs.ChannelBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ChannelBinding/#faststream.asyncapi.schema.bindings.sqs.ChannelBinding.queue","title":"queue instance-attribute","text":"
queue: Dict[str, Any]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/OperationBinding/#faststream.asyncapi.schema.bindings.sqs.OperationBinding","title":"faststream.asyncapi.schema.bindings.sqs.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/OperationBinding/#faststream.asyncapi.schema.bindings.sqs.OperationBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/OperationBinding/#faststream.asyncapi.schema.bindings.sqs.OperationBinding.replyTo","title":"replyTo class-attribute instance-attribute","text":"
replyTo: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ServerBinding/#faststream.asyncapi.schema.bindings.sqs.ServerBinding","title":"faststream.asyncapi.schema.bindings.sqs.ServerBinding","text":"

Bases: BaseModel

A class to represent a server binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ServerBinding/#faststream.asyncapi.schema.bindings.sqs.ServerBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/","title":"Channel","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel","title":"faststream.asyncapi.schema.channels.Channel","text":"

Bases: BaseModel

A class to represent a channel.

Configurations

model_config : configuration for the model (only applicable for Pydantic version 2) Config : configuration for the class (only applicable for Pydantic version 1)

","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.parameters","title":"parameters class-attribute instance-attribute","text":"
parameters: Optional[Parameter] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.publish","title":"publish class-attribute instance-attribute","text":"
publish: Optional[Operation] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.servers","title":"servers class-attribute instance-attribute","text":"
servers: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.subscribe","title":"subscribe class-attribute instance-attribute","text":"
subscribe: Optional[Operation] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/","title":"Contact","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact","title":"faststream.asyncapi.schema.info.Contact","text":"

Bases: BaseModel

A class to represent a contact.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.email","title":"email class-attribute instance-attribute","text":"
email: Optional[EmailStr] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.url","title":"url class-attribute instance-attribute","text":"
url: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/ContactDict/","title":"ContactDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/ContactDict/#faststream.asyncapi.schema.info.ContactDict","title":"faststream.asyncapi.schema.info.ContactDict","text":"

Bases: TypedDict

A class to represent a dictionary of contact information.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/ContactDict/#faststream.asyncapi.schema.info.ContactDict.email","title":"email instance-attribute","text":"
email: EmailStr\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/ContactDict/#faststream.asyncapi.schema.info.ContactDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/ContactDict/#faststream.asyncapi.schema.info.ContactDict.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/EmailStr/","title":"EmailStr","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/EmailStr/#faststream.asyncapi.schema.info.EmailStr","title":"faststream.asyncapi.schema.info.EmailStr","text":"

Bases: str

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/EmailStr/#faststream.asyncapi.schema.info.EmailStr.validate","title":"validate classmethod","text":"
validate(v: Any) -> str\n
Source code in faststream/asyncapi/schema/info.py
@classmethod\ndef validate(cls, v: Any) -> str:\n    logger.warning(\n        \"email-validator bot installed, email fields will be treated as str.\\n\"\n        \"To install, run: pip install email-validator\"\n    )\n    return str(v)\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/","title":"Info","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info","title":"faststream.asyncapi.schema.info.Info","text":"

Bases: BaseModel

A class to represent information.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.contact","title":"contact class-attribute instance-attribute","text":"
contact: Optional[\n    Union[Contact, ContactDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.description","title":"description class-attribute instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.license","title":"license class-attribute instance-attribute","text":"
license: Optional[\n    Union[License, LicenseDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.termsOfService","title":"termsOfService class-attribute instance-attribute","text":"
termsOfService: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.title","title":"title instance-attribute","text":"
title: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.version","title":"version class-attribute instance-attribute","text":"
version: str = '1.0.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/","title":"License","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License","title":"faststream.asyncapi.schema.info.License","text":"

Bases: BaseModel

A class to represent a license.

Config

extra : allow additional attributes in the model (PYDANTIC_V2)

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License.url","title":"url class-attribute instance-attribute","text":"
url: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/LicenseDict/","title":"LicenseDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/LicenseDict/#faststream.asyncapi.schema.info.LicenseDict","title":"faststream.asyncapi.schema.info.LicenseDict","text":"

Bases: TypedDict

A dictionary-like class to represent a license.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/LicenseDict/#faststream.asyncapi.schema.info.LicenseDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/LicenseDict/#faststream.asyncapi.schema.info.LicenseDict.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/","title":"Components","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components","title":"faststream.asyncapi.schema.main.Components","text":"

Bases: BaseModel

A class to represent components in a system.

Note

The following attributes are not implemented yet: - servers - serverVariables - channels - securitySchemes - parameters - correlationIds - operationTraits - messageTraits - serverBindings - channelBindings - operationBindings - messageBindings

","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.messages","title":"messages class-attribute instance-attribute","text":"
messages: Optional[Dict[str, Message]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.schemas","title":"schemas class-attribute instance-attribute","text":"
schemas: Optional[Dict[str, Dict[str, Any]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.securitySchemes","title":"securitySchemes class-attribute instance-attribute","text":"
securitySchemes: Optional[Dict[str, Dict[str, Any]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/","title":"Schema","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema","title":"faststream.asyncapi.schema.main.Schema","text":"

Bases: BaseModel

A class to represent a schema.

METHOD DESCRIPTION to_jsonable

Convert the schema to a JSON-serializable object.

to_json

Convert the schema to a JSON string.

to_yaml

Convert the schema to a YAML string.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.asyncapi","title":"asyncapi class-attribute instance-attribute","text":"
asyncapi: str = ASYNC_API_VERSION\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.channels","title":"channels instance-attribute","text":"
channels: Dict[str, Channel]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.components","title":"components class-attribute instance-attribute","text":"
components: Optional[Components] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.defaultContentType","title":"defaultContentType class-attribute instance-attribute","text":"
defaultContentType: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.id","title":"id class-attribute instance-attribute","text":"
id: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.info","title":"info instance-attribute","text":"
info: Info\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.servers","title":"servers class-attribute instance-attribute","text":"
servers: Optional[Dict[str, Server]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.to_json","title":"to_json","text":"
to_json() -> str\n
Source code in faststream/asyncapi/schema/main.py
def to_json(self) -> str:\n    return model_to_json(\n        self,\n        by_alias=True,\n        exclude_none=True,\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.to_jsonable","title":"to_jsonable","text":"
to_jsonable() -> Any\n
Source code in faststream/asyncapi/schema/main.py
def to_jsonable(self) -> Any:\n    return model_to_jsonable(\n        self,\n        by_alias=True,\n        exclude_none=True,\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.to_yaml","title":"to_yaml","text":"
to_yaml() -> str\n
Source code in faststream/asyncapi/schema/main.py
def to_yaml(self) -> str:\n    from io import StringIO\n\n    import yaml\n\n    io = StringIO(initial_value=\"\", newline=\"\\n\")\n    yaml.dump(self.to_jsonable(), io, sort_keys=False)\n    return io.getvalue()\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/","title":"CorrelationId","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId","title":"faststream.asyncapi.schema.message.CorrelationId","text":"

Bases: BaseModel

A class to represent a correlation ID.

Configurations

extra : allows extra fields in the correlation ID model

","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId.location","title":"location instance-attribute","text":"
location: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/","title":"Message","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message","title":"faststream.asyncapi.schema.message.Message","text":"

Bases: BaseModel

A class to represent a message.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.contentType","title":"contentType class-attribute instance-attribute","text":"
contentType: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.correlationId","title":"correlationId class-attribute instance-attribute","text":"
correlationId: Optional[CorrelationId] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.messageId","title":"messageId class-attribute instance-attribute","text":"
messageId: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.payload","title":"payload instance-attribute","text":"
payload: Dict[str, Any]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.summary","title":"summary class-attribute instance-attribute","text":"
summary: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[List[Union[Tag, Dict[str, Any]]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/","title":"Operation","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation","title":"faststream.asyncapi.schema.operations.Operation","text":"

Bases: BaseModel

A class to represent an operation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.message","title":"message instance-attribute","text":"
message: Union[Message, Reference]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.operationId","title":"operationId class-attribute instance-attribute","text":"
operationId: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.security","title":"security class-attribute instance-attribute","text":"
security: Optional[Dict[str, List[str]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.summary","title":"summary class-attribute instance-attribute","text":"
summary: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/","title":"OauthFlowObj","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj","title":"faststream.asyncapi.schema.security.OauthFlowObj","text":"

Bases: BaseModel

A class to represent an OAuth flow object.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.authorizationUrl","title":"authorizationUrl class-attribute instance-attribute","text":"
authorizationUrl: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.refreshUrl","title":"refreshUrl class-attribute instance-attribute","text":"
refreshUrl: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.scopes","title":"scopes instance-attribute","text":"
scopes: Dict[str, str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.tokenUrl","title":"tokenUrl class-attribute instance-attribute","text":"
tokenUrl: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/","title":"OauthFlows","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows","title":"faststream.asyncapi.schema.security.OauthFlows","text":"

Bases: BaseModel

A class to represent OAuth flows.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.authorizationCode","title":"authorizationCode class-attribute instance-attribute","text":"
authorizationCode: Optional[OauthFlowObj] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.clientCredentials","title":"clientCredentials class-attribute instance-attribute","text":"
clientCredentials: Optional[OauthFlowObj] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.implicit","title":"implicit class-attribute instance-attribute","text":"
implicit: Optional[OauthFlowObj] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.password","title":"password class-attribute instance-attribute","text":"
password: Optional[OauthFlowObj] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/","title":"SecuritySchemaComponent","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent","title":"faststream.asyncapi.schema.security.SecuritySchemaComponent","text":"

Bases: BaseModel

A class to represent a security schema component.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.bearerFormat","title":"bearerFormat class-attribute instance-attribute","text":"
bearerFormat: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.flows","title":"flows class-attribute instance-attribute","text":"
flows: Optional[OauthFlows] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.in_","title":"in_ class-attribute instance-attribute","text":"
in_: Optional[str] = Field(default=None, alias='in')\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.openIdConnectUrl","title":"openIdConnectUrl class-attribute instance-attribute","text":"
openIdConnectUrl: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.schema_","title":"schema_ class-attribute instance-attribute","text":"
schema_: Optional[str] = Field(default=None, alias=\"schema\")\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.type","title":"type instance-attribute","text":"
type: Literal[\n    \"userPassword\",\n    \"apikey\",\n    \"X509\",\n    \"symmetricEncryption\",\n    \"asymmetricEncryption\",\n    \"httpApiKey\",\n    \"http\",\n    \"oauth2\",\n    \"openIdConnect\",\n    \"plain\",\n    \"scramSha256\",\n    \"scramSha512\",\n    \"gssapi\",\n]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/","title":"Server","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server","title":"faststream.asyncapi.schema.servers.Server","text":"

Bases: BaseModel

A class to represent a server.

Note

The attributes description, protocolVersion, tags, security, variables, and bindings are all optional.

Configurations

If PYDANTIC_V2 is True, the model configuration is set to allow extra attributes. Otherwise, the Config class is defined with the extra attribute set to \"allow\".

","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[Union[ServerBinding, Reference]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.protocol","title":"protocol instance-attribute","text":"
protocol: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.protocolVersion","title":"protocolVersion class-attribute instance-attribute","text":"
protocolVersion: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.security","title":"security class-attribute instance-attribute","text":"
security: Optional[SecurityRequirement] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.variables","title":"variables class-attribute instance-attribute","text":"
variables: Optional[\n    Dict[str, Union[ServerVariable, Reference]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/","title":"ServerVariable","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable","title":"faststream.asyncapi.schema.servers.ServerVariable","text":"

Bases: BaseModel

A class to represent a server variable.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.default","title":"default class-attribute instance-attribute","text":"
default: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.enum","title":"enum class-attribute instance-attribute","text":"
enum: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.examples","title":"examples class-attribute instance-attribute","text":"
examples: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/","title":"ExternalDocs","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs","title":"faststream.asyncapi.schema.utils.ExternalDocs","text":"

Bases: BaseModel

A class to represent external documentation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocsDict/","title":"ExternalDocsDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocsDict/#faststream.asyncapi.schema.utils.ExternalDocsDict","title":"faststream.asyncapi.schema.utils.ExternalDocsDict","text":"

Bases: TypedDict

A dictionary type for representing external documentation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocsDict/#faststream.asyncapi.schema.utils.ExternalDocsDict.description","title":"description instance-attribute","text":"
description: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocsDict/#faststream.asyncapi.schema.utils.ExternalDocsDict.url","title":"url instance-attribute","text":"
url: Required[AnyHttpUrl]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Parameter/","title":"Parameter","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Parameter/#faststream.asyncapi.schema.utils.Parameter","title":"faststream.asyncapi.schema.utils.Parameter","text":"

Bases: BaseModel

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Reference/","title":"Reference","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Reference/#faststream.asyncapi.schema.utils.Reference","title":"faststream.asyncapi.schema.utils.Reference","text":"

Bases: BaseModel

A class to represent a reference.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Reference/#faststream.asyncapi.schema.utils.Reference.ref","title":"ref class-attribute instance-attribute","text":"
ref: str = Field(..., alias='$ref')\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/","title":"Tag","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag","title":"faststream.asyncapi.schema.utils.Tag","text":"

Bases: BaseModel

A class to represent a tag.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/TagDict/","title":"TagDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/TagDict/#faststream.asyncapi.schema.utils.TagDict","title":"faststream.asyncapi.schema.utils.TagDict","text":"

Bases: TypedDict

A dictionary-like class for storing tags.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/TagDict/#faststream.asyncapi.schema.utils.TagDict.description","title":"description instance-attribute","text":"
description: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/TagDict/#faststream.asyncapi.schema.utils.TagDict.externalDocs","title":"externalDocs instance-attribute","text":"
externalDocs: Union[ExternalDocs, ExternalDocsDict]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/TagDict/#faststream.asyncapi.schema.utils.TagDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/site/get_asyncapi_html/","title":"get_asyncapi_html","text":"","boost":0.5},{"location":"api/faststream/asyncapi/site/get_asyncapi_html/#faststream.asyncapi.site.get_asyncapi_html","title":"faststream.asyncapi.site.get_asyncapi_html","text":"
get_asyncapi_html(\n    schema: Schema,\n    sidebar: bool = True,\n    info: bool = True,\n    servers: bool = True,\n    operations: bool = True,\n    messages: bool = True,\n    schemas: bool = True,\n    errors: bool = True,\n    expand_message_examples: bool = True,\n    title: str = \"FastStream\",\n) -> str\n

Generate HTML for displaying an AsyncAPI document.

PARAMETER DESCRIPTION schema

The AsyncAPI schema object.

TYPE: Schema

sidebar

Whether to show the sidebar. Defaults to True.

TYPE: bool DEFAULT: True

info

Whether to show the info section. Defaults to True.

TYPE: bool DEFAULT: True

servers

Whether to show the servers section. Defaults to True.

TYPE: bool DEFAULT: True

operations

Whether to show the operations section. Defaults to True.

TYPE: bool DEFAULT: True

messages

Whether to show the messages section. Defaults to True.

TYPE: bool DEFAULT: True

schemas

Whether to show the schemas section. Defaults to True.

TYPE: bool DEFAULT: True

errors

Whether to show the errors section. Defaults to True.

TYPE: bool DEFAULT: True

expand_message_examples

Whether to expand message examples. Defaults to True.

TYPE: bool DEFAULT: True

title

The title of the HTML document. Defaults to \"FastStream\".

TYPE: str DEFAULT: 'FastStream'

RETURNS DESCRIPTION str

The generated HTML document.

TYPE: str

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/asyncapi/site.py
def get_asyncapi_html(\n    schema: \"Schema\",\n    sidebar: bool = True,\n    info: bool = True,\n    servers: bool = True,\n    operations: bool = True,\n    messages: bool = True,\n    schemas: bool = True,\n    errors: bool = True,\n    expand_message_examples: bool = True,\n    title: str = \"FastStream\",\n) -> str:\n    \"\"\"Generate HTML for displaying an AsyncAPI document.\n\n    Args:\n        schema (Schema): The AsyncAPI schema object.\n        sidebar (bool, optional): Whether to show the sidebar. Defaults to True.\n        info (bool, optional): Whether to show the info section. Defaults to True.\n        servers (bool, optional): Whether to show the servers section. Defaults to True.\n        operations (bool, optional): Whether to show the operations section. Defaults to True.\n        messages (bool, optional): Whether to show the messages section. Defaults to True.\n        schemas (bool, optional): Whether to show the schemas section. Defaults to True.\n        errors (bool, optional): Whether to show the errors section. Defaults to True.\n        expand_message_examples (bool, optional): Whether to expand message examples. Defaults to True.\n        title (str, optional): The title of the HTML document. Defaults to \"FastStream\".\n\n    Returns:\n        str: The generated HTML document.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    schema_json = schema.to_json()\n\n    config = {\n        \"schema\": schema_json,\n        \"config\": {\n            \"show\": {\n                \"sidebar\": sidebar,\n                \"info\": info,\n                \"servers\": servers,\n                \"operations\": operations,\n                \"messages\": messages,\n                \"schemas\": schemas,\n                \"errors\": errors,\n            },\n            \"expand\": {\n                \"messageExamples\": expand_message_examples,\n            },\n            \"sidebar\": {\n                \"showServers\": \"byDefault\",\n                \"showOperations\": \"byDefault\",\n            },\n        },\n    }\n\n    return (\n        \"\"\"\n    <!DOCTYPE html>\n    <html>\n        <head>\n    \"\"\"\n        f\"\"\"\n        <title>{title} AsyncAPI</title>\n    \"\"\"\n        \"\"\"\n        <link rel=\"icon\" href=\"https://www.asyncapi.com/favicon.ico\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"https://www.asyncapi.com/favicon-16x16.png\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"https://www.asyncapi.com/favicon-32x32.png\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"194x194\" href=\"https://www.asyncapi.com/favicon-194x194.png\">\n        <link rel=\"stylesheet\" href=\"https://unpkg.com/@asyncapi/react-component@1.0.0-next.46/styles/default.min.css\">\n        </head>\n\n        <style>\n        html {\n            font-family: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;\n            line-height: 1.5;\n        }\n        </style>\n\n        <body>\n        <div id=\"asyncapi\"></div>\n\n        <script src=\"https://unpkg.com/@asyncapi/react-component@1.0.0-next.47/browser/standalone/index.js\"></script>\n        <script>\n    \"\"\"\n        f\"\"\"\n            AsyncApiStandalone.render({json.dumps(config)}, document.getElementById('asyncapi'));\n    \"\"\"\n        \"\"\"\n        </script>\n        </body>\n    </html>\n    \"\"\"\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/site/serve_app/","title":"serve_app","text":"","boost":0.5},{"location":"api/faststream/asyncapi/site/serve_app/#faststream.asyncapi.site.serve_app","title":"faststream.asyncapi.site.serve_app","text":"
serve_app(schema: Schema, host: str, port: int) -> None\n

Serve the FastAPI application.

PARAMETER DESCRIPTION schema

The schema object representing the API specification.

TYPE: Schema

host

The host address to run the application on.

TYPE: str

port

The port number to run the application on.

TYPE: int

RETURNS DESCRIPTION None

None

Source code in faststream/asyncapi/site.py
def serve_app(\n    schema: \"Schema\",\n    host: str,\n    port: int,\n) -> None:\n    \"\"\"Serve the FastAPI application.\n\n    Args:\n        schema: The schema object representing the API specification.\n        host: The host address to run the application on.\n        port: The port number to run the application on.\n\n    Returns:\n        None\n\n    \"\"\"\n    import uvicorn\n    from fastapi import FastAPI\n    from fastapi.responses import HTMLResponse\n\n    app = FastAPI()\n\n    @app.get(\"/\")\n    def asyncapi(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:  # pragma: no cover\n        \"\"\"Generate an AsyncAPI HTML response.\n\n        Args:\n            sidebar (bool): Whether to include the sidebar. Default is True.\n            info (bool): Whether to include the info section. Default is True.\n            servers (bool): Whether to include the servers section. Default is True.\n            operations (bool): Whether to include the operations section. Default is True.\n            messages (bool): Whether to include the messages section. Default is True.\n            schemas (bool): Whether to include the schemas section. Default is True.\n            errors (bool): Whether to include the errors section. Default is True.\n            expandMessageExamples (bool): Whether to expand message examples. Default is True.\n\n        Returns:\n            HTMLResponse: The generated HTML response.\n\n        \"\"\"\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=schema.info.title,\n            )\n        )\n\n    uvicorn.run(app, host=host, port=port)\n
","boost":0.5},{"location":"api/faststream/asyncapi/utils/resolve_payloads/","title":"resolve_payloads","text":"","boost":0.5},{"location":"api/faststream/asyncapi/utils/resolve_payloads/#faststream.asyncapi.utils.resolve_payloads","title":"faststream.asyncapi.utils.resolve_payloads","text":"
resolve_payloads(\n    payloads: List[Tuple[AnyDict, str]],\n    extra: str = \"\",\n    served_words: int = 1,\n) -> AnyDict\n

Resolve payloads.

PARAMETER DESCRIPTION payloads

A list of dictionaries representing payloads.

TYPE: List[Tuple[AnyDict, str]]

RETURNS DESCRIPTION AnyDict

A dictionary representing the resolved payload.

Source code in faststream/asyncapi/utils.py
def resolve_payloads(\n    payloads: List[Tuple[AnyDict, str]],\n    extra: str = \"\",\n    served_words: int = 1,\n) -> AnyDict:\n    \"\"\"Resolve payloads.\n\n    Args:\n        payloads: A list of dictionaries representing payloads.\n\n    Returns:\n        A dictionary representing the resolved payload.\n\n    \"\"\"\n    ln = len(payloads)\n    payload: AnyDict\n    if ln > 1:\n        one_of_payloads = {}\n\n        for body, handler_name in payloads:\n            title = body[\"title\"]\n            words = title.split(\":\")\n\n            if len(words) > 1:  # not pydantic model case\n                body[\"title\"] = title = \":\".join(\n                    filter(\n                        lambda x: bool(x),\n                        (\n                            handler_name,\n                            extra if extra not in words else \"\",\n                            *words[served_words:],\n                        ),\n                    )\n                )\n\n            one_of_payloads[title] = body\n\n        payload = {\"oneOf\": one_of_payloads}\n\n    elif ln == 1:\n        payload = payloads[0][0]\n\n    else:\n        payload = {}\n\n    return payload\n
","boost":0.5},{"location":"api/faststream/asyncapi/utils/to_camelcase/","title":"to_camelcase","text":"","boost":0.5},{"location":"api/faststream/asyncapi/utils/to_camelcase/#faststream.asyncapi.utils.to_camelcase","title":"faststream.asyncapi.utils.to_camelcase","text":"
to_camelcase(*names: str) -> str\n

Converts a list of names to camel case.

PARAMETER DESCRIPTION *names

Variable length list of names to be converted to camel case.

TYPE: str DEFAULT: ()

RETURNS DESCRIPTION str

The camel case representation of the names.

Example

to_camelcase(\"hello_world\") \"HelloWorld\"

Source code in faststream/asyncapi/utils.py
def to_camelcase(*names: str) -> str:\n    \"\"\"Converts a list of names to camel case.\n\n    Args:\n        *names: Variable length list of names to be converted to camel case.\n\n    Returns:\n        The camel case representation of the names.\n\n    Example:\n        >>> to_camelcase(\"hello_world\")\n        \"HelloWorld\"\n\n    \"\"\"\n    return \" \".join(names).replace(\"_\", \" \").title().replace(\" \", \"\")\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/","title":"BrokerUsecase","text":"","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase","title":"faststream.broker.core.abc.BrokerUsecase","text":"
BrokerUsecase(\n    url: Union[str, List[str]],\n    *args: Any,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = None,\n    description: Optional[str] = None,\n    tags: Optional[\n        Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]\n    ] = None,\n    asyncapi_url: Union[str, List[str], None] = None,\n    apply_types: bool = True,\n    validate: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[\n        str\n    ] = \"%(asctime)s %(levelname)s - %(message)s\",\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[Callable[[MsgType], BaseMiddleware]]\n    ] = None,\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: ABC, Generic[MsgType, ConnectionType], LoggingMixin

A class representing a broker use case.

METHOD DESCRIPTION __init__

constructor method

include_router

include a router in the broker

include_routers

include multiple routers in the broker

_resolve_connection_kwargs

resolve connection kwargs

_wrap_handler

wrap a handler function

_abc_start

start the broker

_abc_close

close the broker

_abc__close

close the broker connection

_process_message

process a message

subscriber

decorator to register a subscriber

publisher

register a publisher

_wrap_decode_message

wrap a message decoding function

Initialize a broker.

PARAMETER DESCRIPTION url

The URL or list of URLs to connect to.

TYPE: Union[str, List[str]]

*args

Additional arguments.

TYPE: Any DEFAULT: ()

protocol

The protocol to use for the connection.

TYPE: Optional[str] DEFAULT: None

protocol_version

The version of the protocol.

TYPE: Optional[str] DEFAULT: None

description

A description of the broker.

TYPE: Optional[str] DEFAULT: None

tags

Tags associated with the broker.

TYPE: Optional[Sequence[Union[Tag, TagDict]]] DEFAULT: None

apply_types

Whether to apply types to messages.

TYPE: bool DEFAULT: True

validate

Whether to cast types using Pydantic validation.

TYPE: bool DEFAULT: True

logger

The logger to use.

TYPE: Optional[Logger] DEFAULT: access_logger

log_level

The log level to use.

TYPE: int DEFAULT: INFO

log_fmt

The log format to use.

TYPE: Optional[str] DEFAULT: '%(asctime)s %(levelname)s - %(message)s'

dependencies

Dependencies of the broker.

TYPE: Sequence[Depends] DEFAULT: ()

middlewares

Middlewares to use.

TYPE: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] DEFAULT: None

decoder

Custom decoder for messages.

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

parser

Custom parser for messages.

TYPE: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/core/abc.py
def __init__(\n    self,\n    url: Union[str, List[str]],\n    *args: Any,\n    # AsyncAPI kwargs\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = None,\n    description: Optional[str] = None,\n    tags: Optional[Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]] = None,\n    asyncapi_url: Union[str, List[str], None] = None,\n    # broker kwargs\n    apply_types: bool = True,\n    validate: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = \"%(asctime)s %(levelname)s - %(message)s\",\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] = None,\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a broker.\n\n    Args:\n        url: The URL or list of URLs to connect to.\n        *args: Additional arguments.\n        protocol: The protocol to use for the connection.\n        protocol_version: The version of the protocol.\n        description: A description of the broker.\n        tags: Tags associated with the broker.\n        apply_types: Whether to apply types to messages.\n        validate: Whether to cast types using Pydantic validation.\n        logger: The logger to use.\n        log_level: The log level to use.\n        log_fmt: The log format to use.\n        dependencies: Dependencies of the broker.\n        middlewares: Middlewares to use.\n        decoder: Custom decoder for messages.\n        parser: Custom parser for messages.\n        **kwargs: Additional keyword arguments.\n\n    \"\"\"\n    super().__init__(\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n    )\n\n    self._connection = None\n    self._is_apply_types = apply_types\n    self._is_validate = validate\n    self.handlers = {}\n    self._publishers = {}\n    empty_middleware: Sequence[Callable[[MsgType], BaseMiddleware]] = ()\n    midd_args: Sequence[Callable[[MsgType], BaseMiddleware]] = (\n        middlewares or empty_middleware\n    )\n    self.middlewares = [CriticalLogMiddleware(logger, log_level), *midd_args]\n    self.dependencies = dependencies\n\n    self._connection_args = (url, *args)\n    self._connection_kwargs = kwargs\n\n    self._global_parser = parser\n    self._global_decoder = decoder\n\n    context.set_global(\"logger\", logger)\n    context.set_global(\"broker\", self)\n\n    self.started = False\n\n    # AsyncAPI information\n    self.url = asyncapi_url or url\n    self.protocol = protocol\n    self.protocol_version = protocol_version\n    self.description = description\n    self.tags = tags\n    self.security = security\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.handlers","title":"handlers instance-attribute","text":"
handlers: Mapping[Any, BaseHandler[MsgType]] = {}\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[Any], BaseMiddleware]] = [\n    CriticalLogMiddleware(logger, log_level),\n    *midd_args,\n]\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.url","title":"url instance-attribute","text":"
url = asyncapi_url or url\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.publisher","title":"publisher abstractmethod","text":"
publisher(\n    key: Any, publisher: BasePublisher[MsgType]\n) -> BasePublisher[MsgType]\n

Publishes a publisher.

PARAMETER DESCRIPTION key

The key associated with the publisher.

TYPE: Any

publisher

The publisher to be published.

TYPE: BasePublisher[MsgType]

RETURNS DESCRIPTION BasePublisher[MsgType]

The published publisher.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/abc.py
@abstractmethod\ndef publisher(\n    self,\n    key: Any,\n    publisher: BasePublisher[MsgType],\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a publisher.\n\n    Args:\n        key: The key associated with the publisher.\n        publisher: The publisher to be published.\n\n    Returns:\n        The published publisher.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    self._publishers = {**self._publishers, key: publisher}\n    return publisher\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.subscriber","title":"subscriber abstractmethod","text":"
subscriber(\n    *broker_args: Any,\n    retry: Union[bool, int] = False,\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Filter[\n        StreamMessage[MsgType]\n    ] = lambda: not m.processed,\n    _raw: bool = False,\n    _get_dependant: Optional[Any] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [\n        Union[\n            Callable[P_HandlerParams, T_HandlerReturn],\n            HandlerCallWrapper[\n                MsgType, P_HandlerParams, T_HandlerReturn\n            ],\n        ]\n    ],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

This is a function decorator for subscribing to a message broker.

PARAMETER DESCRIPTION *broker_args

Positional arguments to be passed to the broker.

TYPE: Any DEFAULT: ()

retry

Whether to retry the subscription if it fails. Can be a boolean or an integer specifying the number of retries.

TYPE: Union[bool, int] DEFAULT: False

dependencies

Sequence of dependencies to be injected into the handler function.

TYPE: Sequence[Depends] DEFAULT: ()

decoder

Custom decoder function to decode the message.

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

parser

Custom parser function to parse the decoded message.

TYPE: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] DEFAULT: None

middlewares

Sequence of middleware functions to be applied to the message.

TYPE: Optional[Sequence[Callable[[StreamMessage[MsgType]], BaseMiddleware]]] DEFAULT: None

filter

Filter function to filter the messages to be processed.

TYPE: Filter[StreamMessage[MsgType]] DEFAULT: lambda : not processed

_raw

Whether to return the raw message instead of the processed message.

TYPE: bool DEFAULT: False

_get_dependant

Optional parameter to get the dependant object.

TYPE: Optional[Any] DEFAULT: None

**broker_kwargs

Keyword arguments to be passed to the broker.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Callable[[Union[Callable[P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable object that can be used as a decorator for a handler function.

RAISES DESCRIPTION RuntimeWarning

If the broker is already running.

Source code in faststream/broker/core/abc.py
@abstractmethod\ndef subscriber(  # type: ignore[return]\n    self,\n    *broker_args: Any,\n    retry: Union[bool, int] = False,\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                BaseMiddleware,\n            ]\n        ]\n    ] = None,\n    filter: Filter[StreamMessage[MsgType]] = lambda m: not m.processed,\n    _raw: bool = False,\n    _get_dependant: Optional[Any] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [\n        Union[\n            Callable[P_HandlerParams, T_HandlerReturn],\n            HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n        ]\n    ],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"This is a function decorator for subscribing to a message broker.\n\n    Args:\n        *broker_args: Positional arguments to be passed to the broker.\n        retry: Whether to retry the subscription if it fails. Can be a boolean or an integer specifying the number of retries.\n        dependencies: Sequence of dependencies to be injected into the handler function.\n        decoder: Custom decoder function to decode the message.\n        parser: Custom parser function to parse the decoded message.\n        middlewares: Sequence of middleware functions to be applied to the message.\n        filter: Filter function to filter the messages to be processed.\n        _raw: Whether to return the raw message instead of the processed message.\n        _get_dependant: Optional parameter to get the dependant object.\n        **broker_kwargs: Keyword arguments to be passed to the broker.\n\n    Returns:\n        A callable object that can be used as a decorator for a handler function.\n\n    Raises:\n        RuntimeWarning: If the broker is already running.\n\n    \"\"\"\n    if self.started and not is_test_env():  # pragma: no cover\n        warnings.warn(\n            \"You are trying to register `handler` with already running broker\\n\"  # noqa: E501\n            \"It has no effect until broker restarting.\",  # noqa: E501\n            category=RuntimeWarning,\n            stacklevel=1,\n        )\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/extend_dependencies/","title":"extend_dependencies","text":"","boost":0.5},{"location":"api/faststream/broker/core/abc/extend_dependencies/#faststream.broker.core.abc.extend_dependencies","title":"faststream.broker.core.abc.extend_dependencies","text":"
extend_dependencies(\n    extra: Sequence[CallModel[Any, Any]],\n    dependant: CallModel[Any, Any],\n) -> CallModel[Any, Any]\n

Extends the dependencies of a function or FastAPI dependency.

PARAMETER DESCRIPTION extra

Additional dependencies to be added.

TYPE: Sequence[CallModel[Any, Any]]

dependant

The function or FastAPI dependency whose dependencies will be extended.

TYPE: CallModel[Any, Any]

RETURNS DESCRIPTION CallModel[Any, Any]

The updated function or FastAPI dependency.

Source code in faststream/broker/core/abc.py
def extend_dependencies(\n    extra: Sequence[CallModel[Any, Any]], dependant: CallModel[Any, Any]\n) -> CallModel[Any, Any]:\n    \"\"\"Extends the dependencies of a function or FastAPI dependency.\n\n    Args:\n        extra: Additional dependencies to be added.\n        dependant: The function or FastAPI dependency whose dependencies will be extended.\n\n    Returns:\n        The updated function or FastAPI dependency.\n\n    \"\"\"\n    if isinstance(dependant, CallModel):\n        dependant.extra_dependencies = (*dependant.extra_dependencies, *extra)\n    else:  # FastAPI dependencies\n        dependant.dependencies.extend(extra)\n    return dependant\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/","title":"BrokerAsyncUsecase","text":"","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase","title":"faststream.broker.core.asyncronous.BrokerAsyncUsecase","text":"
BrokerAsyncUsecase(\n    *args: Any,\n    apply_types: bool = True,\n    validate: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[\n        str\n    ] = \"%(asctime)s %(levelname)s - %(message)s\",\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    middlewares: Optional[\n        Sequence[Callable[[MsgType], BaseMiddleware]]\n    ] = None,\n    graceful_timeout: Optional[float] = None,\n    **kwargs: Any\n)\n

Bases: BrokerUsecase[MsgType, ConnectionType]

A class representing a broker async usecase.

METHOD DESCRIPTION start

Abstract method to start the broker async usecase.

_connect

Any) : Abstract method to connect to the broker.

_close

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) : Abstract method to close the connection to the broker.

close

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) : Close the connection to the broker.

_process_message

Callable[[StreamMessage[MsgType]], Awaitable[T_HandlerReturn]], watcher: BaseWatcher) : Abstract method to process a message.

publish

SendableMessage, *args: Any, reply_to: str = \"\", rpc: bool = False, rpc_timeout: Optional[float]

Initialize the class.

PARAMETER DESCRIPTION *args

Variable length arguments

TYPE: Any DEFAULT: ()

apply_types

Whether to apply types or not

TYPE: bool DEFAULT: True

validate

Whether to cast types using Pydantic validation.

TYPE: bool DEFAULT: True

logger

Logger object for logging

TYPE: Optional[Logger] DEFAULT: access_logger

log_level

Log level for logging

TYPE: int DEFAULT: INFO

log_fmt

Log format for logging

TYPE: Optional[str] DEFAULT: '%(asctime)s %(levelname)s - %(message)s'

dependencies

Sequence of dependencies

TYPE: Sequence[Depends] DEFAULT: ()

decoder

Custom decoder object

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

parser

Custom parser object

TYPE: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] DEFAULT: None

middlewares

Sequence of middlewares

TYPE: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] DEFAULT: None

**kwargs

Keyword arguments

TYPE: Any DEFAULT: {}

Source code in faststream/broker/core/asyncronous.py
def __init__(\n    self,\n    *args: Any,\n    apply_types: bool = True,\n    validate: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = \"%(asctime)s %(levelname)s - %(message)s\",\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    middlewares: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] = None,\n    graceful_timeout: Optional[float] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        *args: Variable length arguments\n        apply_types: Whether to apply types or not\n        validate: Whether to cast types using Pydantic validation.\n        logger: Logger object for logging\n        log_level: Log level for logging\n        log_fmt: Log format for logging\n        dependencies: Sequence of dependencies\n        decoder: Custom decoder object\n        parser: Custom parser object\n        middlewares: Sequence of middlewares\n        **kwargs: Keyword arguments\n\n    \"\"\"\n    super().__init__(\n        *args,\n        apply_types=apply_types,\n        validate=validate,\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n        dependencies=dependencies,\n        decoder=cast(\n            Optional[AsyncCustomDecoder[StreamMessage[MsgType]]],\n            to_async(decoder) if decoder else None,\n        ),\n        parser=cast(\n            Optional[AsyncCustomParser[MsgType, StreamMessage[MsgType]]],\n            to_async(parser) if parser else None,\n        ),\n        middlewares=middlewares,\n        **kwargs,\n    )\n    self.graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.handlers","title":"handlers instance-attribute","text":"
handlers: Mapping[Any, AsyncHandler[MsgType]]\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.url","title":"url instance-attribute","text":"
url = asyncapi_url or url\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.connect","title":"connect async","text":"
connect(*args: Any, **kwargs: Any) -> ConnectionType\n

Connect to a remote server.

PARAMETER DESCRIPTION *args

Variable length argument list.

TYPE: Any DEFAULT: ()

**kwargs

Arbitrary keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION ConnectionType

The connection object.

Source code in faststream/broker/core/asyncronous.py
async def connect(self, *args: Any, **kwargs: Any) -> ConnectionType:\n    \"\"\"Connect to a remote server.\n\n    Args:\n        *args: Variable length argument list.\n        **kwargs: Arbitrary keyword arguments.\n\n    Returns:\n        The connection object.\n\n    \"\"\"\n    if self._connection is None:\n        _kwargs = self._resolve_connection_kwargs(*args, **kwargs)\n        self._connection = await self._connect(**_kwargs)\n    return self._connection\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.publish","title":"publish abstractmethod async","text":"
publish(\n    message: SendableMessage,\n    *args: Any,\n    reply_to: str = \"\",\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

*args

Additional arguments.

TYPE: Any DEFAULT: ()

reply_to

The reply-to address for the message.

TYPE: str DEFAULT: ''

rpc

Whether the message is for RPC.

TYPE: bool DEFAULT: False

rpc_timeout

The timeout for RPC.

TYPE: Optional[float] DEFAULT: None

raise_timeout

Whether to raise an exception on timeout.

TYPE: bool DEFAULT: False

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
@abstractmethod\nasync def publish(\n    self,\n    message: SendableMessage,\n    *args: Any,\n    reply_to: str = \"\",\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        *args: Additional arguments.\n        reply_to: The reply-to address for the message.\n        rpc: Whether the message is for RPC.\n        rpc_timeout: The timeout for RPC.\n        raise_timeout: Whether to raise an exception on timeout.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.publisher","title":"publisher abstractmethod","text":"
publisher(\n    key: Any, publisher: BasePublisher[MsgType]\n) -> BasePublisher[MsgType]\n

Publishes a publisher.

PARAMETER DESCRIPTION key

The key associated with the publisher.

TYPE: Any

publisher

The publisher to be published.

TYPE: BasePublisher[MsgType]

RETURNS DESCRIPTION BasePublisher[MsgType]

The published publisher.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/abc.py
@abstractmethod\ndef publisher(\n    self,\n    key: Any,\n    publisher: BasePublisher[MsgType],\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a publisher.\n\n    Args:\n        key: The key associated with the publisher.\n        publisher: The publisher to be published.\n\n    Returns:\n        The published publisher.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    self._publishers = {**self._publishers, key: publisher}\n    return publisher\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.start","title":"start abstractmethod async","text":"
start() -> None\n
Source code in faststream/broker/core/asyncronous.py
@abstractmethod\nasync def start(self) -> None:\n    super()._abc_start()\n    for h in self.handlers.values():\n        for f, _, _, _, _, _ in h.calls:\n            f.refresh(with_mock=False)\n    await self.connect()\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.subscriber","title":"subscriber abstractmethod","text":"
subscriber(\n    *broker_args: Any,\n    retry: Union[bool, int] = False,\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    middlewares: Optional[\n        Sequence[Callable[[MsgType], BaseMiddleware]]\n    ] = None,\n    filter: Filter[StreamMessage[MsgType]] = default_filter,\n    _raw: bool = False,\n    _get_dependant: Optional[Any] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [\n        Union[\n            Callable[P_HandlerParams, T_HandlerReturn],\n            HandlerCallWrapper[\n                MsgType, P_HandlerParams, T_HandlerReturn\n            ],\n        ]\n    ],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function decorator for subscribing to a message broker.

PARAMETER DESCRIPTION *broker_args

Positional arguments to be passed to the message broker.

TYPE: Any DEFAULT: ()

retry

Whether to retry the subscription if it fails. Can be a boolean or an integer specifying the number of retries.

TYPE: Union[bool, int] DEFAULT: False

dependencies

Sequence of dependencies to be injected into the decorated function.

TYPE: Sequence[Depends] DEFAULT: ()

decoder

Custom decoder function for decoding the message.

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

parser

Custom parser function for parsing the decoded message.

TYPE: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] DEFAULT: None

middlewares

Sequence of middleware functions to be applied to the message.

TYPE: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] DEFAULT: None

filter

Filter function for filtering the messages to be processed.

TYPE: Filter[StreamMessage[MsgType]] DEFAULT: default_filter

_raw

Whether to return the raw message instead of the processed result.

TYPE: bool DEFAULT: False

_get_dependant

Optional argument to get the dependant object.

TYPE: Optional[Any] DEFAULT: None

RETURNS DESCRIPTION Callable[[Union[Callable[P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable decorator that wraps the decorated function and handles the subscription.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/core/asyncronous.py
@override\n@abstractmethod\ndef subscriber(  # type: ignore[override,return]\n    self,\n    *broker_args: Any,\n    retry: Union[bool, int] = False,\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    middlewares: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] = None,\n    filter: Filter[StreamMessage[MsgType]] = default_filter,\n    _raw: bool = False,\n    _get_dependant: Optional[Any] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [\n        Union[\n            Callable[P_HandlerParams, T_HandlerReturn],\n            HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n        ]\n    ],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function decorator for subscribing to a message broker.\n\n    Args:\n        *broker_args: Positional arguments to be passed to the message broker.\n        retry: Whether to retry the subscription if it fails. Can be a boolean or an integer specifying the number of retries.\n        dependencies: Sequence of dependencies to be injected into the decorated function.\n        decoder: Custom decoder function for decoding the message.\n        parser: Custom parser function for parsing the decoded message.\n        middlewares: Sequence of middleware functions to be applied to the message.\n        filter: Filter function for filtering the messages to be processed.\n        _raw: Whether to return the raw message instead of the processed result.\n        _get_dependant: Optional argument to get the dependant object.\n\n    Returns:\n        A callable decorator that wraps the decorated function and handles the subscription.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    super().subscriber()\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/default_filter/","title":"default_filter","text":"","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/default_filter/#faststream.broker.core.asyncronous.default_filter","title":"faststream.broker.core.asyncronous.default_filter async","text":"
default_filter(msg: StreamMessage[Any]) -> bool\n

A function to filter stream messages.

PARAMETER DESCRIPTION msg

A stream message object

RETURNS DESCRIPTION bool

True if the message has not been processed, False otherwise

Source code in faststream/broker/core/asyncronous.py
async def default_filter(msg: StreamMessage[Any]) -> bool:\n    \"\"\"A function to filter stream messages.\n\n    Args:\n        msg : A stream message object\n\n    Returns:\n        True if the message has not been processed, False otherwise\n\n    \"\"\"\n    return not msg.processed\n
","boost":0.5},{"location":"api/faststream/broker/core/mixins/LoggingMixin/","title":"LoggingMixin","text":"","boost":0.5},{"location":"api/faststream/broker/core/mixins/LoggingMixin/#faststream.broker.core.mixins.LoggingMixin","title":"faststream.broker.core.mixins.LoggingMixin","text":"
LoggingMixin(\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[\n        str\n    ] = \"%(asctime)s %(levelname)s - %(message)s\",\n    **kwargs: Any\n)\n

A mixin class for logging.

METHOD DESCRIPTION fmt

getter method for _fmt attribute

_get_log_context

returns a dictionary with log context information

_log

logs a message with optional log level, extra data, and exception info

Initialize the class.

PARAMETER DESCRIPTION *args

Variable length argument list

TYPE: Any DEFAULT: ()

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: access_logger

log_level

Log level (default: logging.INFO)

TYPE: int DEFAULT: INFO

log_fmt

Log format (default: \"%(asctime)s %(levelname)s - %(message)s\")

TYPE: Optional[str] DEFAULT: '%(asctime)s %(levelname)s - %(message)s'

**kwargs

Arbitrary keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/mixins.py
def __init__(\n    self,\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = \"%(asctime)s %(levelname)s - %(message)s\",\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        *args: Variable length argument list\n        logger: Optional logger object\n        log_level: Log level (default: logging.INFO)\n        log_fmt: Log format (default: \"%(asctime)s %(levelname)s - %(message)s\")\n        **kwargs: Arbitrary keyword arguments\n\n    Returns:\n        None\n\n    \"\"\"\n    self.logger = logger\n    self.log_level = log_level\n    self._fmt = log_fmt\n    self._message_id_ln = 10\n
","boost":0.5},{"location":"api/faststream/broker/core/mixins/LoggingMixin/#faststream.broker.core.mixins.LoggingMixin.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/broker/core/mixins/LoggingMixin/#faststream.broker.core.mixins.LoggingMixin.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/broker/core/mixins/LoggingMixin/#faststream.broker.core.mixins.LoggingMixin.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/","title":"StreamMessage","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage","title":"faststream.broker.fastapi.StreamMessage","text":"
StreamMessage(\n    *,\n    body: Union[AnyDict, List[Any]],\n    headers: AnyDict,\n    path: AnyDict\n)\n

Bases: Request

A class to represent a stream message.

METHOD DESCRIPTION __init__

initializes the StreamMessage object

get_session

returns a callable function that handles the session of the message

Initialize a class instance.

PARAMETER DESCRIPTION body

The body of the request as a dictionary.

TYPE: Union[AnyDict, List[Any]]

headers

The headers of the request as a dictionary.

TYPE: AnyDict

Source code in faststream/broker/fastapi/route.py
def __init__(\n    self,\n    *,\n    body: Union[AnyDict, List[Any]],\n    headers: AnyDict,\n    path: AnyDict,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        body: The body of the request as a dictionary.\n        headers: The headers of the request as a dictionary.\n\n    Attributes:\n        scope: A dictionary to store the scope of the request.\n        _cookies: A dictionary to store the cookies of the request.\n        _headers: A dictionary to store the headers of the request.\n        _body: A dictionary to store the body of the request.\n        _query_params: A dictionary to store the query parameters of the request.\n\n    \"\"\"\n    self._headers = headers\n    self._body = body\n    self._query_params = path\n\n    self.scope = {\"path_params\": self._query_params}\n    self._cookies = {}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.app","title":"app property","text":"
app: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.auth","title":"auth property","text":"
auth: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.base_url","title":"base_url property","text":"
base_url: URL\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.client","title":"client property","text":"
client: typing.Optional[Address]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.cookies","title":"cookies property","text":"
cookies: typing.Dict[str, str]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.headers","title":"headers property","text":"
headers: Headers\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.method","title":"method property","text":"
method: str\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.path_params","title":"path_params property","text":"
path_params: typing.Dict[str, typing.Any]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.query_params","title":"query_params property","text":"
query_params: QueryParams\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.receive","title":"receive property","text":"
receive: Receive\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.scope","title":"scope instance-attribute","text":"
scope: AnyDict = {'path_params': self._query_params}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.session","title":"session property","text":"
session: typing.Dict[str, typing.Any]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.state","title":"state property","text":"
state: State\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.url","title":"url property","text":"
url: URL\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.user","title":"user property","text":"
user: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.body","title":"body async","text":"
body() -> bytes\n
Source code in starlette/requests.py
async def body(self) -> bytes:\n    if not hasattr(self, \"_body\"):\n        chunks: \"typing.List[bytes]\" = []\n        async for chunk in self.stream():\n            chunks.append(chunk)\n        self._body = b\"\".join(chunks)\n    return self._body\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.close","title":"close async","text":"
close() -> None\n
Source code in starlette/requests.py
async def close(self) -> None:\n    if self._form is not None:\n        await self._form.close()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.form","title":"form","text":"
form(\n    *,\n    max_files: typing.Union[int, float] = 1000,\n    max_fields: typing.Union[int, float] = 1000\n) -> AwaitableOrContextManager[FormData]\n
Source code in starlette/requests.py
def form(\n    self,\n    *,\n    max_files: typing.Union[int, float] = 1000,\n    max_fields: typing.Union[int, float] = 1000,\n) -> AwaitableOrContextManager[FormData]:\n    return AwaitableOrContextManagerWrapper(\n        self._get_form(max_files=max_files, max_fields=max_fields)\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.get_session","title":"get_session classmethod","text":"
get_session(\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[\n    [NativeMessage[Any]], Awaitable[SendableMessage]\n]\n

Creates a session for handling requests.

PARAMETER DESCRIPTION dependant

The dependant object representing the session.

TYPE: Dependant

dependency_overrides_provider

Optional provider for dependency overrides.

TYPE: Optional[Any] DEFAULT: None

RETURNS DESCRIPTION Callable[[StreamMessage[Any]], Awaitable[SendableMessage]]

A callable that takes a native message and returns an awaitable sendable message.

RAISES DESCRIPTION AssertionError

If the dependant call is not defined.

Note

This function is used to create a session for handling requests. It takes a dependant object, which represents the session, and a dependency overrides provider, which allows for overriding dependencies. It returns a callable that takes a native message and returns an awaitable sendable message. The session is created based on the dependant object and the message passed to the callable. The session is then used to call the function obtained from the dependant object, and the result is returned.

Source code in faststream/broker/fastapi/route.py
@classmethod\ndef get_session(\n    cls,\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[[NativeMessage[Any]], Awaitable[SendableMessage]]:\n    \"\"\"Creates a session for handling requests.\n\n    Args:\n        dependant: The dependant object representing the session.\n        dependency_overrides_provider: Optional provider for dependency overrides.\n\n    Returns:\n        A callable that takes a native message and returns an awaitable sendable message.\n\n    Raises:\n        AssertionError: If the dependant call is not defined.\n\n    Note:\n        This function is used to create a session for handling requests. It takes a dependant object, which represents the session, and a dependency overrides provider, which allows for overriding dependencies. It returns a callable that takes a native message and returns an awaitable sendable message. The session is created based on the dependant object and the message passed to the callable. The session is then used to call the function obtained from the dependant object, and the result is returned.\n\n    \"\"\"\n    assert dependant.call  # nosec B101\n\n    func = get_app(dependant, dependency_overrides_provider)\n\n    dependencies_names = tuple(i.name for i in dependant.dependencies)\n\n    first_arg = next(\n        dropwhile(\n            lambda i: i in dependencies_names,\n            inspect.signature(dependant.call).parameters,\n        ),\n        None,\n    )\n\n    async def app(message: NativeMessage[Any]) -> SendableMessage:\n        \"\"\"An asynchronous function that processes an incoming message and returns a sendable message.\n\n        Args:\n            message : The incoming message to be processed\n\n        Returns:\n            The sendable message\n\n        Raises:\n            TypeError: If the body of the message is not a dictionary\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        body = message.decoded_body\n\n        fastapi_body: Union[AnyDict, List[Any]]\n        if first_arg is not None:\n            if isinstance(body, dict):\n                path = fastapi_body = body or {}\n            elif isinstance(body, list):\n                fastapi_body, path = body, {}\n            else:\n                path = fastapi_body = {first_arg: body}\n\n            session = cls(\n                body=fastapi_body,\n                headers=message.headers,\n                path={**path, **message.path},\n            )\n\n        else:\n            session = cls(\n                body={},\n                headers={},\n                path={},\n            )\n\n        return await func(session)\n\n    return app\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.is_disconnected","title":"is_disconnected async","text":"
is_disconnected() -> bool\n
Source code in starlette/requests.py
async def is_disconnected(self) -> bool:\n    if not self._is_disconnected:\n        message: Message = {}\n\n        # If message isn't immediately available, move on\n        with anyio.CancelScope() as cs:\n            cs.cancel()\n            message = await self._receive()\n\n        if message.get(\"type\") == \"http.disconnect\":\n            self._is_disconnected = True\n\n    return self._is_disconnected\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.json","title":"json async","text":"
json() -> typing.Any\n
Source code in starlette/requests.py
async def json(self) -> typing.Any:\n    if not hasattr(self, \"_json\"):\n        body = await self.body()\n        self._json = json.loads(body)\n    return self._json\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.send_push_promise","title":"send_push_promise async","text":"
send_push_promise(path: str) -> None\n
Source code in starlette/requests.py
async def send_push_promise(self, path: str) -> None:\n    if \"http.response.push\" in self.scope.get(\"extensions\", {}):\n        raw_headers: \"typing.List[typing.Tuple[bytes, bytes]]\" = []\n        for name in SERVER_PUSH_HEADERS_TO_COPY:\n            for value in self.headers.getlist(name):\n                raw_headers.append(\n                    (name.encode(\"latin-1\"), value.encode(\"latin-1\"))\n                )\n        await self._send(\n            {\"type\": \"http.response.push\", \"path\": path, \"headers\": raw_headers}\n        )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.stream","title":"stream async","text":"
stream() -> typing.AsyncGenerator[bytes, None]\n
Source code in starlette/requests.py
async def stream(self) -> typing.AsyncGenerator[bytes, None]:\n    if hasattr(self, \"_body\"):\n        yield self._body\n        yield b\"\"\n        return\n    if self._stream_consumed:\n        raise RuntimeError(\"Stream consumed\")\n    self._stream_consumed = True\n    while True:\n        message = await self._receive()\n        if message[\"type\"] == \"http.request\":\n            body = message.get(\"body\", b\"\")\n            if body:\n                yield body\n            if not message.get(\"more_body\", False):\n                break\n        elif message[\"type\"] == \"http.disconnect\":\n            self._is_disconnected = True\n            raise ClientDisconnect()\n    yield b\"\"\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.url_for","title":"url_for","text":"
url_for(__name: str, **path_params: typing.Any) -> URL\n
Source code in starlette/requests.py
def url_for(self, __name: str, **path_params: typing.Any) -> URL:\n    router: Router = self.scope[\"router\"]\n    url_path = router.url_path_for(__name, **path_params)\n    return url_path.make_absolute_url(base_url=self.base_url)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/","title":"StreamRoute","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute","title":"faststream.broker.fastapi.StreamRoute","text":"
StreamRoute(\n    path: Union[NameRequired, str, None],\n    *extra: Union[NameRequired, str],\n    endpoint: Union[\n        Callable[P_HandlerParams, T_HandlerReturn],\n        HandlerCallWrapper[\n            MsgType, P_HandlerParams, T_HandlerReturn\n        ],\n    ],\n    broker: BrokerAsyncUsecase[MsgType, Any],\n    dependencies: Sequence[params.Depends] = (),\n    dependency_overrides_provider: Optional[Any] = None,\n    **handle_kwargs: Any\n)\n

Bases: BaseRoute, Generic[MsgType, P_HandlerParams, T_HandlerReturn]

A class representing a stream route.

Initialize a class instance.

PARAMETER DESCRIPTION path

The path of the instance.

TYPE: Union[NameRequired, str, None]

*extra

Additional arguments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint of the instance.

TYPE: Union[Callable[P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

broker

The broker of the instance.

TYPE: BrokerAsyncUsecase[MsgType, Any]

dependencies

The dependencies of the instance.

TYPE: Sequence[Depends] DEFAULT: ()

dependency_overrides_provider

The provider for dependency overrides.

TYPE: Optional[Any] DEFAULT: None

**handle_kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None.

Source code in faststream/broker/fastapi/route.py
def __init__(\n    self,\n    path: Union[NameRequired, str, None],\n    *extra: Union[NameRequired, str],\n    endpoint: Union[\n        Callable[P_HandlerParams, T_HandlerReturn],\n        HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n    ],\n    broker: BrokerAsyncUsecase[MsgType, Any],\n    dependencies: Sequence[params.Depends] = (),\n    dependency_overrides_provider: Optional[Any] = None,\n    **handle_kwargs: Any,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        path: The path of the instance.\n        *extra: Additional arguments.\n        endpoint: The endpoint of the instance.\n        broker: The broker of the instance.\n        dependencies: The dependencies of the instance.\n        dependency_overrides_provider: The provider for dependency overrides.\n        **handle_kwargs: Additional keyword arguments.\n\n    Returns:\n        None.\n\n    \"\"\"\n    self.path = path or \"\"\n    self.broker = broker\n\n    path_name = self.path if isinstance(self.path, str) else self.path.name\n\n    if isinstance(endpoint, HandlerCallWrapper):\n        orig_call = endpoint._original_call\n    else:\n        orig_call = endpoint\n\n    dependant = get_dependant(\n        path=path_name,\n        call=orig_call,\n    )\n    for depends in dependencies[::-1]:\n        dependant.dependencies.insert(\n            0,\n            get_parameterless_sub_dependant(depends=depends, path=path_name),\n        )\n    self.dependant = dependant\n\n    call = wraps(orig_call)(\n        StreamMessage.get_session(\n            dependant,\n            dependency_overrides_provider,\n        )\n    )\n\n    if isinstance(endpoint, HandlerCallWrapper):\n        endpoint._original_call = call\n        handler = endpoint\n\n    else:\n        handler = call\n\n    self.handler = broker.subscriber(\n        path,\n        *extra,\n        _raw=True,\n        _get_dependant=lambda call: dependant,\n        **handle_kwargs,\n    )(\n        handler  # type: ignore[arg-type]\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.dependant","title":"dependant instance-attribute","text":"
dependant = dependant\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.handler","title":"handler instance-attribute","text":"
handler: HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n] = broker.subscriber(\n    path,\n    *extra,\n    _raw=True,\n    _get_dependant=lambda: dependant,\n    **handle_kwargs\n)(\n    handler\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.path","title":"path instance-attribute","text":"
path = path or ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.handle","title":"handle async","text":"
handle(scope: Scope, receive: Receive, send: Send) -> None\n
Source code in starlette/routing.py
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.matches","title":"matches","text":"
matches(scope: Scope) -> typing.Tuple[Match, Scope]\n
Source code in starlette/routing.py
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/","title":"StreamRouter","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter","title":"faststream.broker.fastapi.StreamRouter","text":"
StreamRouter(\n    *connection_args: Tuple[Any, ...],\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    setup_state: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id),\n    asyncapi_tags: Optional[\n        Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]\n    ] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    **connection_kwars: Any\n)\n

Bases: APIRouter, Generic[MsgType]

A class to route streams.

METHOD DESCRIPTION __init__

initialize the StreamRouter

add_api_mq_route

add a route for API and message queue

subscriber

decorator to define a subscriber

wrap_lifespan

wrap the lifespan of the router

after_startup

decorator to define a function to be executed after startup

publisher

create a publisher for the broker

asyncapi_router

create an APIRouter for AsyncAPI documentation

include_router

include another router in the StreamRouter

_setup_log_context

setup log context for the broker

Initialize an instance of a class.

PARAMETER DESCRIPTION *connection_args

Variable length arguments for the connection

TYPE: Tuple[Any, ...] DEFAULT: ()

prefix

Prefix for the class

TYPE: str DEFAULT: ''

tags

Optional list of tags for the class

TYPE: Optional[List[Union[str, Enum]]] DEFAULT: None

dependencies

Optional sequence of dependencies for the class

TYPE: Optional[Sequence[Depends]] DEFAULT: None

default_response_class

Default response class for the class

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

Optional dictionary of responses for the class

TYPE: Optional[Dict[Union[int, str], AnyDict]] DEFAULT: None

callbacks

Optional list of callbacks for the class

TYPE: Optional[List[BaseRoute]] DEFAULT: None

routes

Optional list of routes for the class

TYPE: Optional[List[BaseRoute]] DEFAULT: None

redirect_slashes

Boolean value indicating whether to redirect slashes

TYPE: bool DEFAULT: True

default

Optional default value for the class

TYPE: Optional[ASGIApp] DEFAULT: None

dependency_overrides_provider

Optional provider for dependency overrides

TYPE: Optional[Any] DEFAULT: None

route_class

Route class for the class

TYPE: Type[APIRoute] DEFAULT: APIRoute

on_startup

Optional sequence of functions to run on startup

TYPE: Optional[Sequence[Callable[[], Any]]] DEFAULT: None

on_shutdown

Optional sequence of functions to run on shutdown

TYPE: Optional[Sequence[Callable[[], Any]]] DEFAULT: None

deprecated

Optional boolean value indicating whether the class is deprecated

TYPE: Optional[bool] DEFAULT: None

include_in_schema

Boolean value indicating whether to include the class in the schema

TYPE: bool DEFAULT: True

setup_state

Boolean value indicating whether to setup state

TYPE: bool DEFAULT: True

lifespan

Optional lifespan for the class

TYPE: Optional[Lifespan[Any]] DEFAULT: None

generate_unique_id_function

Function to generate unique ID for the class

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

asyncapi_tags

Optional sequence of asyncapi tags for the class schema

TYPE: Optional[Sequence[Union[Tag, TagDict]]] DEFAULT: None

Source code in faststream/broker/fastapi/router.py
def __init__(\n    self,\n    *connection_args: Tuple[Any, ...],\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[Sequence[Callable[[], Any]]] = None,\n    on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    setup_state: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n    # AsyncAPI information\n    asyncapi_tags: Optional[Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    **connection_kwars: Any,\n) -> None:\n    \"\"\"Initialize an instance of a class.\n\n    Args:\n        *connection_args: Variable length arguments for the connection\n        prefix: Prefix for the class\n        tags: Optional list of tags for the class\n        dependencies: Optional sequence of dependencies for the class\n        default_response_class: Default response class for the class\n        responses: Optional dictionary of responses for the class\n        callbacks: Optional list of callbacks for the class\n        routes: Optional list of routes for the class\n        redirect_slashes: Boolean value indicating whether to redirect slashes\n        default: Optional default value for the class\n        dependency_overrides_provider: Optional provider for dependency overrides\n        route_class: Route class for the class\n        on_startup: Optional sequence of functions to run on startup\n        on_shutdown: Optional sequence of functions to run on shutdown\n        deprecated: Optional boolean value indicating whether the class is deprecated\n        include_in_schema: Boolean value indicating whether to include the class in the schema\n        setup_state: Boolean value indicating whether to setup state\n        lifespan: Optional lifespan for the class\n        generate_unique_id_function: Function to generate unique ID for the class\n        asyncapi_tags: Optional sequence of asyncapi tags for the class schema\n\n    \"\"\"\n    assert (  # nosec B101\n        self.broker_class\n    ), \"You should specify `broker_class` at your implementation\"\n\n    self.broker = self.broker_class(\n        *connection_args,\n        apply_types=False,\n        tags=asyncapi_tags,\n        **connection_kwars,\n    )\n\n    self.setup_state = setup_state\n\n    # AsyncAPI information\n    # Empty\n    self.terms_of_service = None\n    self.identifier = None\n    self.asyncapi_tags = None\n    self.external_docs = None\n    # parse from FastAPI app on startup\n    self.title = \"\"\n    self.version = \"\"\n    self.description = \"\"\n    self.license = None\n    self.contact = None\n\n    self.schema = None\n\n    super().__init__(\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        routes=routes,\n        redirect_slashes=redirect_slashes,\n        default=default,\n        dependency_overrides_provider=dependency_overrides_provider,\n        route_class=route_class,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n        lifespan=self.wrap_lifespan(lifespan),\n        on_startup=on_startup,\n        on_shutdown=on_shutdown,\n    )\n\n    self.docs_router = self.asyncapi_router(schema_url)\n\n    self._after_startup_hooks = []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.broker","title":"broker instance-attribute","text":"
broker: BrokerAsyncUsecase[\n    MsgType, Any\n] = self.broker_class(\n    *connection_args,\n    apply_types=False,\n    tags=asyncapi_tags,\n    **connection_kwars\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.broker_class","title":"broker_class instance-attribute","text":"
broker_class: Type[BrokerAsyncUsecase[MsgType, Any]]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any\n) -> HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n]\n

Add an API message queue route.

PARAMETER DESCRIPTION path

The path of the route.

TYPE: Union[NameRequired, str]

*extra

Additional path segments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint function to be called for this route.

TYPE: Callable[P_HandlerParams, T_HandlerReturn]

dependencies

The dependencies required by the endpoint function.

TYPE: Sequence[Depends]

**broker_kwargs

Additional keyword arguments to be passed to the broker.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]

The handler call wrapper for the route.

Source code in faststream/broker/fastapi/router.py
def add_api_mq_route(\n    self,\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any,\n) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n    \"\"\"Add an API message queue route.\n\n    Args:\n        path: The path of the route.\n        *extra: Additional path segments.\n        endpoint: The endpoint function to be called for this route.\n        dependencies: The dependencies required by the endpoint function.\n        **broker_kwargs: Additional keyword arguments to be passed to the broker.\n\n    Returns:\n        The handler call wrapper for the route.\n\n    \"\"\"\n    route: StreamRoute[MsgType, P_HandlerParams, T_HandlerReturn] = StreamRoute(\n        path,\n        *extra,\n        endpoint=endpoint,\n        dependencies=dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        broker=self.broker,\n        **broker_kwargs,\n    )\n    self.routes.append(route)\n    return route.handler\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.publisher","title":"publisher","text":"
publisher(\n    queue: Union[NameRequired, str],\n    *publisher_args: Any,\n    **publisher_kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes messages to a queue.

PARAMETER DESCRIPTION queue

The queue to publish the messages to. Can be either a NameRequired object or a string.

TYPE: Union[NameRequired, str]

*publisher_args

Additional arguments to be passed to the publisher.

TYPE: Any DEFAULT: ()

**publisher_kwargs

Additional keyword arguments to be passed to the publisher.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

An instance of BasePublisher that can be used to publish messages to the specified queue.

Source code in faststream/broker/fastapi/router.py
def publisher(\n    self,\n    queue: Union[NameRequired, str],\n    *publisher_args: Any,\n    **publisher_kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes messages to a queue.\n\n    Args:\n        queue: The queue to publish the messages to. Can be either a `NameRequired` object or a string.\n        *publisher_args: Additional arguments to be passed to the publisher.\n        **publisher_kwargs: Additional keyword arguments to be passed to the publisher.\n\n    Returns:\n        An instance of `BasePublisher` that can be used to publish messages to the specified queue.\n\n    \"\"\"\n    return self.broker.publisher(\n        queue,\n        *publisher_args,\n        **publisher_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.subscriber","title":"subscriber","text":"
subscriber(\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function decorator for subscribing to a message queue.

PARAMETER DESCRIPTION path

The path to subscribe to. Can be a string or a NameRequired object.

*extra

Additional path segments. Can be a NameRequired object or a string.

DEFAULT: ()

dependencies

Optional sequence of dependencies.

DEFAULT: None

**broker_kwargs

Additional keyword arguments for the broker.

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable decorator that adds the decorated function as an endpoint for the specified path.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def subscriber(\n    self,\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function decorator for subscribing to a message queue.\n\n    Args:\n        path : The path to subscribe to. Can be a string or a `NameRequired` object.\n        *extra : Additional path segments. Can be a `NameRequired` object or a string.\n        dependencies : Optional sequence of dependencies.\n        **broker_kwargs : Additional keyword arguments for the broker.\n\n    Returns:\n        A callable decorator that adds the decorated function as an endpoint for the specified path.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    def decorator(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n        \"\"\"A decorator function.\n\n        Args:\n            func: The function to be decorated.\n\n        Returns:\n            The decorated function.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        return self.add_api_mq_route(\n            path,\n            *extra,\n            endpoint=func,\n            dependencies=current_dependencies,\n            **broker_kwargs,\n        )\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/context/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/context/Context/#faststream.broker.fastapi.context.Context","title":"faststream.broker.fastapi.context.Context","text":"
Context(name: str) -> Any\n
Source code in faststream/broker/fastapi/context.py
def Context(name: str) -> Any:\n    return params.Depends(\n        lambda: context.resolve(name),\n        use_cache=True,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/","title":"StreamMessage","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage","title":"faststream.broker.fastapi.route.StreamMessage","text":"
StreamMessage(\n    *,\n    body: Union[AnyDict, List[Any]],\n    headers: AnyDict,\n    path: AnyDict\n)\n

Bases: Request

A class to represent a stream message.

METHOD DESCRIPTION __init__

initializes the StreamMessage object

get_session

returns a callable function that handles the session of the message

Initialize a class instance.

PARAMETER DESCRIPTION body

The body of the request as a dictionary.

TYPE: Union[AnyDict, List[Any]]

headers

The headers of the request as a dictionary.

TYPE: AnyDict

Source code in faststream/broker/fastapi/route.py
def __init__(\n    self,\n    *,\n    body: Union[AnyDict, List[Any]],\n    headers: AnyDict,\n    path: AnyDict,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        body: The body of the request as a dictionary.\n        headers: The headers of the request as a dictionary.\n\n    Attributes:\n        scope: A dictionary to store the scope of the request.\n        _cookies: A dictionary to store the cookies of the request.\n        _headers: A dictionary to store the headers of the request.\n        _body: A dictionary to store the body of the request.\n        _query_params: A dictionary to store the query parameters of the request.\n\n    \"\"\"\n    self._headers = headers\n    self._body = body\n    self._query_params = path\n\n    self.scope = {\"path_params\": self._query_params}\n    self._cookies = {}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.app","title":"app property","text":"
app: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.auth","title":"auth property","text":"
auth: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.base_url","title":"base_url property","text":"
base_url: URL\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.client","title":"client property","text":"
client: typing.Optional[Address]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.cookies","title":"cookies property","text":"
cookies: typing.Dict[str, str]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.headers","title":"headers property","text":"
headers: Headers\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.method","title":"method property","text":"
method: str\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.path_params","title":"path_params property","text":"
path_params: typing.Dict[str, typing.Any]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.query_params","title":"query_params property","text":"
query_params: QueryParams\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.receive","title":"receive property","text":"
receive: Receive\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.scope","title":"scope instance-attribute","text":"
scope: AnyDict = {'path_params': self._query_params}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.session","title":"session property","text":"
session: typing.Dict[str, typing.Any]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.state","title":"state property","text":"
state: State\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.url","title":"url property","text":"
url: URL\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.user","title":"user property","text":"
user: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.body","title":"body async","text":"
body() -> bytes\n
Source code in starlette/requests.py
async def body(self) -> bytes:\n    if not hasattr(self, \"_body\"):\n        chunks: \"typing.List[bytes]\" = []\n        async for chunk in self.stream():\n            chunks.append(chunk)\n        self._body = b\"\".join(chunks)\n    return self._body\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.close","title":"close async","text":"
close() -> None\n
Source code in starlette/requests.py
async def close(self) -> None:\n    if self._form is not None:\n        await self._form.close()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.form","title":"form","text":"
form(\n    *,\n    max_files: typing.Union[int, float] = 1000,\n    max_fields: typing.Union[int, float] = 1000\n) -> AwaitableOrContextManager[FormData]\n
Source code in starlette/requests.py
def form(\n    self,\n    *,\n    max_files: typing.Union[int, float] = 1000,\n    max_fields: typing.Union[int, float] = 1000,\n) -> AwaitableOrContextManager[FormData]:\n    return AwaitableOrContextManagerWrapper(\n        self._get_form(max_files=max_files, max_fields=max_fields)\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.get_session","title":"get_session classmethod","text":"
get_session(\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[\n    [NativeMessage[Any]], Awaitable[SendableMessage]\n]\n

Creates a session for handling requests.

PARAMETER DESCRIPTION dependant

The dependant object representing the session.

TYPE: Dependant

dependency_overrides_provider

Optional provider for dependency overrides.

TYPE: Optional[Any] DEFAULT: None

RETURNS DESCRIPTION Callable[[StreamMessage[Any]], Awaitable[SendableMessage]]

A callable that takes a native message and returns an awaitable sendable message.

RAISES DESCRIPTION AssertionError

If the dependant call is not defined.

Note

This function is used to create a session for handling requests. It takes a dependant object, which represents the session, and a dependency overrides provider, which allows for overriding dependencies. It returns a callable that takes a native message and returns an awaitable sendable message. The session is created based on the dependant object and the message passed to the callable. The session is then used to call the function obtained from the dependant object, and the result is returned.

Source code in faststream/broker/fastapi/route.py
@classmethod\ndef get_session(\n    cls,\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[[NativeMessage[Any]], Awaitable[SendableMessage]]:\n    \"\"\"Creates a session for handling requests.\n\n    Args:\n        dependant: The dependant object representing the session.\n        dependency_overrides_provider: Optional provider for dependency overrides.\n\n    Returns:\n        A callable that takes a native message and returns an awaitable sendable message.\n\n    Raises:\n        AssertionError: If the dependant call is not defined.\n\n    Note:\n        This function is used to create a session for handling requests. It takes a dependant object, which represents the session, and a dependency overrides provider, which allows for overriding dependencies. It returns a callable that takes a native message and returns an awaitable sendable message. The session is created based on the dependant object and the message passed to the callable. The session is then used to call the function obtained from the dependant object, and the result is returned.\n\n    \"\"\"\n    assert dependant.call  # nosec B101\n\n    func = get_app(dependant, dependency_overrides_provider)\n\n    dependencies_names = tuple(i.name for i in dependant.dependencies)\n\n    first_arg = next(\n        dropwhile(\n            lambda i: i in dependencies_names,\n            inspect.signature(dependant.call).parameters,\n        ),\n        None,\n    )\n\n    async def app(message: NativeMessage[Any]) -> SendableMessage:\n        \"\"\"An asynchronous function that processes an incoming message and returns a sendable message.\n\n        Args:\n            message : The incoming message to be processed\n\n        Returns:\n            The sendable message\n\n        Raises:\n            TypeError: If the body of the message is not a dictionary\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        body = message.decoded_body\n\n        fastapi_body: Union[AnyDict, List[Any]]\n        if first_arg is not None:\n            if isinstance(body, dict):\n                path = fastapi_body = body or {}\n            elif isinstance(body, list):\n                fastapi_body, path = body, {}\n            else:\n                path = fastapi_body = {first_arg: body}\n\n            session = cls(\n                body=fastapi_body,\n                headers=message.headers,\n                path={**path, **message.path},\n            )\n\n        else:\n            session = cls(\n                body={},\n                headers={},\n                path={},\n            )\n\n        return await func(session)\n\n    return app\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.is_disconnected","title":"is_disconnected async","text":"
is_disconnected() -> bool\n
Source code in starlette/requests.py
async def is_disconnected(self) -> bool:\n    if not self._is_disconnected:\n        message: Message = {}\n\n        # If message isn't immediately available, move on\n        with anyio.CancelScope() as cs:\n            cs.cancel()\n            message = await self._receive()\n\n        if message.get(\"type\") == \"http.disconnect\":\n            self._is_disconnected = True\n\n    return self._is_disconnected\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.json","title":"json async","text":"
json() -> typing.Any\n
Source code in starlette/requests.py
async def json(self) -> typing.Any:\n    if not hasattr(self, \"_json\"):\n        body = await self.body()\n        self._json = json.loads(body)\n    return self._json\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.send_push_promise","title":"send_push_promise async","text":"
send_push_promise(path: str) -> None\n
Source code in starlette/requests.py
async def send_push_promise(self, path: str) -> None:\n    if \"http.response.push\" in self.scope.get(\"extensions\", {}):\n        raw_headers: \"typing.List[typing.Tuple[bytes, bytes]]\" = []\n        for name in SERVER_PUSH_HEADERS_TO_COPY:\n            for value in self.headers.getlist(name):\n                raw_headers.append(\n                    (name.encode(\"latin-1\"), value.encode(\"latin-1\"))\n                )\n        await self._send(\n            {\"type\": \"http.response.push\", \"path\": path, \"headers\": raw_headers}\n        )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.stream","title":"stream async","text":"
stream() -> typing.AsyncGenerator[bytes, None]\n
Source code in starlette/requests.py
async def stream(self) -> typing.AsyncGenerator[bytes, None]:\n    if hasattr(self, \"_body\"):\n        yield self._body\n        yield b\"\"\n        return\n    if self._stream_consumed:\n        raise RuntimeError(\"Stream consumed\")\n    self._stream_consumed = True\n    while True:\n        message = await self._receive()\n        if message[\"type\"] == \"http.request\":\n            body = message.get(\"body\", b\"\")\n            if body:\n                yield body\n            if not message.get(\"more_body\", False):\n                break\n        elif message[\"type\"] == \"http.disconnect\":\n            self._is_disconnected = True\n            raise ClientDisconnect()\n    yield b\"\"\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.url_for","title":"url_for","text":"
url_for(__name: str, **path_params: typing.Any) -> URL\n
Source code in starlette/requests.py
def url_for(self, __name: str, **path_params: typing.Any) -> URL:\n    router: Router = self.scope[\"router\"]\n    url_path = router.url_path_for(__name, **path_params)\n    return url_path.make_absolute_url(base_url=self.base_url)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/","title":"StreamRoute","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute","title":"faststream.broker.fastapi.route.StreamRoute","text":"
StreamRoute(\n    path: Union[NameRequired, str, None],\n    *extra: Union[NameRequired, str],\n    endpoint: Union[\n        Callable[P_HandlerParams, T_HandlerReturn],\n        HandlerCallWrapper[\n            MsgType, P_HandlerParams, T_HandlerReturn\n        ],\n    ],\n    broker: BrokerAsyncUsecase[MsgType, Any],\n    dependencies: Sequence[params.Depends] = (),\n    dependency_overrides_provider: Optional[Any] = None,\n    **handle_kwargs: Any\n)\n

Bases: BaseRoute, Generic[MsgType, P_HandlerParams, T_HandlerReturn]

A class representing a stream route.

Initialize a class instance.

PARAMETER DESCRIPTION path

The path of the instance.

TYPE: Union[NameRequired, str, None]

*extra

Additional arguments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint of the instance.

TYPE: Union[Callable[P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

broker

The broker of the instance.

TYPE: BrokerAsyncUsecase[MsgType, Any]

dependencies

The dependencies of the instance.

TYPE: Sequence[Depends] DEFAULT: ()

dependency_overrides_provider

The provider for dependency overrides.

TYPE: Optional[Any] DEFAULT: None

**handle_kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None.

Source code in faststream/broker/fastapi/route.py
def __init__(\n    self,\n    path: Union[NameRequired, str, None],\n    *extra: Union[NameRequired, str],\n    endpoint: Union[\n        Callable[P_HandlerParams, T_HandlerReturn],\n        HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n    ],\n    broker: BrokerAsyncUsecase[MsgType, Any],\n    dependencies: Sequence[params.Depends] = (),\n    dependency_overrides_provider: Optional[Any] = None,\n    **handle_kwargs: Any,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        path: The path of the instance.\n        *extra: Additional arguments.\n        endpoint: The endpoint of the instance.\n        broker: The broker of the instance.\n        dependencies: The dependencies of the instance.\n        dependency_overrides_provider: The provider for dependency overrides.\n        **handle_kwargs: Additional keyword arguments.\n\n    Returns:\n        None.\n\n    \"\"\"\n    self.path = path or \"\"\n    self.broker = broker\n\n    path_name = self.path if isinstance(self.path, str) else self.path.name\n\n    if isinstance(endpoint, HandlerCallWrapper):\n        orig_call = endpoint._original_call\n    else:\n        orig_call = endpoint\n\n    dependant = get_dependant(\n        path=path_name,\n        call=orig_call,\n    )\n    for depends in dependencies[::-1]:\n        dependant.dependencies.insert(\n            0,\n            get_parameterless_sub_dependant(depends=depends, path=path_name),\n        )\n    self.dependant = dependant\n\n    call = wraps(orig_call)(\n        StreamMessage.get_session(\n            dependant,\n            dependency_overrides_provider,\n        )\n    )\n\n    if isinstance(endpoint, HandlerCallWrapper):\n        endpoint._original_call = call\n        handler = endpoint\n\n    else:\n        handler = call\n\n    self.handler = broker.subscriber(\n        path,\n        *extra,\n        _raw=True,\n        _get_dependant=lambda call: dependant,\n        **handle_kwargs,\n    )(\n        handler  # type: ignore[arg-type]\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.dependant","title":"dependant instance-attribute","text":"
dependant = dependant\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.handler","title":"handler instance-attribute","text":"
handler: HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n] = broker.subscriber(\n    path,\n    *extra,\n    _raw=True,\n    _get_dependant=lambda: dependant,\n    **handle_kwargs\n)(\n    handler\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.path","title":"path instance-attribute","text":"
path = path or ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.handle","title":"handle async","text":"
handle(scope: Scope, receive: Receive, send: Send) -> None\n
Source code in starlette/routing.py
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.matches","title":"matches","text":"
matches(scope: Scope) -> typing.Tuple[Match, Scope]\n
Source code in starlette/routing.py
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/get_app/","title":"get_app","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/route/get_app/#faststream.broker.fastapi.route.get_app","title":"faststream.broker.fastapi.route.get_app","text":"
get_app(\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[\n    [StreamMessage], Coroutine[Any, Any, SendableMessage]\n]\n

Creates a FastAPI application.

PARAMETER DESCRIPTION dependant

The dependant object that defines the endpoint function and its dependencies.

TYPE: Dependant

dependency_overrides_provider

Optional provider for dependency overrides.

TYPE: Optional[Any] DEFAULT: None

RETURNS DESCRIPTION Callable[[StreamMessage], Coroutine[Any, Any, SendableMessage]]

The FastAPI application as a callable that takes a StreamMessage object as input and returns a SendableMessage coroutine.

RAISES DESCRIPTION AssertionError

If the code reaches an unreachable state.

Source code in faststream/broker/fastapi/route.py
def get_app(\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[[StreamMessage], Coroutine[Any, Any, SendableMessage]]:\n    \"\"\"Creates a FastAPI application.\n\n    Args:\n        dependant: The dependant object that defines the endpoint function and its dependencies.\n        dependency_overrides_provider: Optional provider for dependency overrides.\n\n    Returns:\n        The FastAPI application as a callable that takes a StreamMessage object as input and returns a SendableMessage coroutine.\n\n    Raises:\n        AssertionError: If the code reaches an unreachable state.\n\n    \"\"\"\n\n    async def app(request: StreamMessage) -> SendableMessage:\n        \"\"\"Handle an HTTP request and return a response.\n\n        Args:\n            request: The incoming HTTP request.\n\n        Returns:\n            The response to be sent back to the client.\n\n        Raises:\n            AssertionError: If the code reaches an unreachable point.\n\n        \"\"\"\n        async with AsyncExitStack() as stack:\n            request.scope[\"fastapi_astack\"] = stack\n\n            solved_result = await solve_dependencies(\n                request=request,\n                body=request._body,\n                dependant=dependant,\n                dependency_overrides_provider=dependency_overrides_provider,\n            )\n\n            values, errors, _, _2, _3 = solved_result\n            if errors:\n                raise_fastapi_validation_error(errors, request._body)\n\n            return cast(\n                SendableMessage,\n                await run_endpoint_function(\n                    dependant=dependant,\n                    values=values,\n                    is_coroutine=asyncio.iscoroutinefunction(dependant.call),\n                ),\n            )\n\n        raise AssertionError(\"unreachable\")\n\n    return app\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/","title":"StreamRouter","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter","title":"faststream.broker.fastapi.router.StreamRouter","text":"
StreamRouter(\n    *connection_args: Tuple[Any, ...],\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    setup_state: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id),\n    asyncapi_tags: Optional[\n        Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]\n    ] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    **connection_kwars: Any\n)\n

Bases: APIRouter, Generic[MsgType]

A class to route streams.

METHOD DESCRIPTION __init__

initialize the StreamRouter

add_api_mq_route

add a route for API and message queue

subscriber

decorator to define a subscriber

wrap_lifespan

wrap the lifespan of the router

after_startup

decorator to define a function to be executed after startup

publisher

create a publisher for the broker

asyncapi_router

create an APIRouter for AsyncAPI documentation

include_router

include another router in the StreamRouter

_setup_log_context

setup log context for the broker

Initialize an instance of a class.

PARAMETER DESCRIPTION *connection_args

Variable length arguments for the connection

TYPE: Tuple[Any, ...] DEFAULT: ()

prefix

Prefix for the class

TYPE: str DEFAULT: ''

tags

Optional list of tags for the class

TYPE: Optional[List[Union[str, Enum]]] DEFAULT: None

dependencies

Optional sequence of dependencies for the class

TYPE: Optional[Sequence[Depends]] DEFAULT: None

default_response_class

Default response class for the class

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

Optional dictionary of responses for the class

TYPE: Optional[Dict[Union[int, str], AnyDict]] DEFAULT: None

callbacks

Optional list of callbacks for the class

TYPE: Optional[List[BaseRoute]] DEFAULT: None

routes

Optional list of routes for the class

TYPE: Optional[List[BaseRoute]] DEFAULT: None

redirect_slashes

Boolean value indicating whether to redirect slashes

TYPE: bool DEFAULT: True

default

Optional default value for the class

TYPE: Optional[ASGIApp] DEFAULT: None

dependency_overrides_provider

Optional provider for dependency overrides

TYPE: Optional[Any] DEFAULT: None

route_class

Route class for the class

TYPE: Type[APIRoute] DEFAULT: APIRoute

on_startup

Optional sequence of functions to run on startup

TYPE: Optional[Sequence[Callable[[], Any]]] DEFAULT: None

on_shutdown

Optional sequence of functions to run on shutdown

TYPE: Optional[Sequence[Callable[[], Any]]] DEFAULT: None

deprecated

Optional boolean value indicating whether the class is deprecated

TYPE: Optional[bool] DEFAULT: None

include_in_schema

Boolean value indicating whether to include the class in the schema

TYPE: bool DEFAULT: True

setup_state

Boolean value indicating whether to setup state

TYPE: bool DEFAULT: True

lifespan

Optional lifespan for the class

TYPE: Optional[Lifespan[Any]] DEFAULT: None

generate_unique_id_function

Function to generate unique ID for the class

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

asyncapi_tags

Optional sequence of asyncapi tags for the class schema

TYPE: Optional[Sequence[Union[Tag, TagDict]]] DEFAULT: None

Source code in faststream/broker/fastapi/router.py
def __init__(\n    self,\n    *connection_args: Tuple[Any, ...],\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[Sequence[Callable[[], Any]]] = None,\n    on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    setup_state: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n    # AsyncAPI information\n    asyncapi_tags: Optional[Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    **connection_kwars: Any,\n) -> None:\n    \"\"\"Initialize an instance of a class.\n\n    Args:\n        *connection_args: Variable length arguments for the connection\n        prefix: Prefix for the class\n        tags: Optional list of tags for the class\n        dependencies: Optional sequence of dependencies for the class\n        default_response_class: Default response class for the class\n        responses: Optional dictionary of responses for the class\n        callbacks: Optional list of callbacks for the class\n        routes: Optional list of routes for the class\n        redirect_slashes: Boolean value indicating whether to redirect slashes\n        default: Optional default value for the class\n        dependency_overrides_provider: Optional provider for dependency overrides\n        route_class: Route class for the class\n        on_startup: Optional sequence of functions to run on startup\n        on_shutdown: Optional sequence of functions to run on shutdown\n        deprecated: Optional boolean value indicating whether the class is deprecated\n        include_in_schema: Boolean value indicating whether to include the class in the schema\n        setup_state: Boolean value indicating whether to setup state\n        lifespan: Optional lifespan for the class\n        generate_unique_id_function: Function to generate unique ID for the class\n        asyncapi_tags: Optional sequence of asyncapi tags for the class schema\n\n    \"\"\"\n    assert (  # nosec B101\n        self.broker_class\n    ), \"You should specify `broker_class` at your implementation\"\n\n    self.broker = self.broker_class(\n        *connection_args,\n        apply_types=False,\n        tags=asyncapi_tags,\n        **connection_kwars,\n    )\n\n    self.setup_state = setup_state\n\n    # AsyncAPI information\n    # Empty\n    self.terms_of_service = None\n    self.identifier = None\n    self.asyncapi_tags = None\n    self.external_docs = None\n    # parse from FastAPI app on startup\n    self.title = \"\"\n    self.version = \"\"\n    self.description = \"\"\n    self.license = None\n    self.contact = None\n\n    self.schema = None\n\n    super().__init__(\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        routes=routes,\n        redirect_slashes=redirect_slashes,\n        default=default,\n        dependency_overrides_provider=dependency_overrides_provider,\n        route_class=route_class,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n        lifespan=self.wrap_lifespan(lifespan),\n        on_startup=on_startup,\n        on_shutdown=on_shutdown,\n    )\n\n    self.docs_router = self.asyncapi_router(schema_url)\n\n    self._after_startup_hooks = []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.broker","title":"broker instance-attribute","text":"
broker: BrokerAsyncUsecase[\n    MsgType, Any\n] = self.broker_class(\n    *connection_args,\n    apply_types=False,\n    tags=asyncapi_tags,\n    **connection_kwars\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.broker_class","title":"broker_class instance-attribute","text":"
broker_class: Type[BrokerAsyncUsecase[MsgType, Any]]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any\n) -> HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n]\n

Add an API message queue route.

PARAMETER DESCRIPTION path

The path of the route.

TYPE: Union[NameRequired, str]

*extra

Additional path segments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint function to be called for this route.

TYPE: Callable[P_HandlerParams, T_HandlerReturn]

dependencies

The dependencies required by the endpoint function.

TYPE: Sequence[Depends]

**broker_kwargs

Additional keyword arguments to be passed to the broker.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]

The handler call wrapper for the route.

Source code in faststream/broker/fastapi/router.py
def add_api_mq_route(\n    self,\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any,\n) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n    \"\"\"Add an API message queue route.\n\n    Args:\n        path: The path of the route.\n        *extra: Additional path segments.\n        endpoint: The endpoint function to be called for this route.\n        dependencies: The dependencies required by the endpoint function.\n        **broker_kwargs: Additional keyword arguments to be passed to the broker.\n\n    Returns:\n        The handler call wrapper for the route.\n\n    \"\"\"\n    route: StreamRoute[MsgType, P_HandlerParams, T_HandlerReturn] = StreamRoute(\n        path,\n        *extra,\n        endpoint=endpoint,\n        dependencies=dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        broker=self.broker,\n        **broker_kwargs,\n    )\n    self.routes.append(route)\n    return route.handler\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.publisher","title":"publisher","text":"
publisher(\n    queue: Union[NameRequired, str],\n    *publisher_args: Any,\n    **publisher_kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes messages to a queue.

PARAMETER DESCRIPTION queue

The queue to publish the messages to. Can be either a NameRequired object or a string.

TYPE: Union[NameRequired, str]

*publisher_args

Additional arguments to be passed to the publisher.

TYPE: Any DEFAULT: ()

**publisher_kwargs

Additional keyword arguments to be passed to the publisher.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

An instance of BasePublisher that can be used to publish messages to the specified queue.

Source code in faststream/broker/fastapi/router.py
def publisher(\n    self,\n    queue: Union[NameRequired, str],\n    *publisher_args: Any,\n    **publisher_kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes messages to a queue.\n\n    Args:\n        queue: The queue to publish the messages to. Can be either a `NameRequired` object or a string.\n        *publisher_args: Additional arguments to be passed to the publisher.\n        **publisher_kwargs: Additional keyword arguments to be passed to the publisher.\n\n    Returns:\n        An instance of `BasePublisher` that can be used to publish messages to the specified queue.\n\n    \"\"\"\n    return self.broker.publisher(\n        queue,\n        *publisher_args,\n        **publisher_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.subscriber","title":"subscriber","text":"
subscriber(\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function decorator for subscribing to a message queue.

PARAMETER DESCRIPTION path

The path to subscribe to. Can be a string or a NameRequired object.

*extra

Additional path segments. Can be a NameRequired object or a string.

DEFAULT: ()

dependencies

Optional sequence of dependencies.

DEFAULT: None

**broker_kwargs

Additional keyword arguments for the broker.

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable decorator that adds the decorated function as an endpoint for the specified path.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def subscriber(\n    self,\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function decorator for subscribing to a message queue.\n\n    Args:\n        path : The path to subscribe to. Can be a string or a `NameRequired` object.\n        *extra : Additional path segments. Can be a `NameRequired` object or a string.\n        dependencies : Optional sequence of dependencies.\n        **broker_kwargs : Additional keyword arguments for the broker.\n\n    Returns:\n        A callable decorator that adds the decorated function as an endpoint for the specified path.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    def decorator(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n        \"\"\"A decorator function.\n\n        Args:\n            func: The function to be decorated.\n\n        Returns:\n            The decorated function.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        return self.add_api_mq_route(\n            path,\n            *extra,\n            endpoint=func,\n            dependencies=current_dependencies,\n            **broker_kwargs,\n        )\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/","title":"AsyncHandler","text":"","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler","title":"faststream.broker.handler.AsyncHandler","text":"
AsyncHandler(\n    *,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    graceful_timeout: Optional[float] = None\n)\n

Bases: BaseHandler[MsgType]

A class representing an asynchronous handler.

METHOD DESCRIPTION add_call

adds a new call to the list of calls

consume

consumes a message and returns a sendable message

start

starts the handler

close

closes the handler

Source code in faststream/broker/handler.py
def __init__(\n    self,\n    *,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    graceful_timeout: Optional[float] = None,\n) -> None:\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n    )\n    self.lock = MultiLock()\n    self.graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n    parser: CustomParser[MsgType, Any],\n    decoder: CustomDecoder[Any],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    filter: Filter[StreamMessage[MsgType]],\n    middlewares: Optional[\n        Sequence[Callable[[Any], BaseMiddleware]]\n    ]\n) -> None\n

Adds a call to the handler.

PARAMETER DESCRIPTION handler

The handler call wrapper.

TYPE: HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]

parser

The custom parser.

TYPE: CustomParser[MsgType, Any]

decoder

The custom decoder.

TYPE: CustomDecoder[Any]

dependant

The call model.

TYPE: CallModel[P_HandlerParams, T_HandlerReturn]

filter

The filter for stream messages.

TYPE: Filter[StreamMessage[MsgType]]

middlewares

Optional sequence of middlewares.

TYPE: Optional[Sequence[Callable[[Any], BaseMiddleware]]]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n    parser: CustomParser[MsgType, Any],\n    decoder: CustomDecoder[Any],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    filter: Filter[StreamMessage[MsgType]],\n    middlewares: Optional[Sequence[Callable[[Any], BaseMiddleware]]],\n) -> None:\n    \"\"\"Adds a call to the handler.\n\n    Args:\n        handler: The handler call wrapper.\n        parser: The custom parser.\n        decoder: The custom decoder.\n        dependant: The call model.\n        filter: The filter for stream messages.\n        middlewares: Optional sequence of middlewares.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.calls.append(\n        (\n            handler,\n            to_async(filter),\n            to_async(parser) if parser else None,  # type: ignore[arg-type]\n            to_async(decoder) if decoder else None,  # type: ignore[arg-type]\n            middlewares or (),\n            dependant,\n        )\n    )\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.close","title":"close abstractmethod async","text":"
close() -> None\n
Source code in faststream/broker/handler.py
@abstractmethod\nasync def close(self) -> None:\n    self.running = False\n    await self.lock.wait_release(self.graceful_timeout)\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.start","title":"start abstractmethod async","text":"
start() -> None\n
Source code in faststream/broker/handler.py
@abstractmethod\nasync def start(self) -> None:\n    self.running = True\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/","title":"BaseHandler","text":"","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler","title":"faststream.broker.handler.BaseHandler","text":"
BaseHandler(\n    *,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True\n)\n

Bases: AsyncAPIOperation, Generic[MsgType]

A base handler class for asynchronous API operations.

METHOD DESCRIPTION __init__

Initializes the BaseHandler object.

name

Returns the name of the handler.

call_name

Returns the name of the handler call.

description

Returns the description of the handler.

consume

Abstract method to consume a message.

Note: This class inherits from AsyncAPIOperation and is a generic class with type parameter MsgType.

Initialize a new instance of the class.

PARAMETER DESCRIPTION description

Optional description of the instance.

TYPE: Optional[str] DEFAULT: None

title

Optional title of the instance.

TYPE: Optional[str] DEFAULT: None

Source code in faststream/broker/handler.py
def __init__(\n    self,\n    *,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    \"\"\"Initialize a new instance of the class.\n\n    Args:\n        description: Optional description of the instance.\n        title: Optional title of the instance.\n\n    \"\"\"\n    self.calls = []  # type: ignore[assignment]\n    self.global_middlewares = []\n\n    self.log_context_builder = log_context_builder\n    self.running = False\n\n    # AsyncAPI information\n    self._description = description\n    self._title = title\n    self.include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.calls","title":"calls instance-attribute","text":"
calls: Union[\n    List[\n        Tuple[\n            HandlerCallWrapper[\n                MsgType, Any, SendableMessage\n            ],\n            Callable[[StreamMessage[MsgType]], bool],\n            SyncParser[MsgType, StreamMessage[MsgType]],\n            SyncDecoder[StreamMessage[MsgType]],\n            Sequence[Callable[[Any], BaseMiddleware]],\n            CallModel[Any, SendableMessage],\n        ]\n    ],\n    List[\n        Tuple[\n            HandlerCallWrapper[\n                MsgType, Any, SendableMessage\n            ],\n            Callable[\n                [StreamMessage[MsgType]], Awaitable[bool]\n            ],\n            AsyncParser[MsgType, StreamMessage[MsgType]],\n            AsyncDecoder[StreamMessage[MsgType]],\n            Sequence[Callable[[Any], BaseMiddleware]],\n            CallModel[Any, SendableMessage],\n        ]\n    ],\n] = []\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.consume","title":"consume abstractmethod","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/handler.py
@abstractmethod\ndef consume(self, msg: MsgType) -> SendableMessage:\n    \"\"\"Consume a message.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/","title":"MultiLock","text":"","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/#faststream.broker.handler.MultiLock","title":"faststream.broker.handler.MultiLock","text":"
MultiLock()\n
Source code in faststream/broker/handler.py
def __init__(self) -> None:\n    self.queue: \"asyncio.Queue[None]\" = asyncio.Queue()\n
","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/#faststream.broker.handler.MultiLock.empty","title":"empty property","text":"
empty: bool\n
","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/#faststream.broker.handler.MultiLock.qsize","title":"qsize property","text":"
qsize: int\n
","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/#faststream.broker.handler.MultiLock.queue","title":"queue instance-attribute","text":"
queue: asyncio.Queue[None] = asyncio.Queue()\n
","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/#faststream.broker.handler.MultiLock.wait_release","title":"wait_release async","text":"
wait_release(timeout: Optional[float] = None) -> None\n
Source code in faststream/broker/handler.py
async def wait_release(self, timeout: Optional[float] = None) -> None:\n    if timeout:\n        with anyio.move_on_after(timeout):\n            await self.queue.join()\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/","title":"ABCStreamMessage","text":"","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage","title":"faststream.broker.message.ABCStreamMessage dataclass","text":"

Bases: Generic[Msg]

A generic class to represent a stream message.

","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/","title":"StreamMessage","text":"","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage","title":"faststream.broker.message.StreamMessage","text":"

Bases: ABCStreamMessage[Msg]

","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.ack","title":"ack async","text":"
ack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def ack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.nack","title":"nack async","text":"
nack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def nack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.reject","title":"reject async","text":"
reject(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def reject(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/","title":"SyncStreamMessage","text":"","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage","title":"faststream.broker.message.SyncStreamMessage","text":"

Bases: ABCStreamMessage[Msg]

","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.ack","title":"ack","text":"
ack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
def ack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.nack","title":"nack","text":"
nack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
def nack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.reject","title":"reject","text":"
reject(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
def reject(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/","title":"BaseMiddleware","text":"","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware","title":"faststream.broker.middlewares.BaseMiddleware","text":"
BaseMiddleware(msg: Any)\n

A base middleware class.

METHOD DESCRIPTION on_receive

Called when a message is received.

after_processed

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) -> Optional[bool]: Called after processing a message.

__aenter__

Called when entering a context.

__aexit__

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) -> Optional[bool]: Called when exiting a context.

on_consume

DecodedMessage) -> DecodedMessage: Called before consuming a message.

after_consume

Optional[Exception]) -> None: Called after consuming a message.

consume_scope

DecodedMessage) -> AsyncIterator[DecodedMessage]: Context manager for consuming a message.

on_publish

SendableMessage) -> SendableMessage: Called before publishing a message.

after_publish

Optional[Exception]) -> None: Asynchronous function to handle the after publish event.

Initialize the class.

PARAMETER DESCRIPTION msg

Any message to be stored.

TYPE: Any

Source code in faststream/broker/middlewares.py
def __init__(self, msg: Any) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        msg: Any message to be stored.\n    \"\"\"\n    self.msg = msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.msg","title":"msg instance-attribute","text":"
msg = msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.after_consume","title":"after_consume async","text":"
after_consume(err: Optional[Exception]) -> None\n

A function to handle the result of consuming a resource asynchronously.

PARAMETER DESCRIPTION err

Optional exception that occurred during consumption

RAISES DESCRIPTION err

If an exception occurred during consumption

Source code in faststream/broker/middlewares.py
async def after_consume(self, err: Optional[Exception]) -> None:\n    \"\"\"A function to handle the result of consuming a resource asynchronously.\n\n    Args:\n        err : Optional exception that occurred during consumption\n\n    Raises:\n        err : If an exception occurred during consumption\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.after_processed","title":"after_processed async","text":"
after_processed(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> Optional[bool]\n

Asynchronously called after processing.

PARAMETER DESCRIPTION exc_type

Optional exception type

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

Optional exception value

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

Optional traceback

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION Optional[bool]

Optional boolean value indicating whether the processing was successful or not.

Source code in faststream/broker/middlewares.py
async def after_processed(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> Optional[bool]:\n    \"\"\"Asynchronously called after processing.\n\n    Args:\n        exc_type: Optional exception type\n        exc_val: Optional exception value\n        exec_tb: Optional traceback\n\n    Returns:\n        Optional boolean value indicating whether the processing was successful or not.\n    \"\"\"\n    return False\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.after_publish","title":"after_publish async","text":"
after_publish(err: Optional[Exception]) -> None\n

Asynchronous function to handle the after publish event.

PARAMETER DESCRIPTION err

Optional exception that occurred during the publish

TYPE: Optional[Exception]

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION Exception

If an error occurred during the publish

Source code in faststream/broker/middlewares.py
async def after_publish(self, err: Optional[Exception]) -> None:\n    \"\"\"Asynchronous function to handle the after publish event.\n\n    Args:\n        err: Optional exception that occurred during the publish\n\n    Returns:\n        None\n\n    Raises:\n        Exception: If an error occurred during the publish\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.consume_scope","title":"consume_scope async","text":"
consume_scope(\n    msg: DecodedMessage,\n) -> AsyncIterator[DecodedMessage]\n

Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.

PARAMETER DESCRIPTION msg

The decoded message to consume.

TYPE: DecodedMessage

YIELDS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RETURNS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RAISES DESCRIPTION Exception

If an error occurs while consuming the message.

AsyncIterator

An asynchronous iterator that yields decoded messages.

Note

This function is an async function.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def consume_scope(self, msg: DecodedMessage) -> AsyncIterator[DecodedMessage]:\n    \"\"\"Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.\n\n    Args:\n        msg: The decoded message to consume.\n\n    Yields:\n        An asynchronous iterator of decoded messages.\n\n    Returns:\n        An asynchronous iterator of decoded messages.\n\n    Raises:\n        Exception: If an error occurs while consuming the message.\n\n    AsyncIterator:\n        An asynchronous iterator that yields decoded messages.\n\n    Note:\n        This function is an async function.\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_consume(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_consume(err)\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.on_consume","title":"on_consume async","text":"
on_consume(msg: DecodedMessage) -> DecodedMessage\n

Asynchronously consumes a message.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: DecodedMessage

RETURNS DESCRIPTION DecodedMessage

The consumed message.

Source code in faststream/broker/middlewares.py
async def on_consume(self, msg: DecodedMessage) -> DecodedMessage:\n    \"\"\"Asynchronously consumes a message.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The consumed message.\n    \"\"\"\n    return msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.on_publish","title":"on_publish async","text":"
on_publish(msg: SendableMessage) -> SendableMessage\n

Asynchronously handle a publish event.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

RETURNS DESCRIPTION SendableMessage

The published message.

Source code in faststream/broker/middlewares.py
async def on_publish(self, msg: SendableMessage) -> SendableMessage:\n    \"\"\"Asynchronously handle a publish event.\n\n    Args:\n        msg: The message to be published.\n\n    Returns:\n        The published message.\n    \"\"\"\n    return msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.on_receive","title":"on_receive async","text":"
on_receive() -> None\n
Source code in faststream/broker/middlewares.py
async def on_receive(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.publish_scope","title":"publish_scope async","text":"
publish_scope(\n    msg: SendableMessage,\n) -> AsyncIterator[SendableMessage]\n

Publish a message and return an async iterator.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

YIELDS DESCRIPTION AsyncIterator[SendableMessage]

A sendable message.

RETURNS DESCRIPTION AsyncIterator[SendableMessage]

An async iterator of sendable messages.

RAISES DESCRIPTION Exception

If an error occurs during publishing.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def publish_scope(\n    self, msg: SendableMessage\n) -> AsyncIterator[SendableMessage]:\n    \"\"\"Publish a message and return an async iterator.\n\n    Args:\n        msg: The message to be published.\n\n    Yields:\n        A sendable message.\n\n    Returns:\n        An async iterator of sendable messages.\n\n    Raises:\n        Exception: If an error occurs during publishing.\n\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_publish(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_publish(err)\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/","title":"CriticalLogMiddleware","text":"","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware","title":"faststream.broker.middlewares.CriticalLogMiddleware","text":"
CriticalLogMiddleware(\n    logger: Optional[logging.Logger], log_level: int\n)\n

Bases: BaseMiddleware

A middleware class for logging critical errors.

PARAMETER DESCRIPTION logger

The logger object to use for logging

TYPE: Optional[Logger]

METHOD DESCRIPTION __call__

Any) -> Self: Returns the middleware instance

after_processed

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) -> bool: Logs critical errors if they occur and returns True

Initialize the class.

PARAMETER DESCRIPTION logger

an instance of the logging.Logger class

TYPE: Optional[Logger]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/middlewares.py
def __init__(\n    self,\n    logger: Optional[logging.Logger],\n    log_level: int,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        logger: an instance of the logging.Logger class\n\n    Returns:\n        None\n    \"\"\"\n    self.logger = logger\n    self.log_level = log_level\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.msg","title":"msg instance-attribute","text":"
msg = msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.after_consume","title":"after_consume async","text":"
after_consume(err: Optional[Exception]) -> None\n

A function to handle the result of consuming a resource asynchronously.

PARAMETER DESCRIPTION err

Optional exception that occurred during consumption

RAISES DESCRIPTION err

If an exception occurred during consumption

Source code in faststream/broker/middlewares.py
async def after_consume(self, err: Optional[Exception]) -> None:\n    \"\"\"A function to handle the result of consuming a resource asynchronously.\n\n    Args:\n        err : Optional exception that occurred during consumption\n\n    Raises:\n        err : If an exception occurred during consumption\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.after_processed","title":"after_processed async","text":"
after_processed(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> bool\n

Asynchronously called after processing.

PARAMETER DESCRIPTION exc_type

Type of the exception raised during processing.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

Value of the exception raised during processing.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

Traceback of the exception raised during processing.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION bool

True if the method is successfully executed.

TYPE: bool

Source code in faststream/broker/middlewares.py
async def after_processed(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> bool:\n    \"\"\"Asynchronously called after processing.\n\n    Args:\n        exc_type (Optional[Type[BaseException]]): Type of the exception raised during processing.\n        exc_val (Optional[BaseException]): Value of the exception raised during processing.\n        exec_tb (Optional[TracebackType]): Traceback of the exception raised during processing.\n\n    Returns:\n        bool: True if the method is successfully executed.\n    \"\"\"\n    if self.logger is not None:\n        c = context.get_local(\"log_context\")\n\n        if exc_type and exc_val:\n            self.logger.error(\n                f\"{exc_type.__name__}: {exc_val}\",\n                exc_info=exc_val,\n                extra=c,\n            )\n\n        self.logger.log(self.log_level, \"Processed\", extra=c)\n    return True\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.after_publish","title":"after_publish async","text":"
after_publish(err: Optional[Exception]) -> None\n

Asynchronous function to handle the after publish event.

PARAMETER DESCRIPTION err

Optional exception that occurred during the publish

TYPE: Optional[Exception]

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION Exception

If an error occurred during the publish

Source code in faststream/broker/middlewares.py
async def after_publish(self, err: Optional[Exception]) -> None:\n    \"\"\"Asynchronous function to handle the after publish event.\n\n    Args:\n        err: Optional exception that occurred during the publish\n\n    Returns:\n        None\n\n    Raises:\n        Exception: If an error occurred during the publish\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.consume_scope","title":"consume_scope async","text":"
consume_scope(\n    msg: DecodedMessage,\n) -> AsyncIterator[DecodedMessage]\n

Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.

PARAMETER DESCRIPTION msg

The decoded message to consume.

TYPE: DecodedMessage

YIELDS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RETURNS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RAISES DESCRIPTION Exception

If an error occurs while consuming the message.

AsyncIterator

An asynchronous iterator that yields decoded messages.

Note

This function is an async function.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def consume_scope(self, msg: DecodedMessage) -> AsyncIterator[DecodedMessage]:\n    \"\"\"Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.\n\n    Args:\n        msg: The decoded message to consume.\n\n    Yields:\n        An asynchronous iterator of decoded messages.\n\n    Returns:\n        An asynchronous iterator of decoded messages.\n\n    Raises:\n        Exception: If an error occurs while consuming the message.\n\n    AsyncIterator:\n        An asynchronous iterator that yields decoded messages.\n\n    Note:\n        This function is an async function.\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_consume(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_consume(err)\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.on_consume","title":"on_consume async","text":"
on_consume(msg: DecodedMessage) -> DecodedMessage\n
Source code in faststream/broker/middlewares.py
async def on_consume(self, msg: DecodedMessage) -> DecodedMessage:\n    if self.logger is not None:\n        c = context.get_local(\"log_context\")\n        self.logger.log(self.log_level, \"Received\", extra=c)\n\n    return await super().on_consume(msg)\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.on_publish","title":"on_publish async","text":"
on_publish(msg: SendableMessage) -> SendableMessage\n

Asynchronously handle a publish event.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

RETURNS DESCRIPTION SendableMessage

The published message.

Source code in faststream/broker/middlewares.py
async def on_publish(self, msg: SendableMessage) -> SendableMessage:\n    \"\"\"Asynchronously handle a publish event.\n\n    Args:\n        msg: The message to be published.\n\n    Returns:\n        The published message.\n    \"\"\"\n    return msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.on_receive","title":"on_receive async","text":"
on_receive() -> None\n
Source code in faststream/broker/middlewares.py
async def on_receive(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.publish_scope","title":"publish_scope async","text":"
publish_scope(\n    msg: SendableMessage,\n) -> AsyncIterator[SendableMessage]\n

Publish a message and return an async iterator.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

YIELDS DESCRIPTION AsyncIterator[SendableMessage]

A sendable message.

RETURNS DESCRIPTION AsyncIterator[SendableMessage]

An async iterator of sendable messages.

RAISES DESCRIPTION Exception

If an error occurs during publishing.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def publish_scope(\n    self, msg: SendableMessage\n) -> AsyncIterator[SendableMessage]:\n    \"\"\"Publish a message and return an async iterator.\n\n    Args:\n        msg: The message to be published.\n\n    Yields:\n        A sendable message.\n\n    Returns:\n        An async iterator of sendable messages.\n\n    Raises:\n        Exception: If an error occurs during publishing.\n\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_publish(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_publish(err)\n
","boost":0.5},{"location":"api/faststream/broker/parsers/decode_message/","title":"decode_message","text":"","boost":0.5},{"location":"api/faststream/broker/parsers/decode_message/#faststream.broker.parsers.decode_message","title":"faststream.broker.parsers.decode_message","text":"
decode_message(\n    message: StreamMessage[Any],\n) -> DecodedMessage\n

Decodes a message.

PARAMETER DESCRIPTION message

The message to decode.

TYPE: StreamMessage[Any]

RETURNS DESCRIPTION DecodedMessage

The decoded message.

RAISES DESCRIPTION JSONDecodeError

If the message body cannot be decoded as JSON.

Source code in faststream/broker/parsers.py
def decode_message(message: StreamMessage[Any]) -> DecodedMessage:\n    \"\"\"Decodes a message.\n\n    Args:\n        message: The message to decode.\n\n    Returns:\n        The decoded message.\n\n    Raises:\n        JSONDecodeError: If the message body cannot be decoded as JSON.\n\n    \"\"\"\n    body: Any = getattr(message, \"body\", message)\n    m: DecodedMessage = body\n\n    if content_type := getattr(message, \"content_type\", None):\n        if ContentTypes.text.value in content_type:\n            m = body.decode()\n        elif ContentTypes.json.value in content_type:  # pragma: no branch\n            m = json.loads(body)\n\n    else:\n        with suppress(json.JSONDecodeError):\n            m = json.loads(body)\n\n    return m\n
","boost":0.5},{"location":"api/faststream/broker/parsers/encode_message/","title":"encode_message","text":"","boost":0.5},{"location":"api/faststream/broker/parsers/encode_message/#faststream.broker.parsers.encode_message","title":"faststream.broker.parsers.encode_message","text":"
encode_message(\n    msg: SendableMessage,\n) -> Tuple[bytes, Optional[ContentType]]\n

Encodes a message.

PARAMETER DESCRIPTION msg

The message to be encoded.

TYPE: SendableMessage

RETURNS DESCRIPTION Tuple[bytes, Optional[ContentType]]

A tuple containing the encoded message as bytes and the content type of the message.

Source code in faststream/broker/parsers.py
def encode_message(msg: SendableMessage) -> Tuple[bytes, Optional[ContentType]]:\n    \"\"\"Encodes a message.\n\n    Args:\n        msg: The message to be encoded.\n\n    Returns:\n        A tuple containing the encoded message as bytes and the content type of the message.\n\n    \"\"\"\n    if msg is None:\n        return b\"\", None\n\n    if isinstance(msg, bytes):\n        return msg, None\n\n    if isinstance(msg, str):\n        return msg.encode(), ContentTypes.text.value\n\n    return (\n        dump_json(msg).encode(),\n        ContentTypes.json.value,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/parsers/resolve_custom_func/","title":"resolve_custom_func","text":"","boost":0.5},{"location":"api/faststream/broker/parsers/resolve_custom_func/#faststream.broker.parsers.resolve_custom_func","title":"faststream.broker.parsers.resolve_custom_func","text":"
resolve_custom_func(\n    custom_func: Optional[\n        Union[\n            CustomDecoder[StreamMsg],\n            CustomParser[MsgType, StreamMsg],\n        ]\n    ],\n    default_func: Union[\n        Decoder[StreamMsg], Parser[MsgType, StreamMsg]\n    ],\n) -> Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]]\n

Resolve a custom function.

PARAMETER DESCRIPTION custom_func

Optional custom function of type CustomDecoder or CustomParser.

TYPE: Optional[Union[CustomDecoder[StreamMsg], CustomParser[MsgType, StreamMsg]]]

default_func

Default function of type Decoder or Parser.

TYPE: Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]]

RETURNS DESCRIPTION Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]]

The resolved function of type Decoder or Parser.

Source code in faststream/broker/parsers.py
def resolve_custom_func(  # type: ignore[misc]\n    custom_func: Optional[\n        Union[CustomDecoder[StreamMsg], CustomParser[MsgType, StreamMsg]]\n    ],\n    default_func: Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]],\n) -> Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]]:\n    \"\"\"Resolve a custom function.\n\n    Args:\n        custom_func: Optional custom function of type CustomDecoder or CustomParser.\n        default_func: Default function of type Decoder or Parser.\n\n    Returns:\n        The resolved function of type Decoder or Parser.\n\n    \"\"\"\n    if custom_func is None:\n        return default_func\n\n    original_params = inspect.signature(custom_func).parameters\n    if len(original_params) == 1:\n        return cast(Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]], custom_func)\n\n    else:\n        name = tuple(original_params.items())[1][0]\n        return partial(custom_func, **{name: default_func})  # type: ignore\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/","title":"BasePublisher","text":"","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher","title":"faststream.broker.publisher.BasePublisher dataclass","text":"

Bases: AsyncAPIOperation, Generic[MsgType]

A base class for publishers in an asynchronous API.

METHOD DESCRIPTION description

returns the description of the publisher

__call__

decorator to register a function as a handler for the publisher

publish

publishes a message with optional correlation ID

RAISES DESCRIPTION NotImplementedError

if the publish method is not implemented.

","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.publish","title":"publish abstractmethod async","text":"
publish(\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

correlation_id

Optional correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/publisher.py
@abstractmethod\nasync def publish(\n    self,\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        correlation_id: Optional correlation ID for the message.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/","title":"BaseWatcher","text":"","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher","title":"faststream.broker.push_back_watcher.BaseWatcher","text":"
BaseWatcher(\n    max_tries: int = 0, logger: Optional[Logger] = None\n)\n

Bases: ABC

A base class for a watcher.

PARAMETER DESCRIPTION max_tries

maximum number of tries allowed (default=0)

DEFAULT: 0

logger

logger object (optional)

DEFAULT: None

METHOD DESCRIPTION add

add a message to the watcher

is_max

check if the maximum number of tries has been reached for a message

remove

remove a message from the watcher

Initialize the class.

PARAMETER DESCRIPTION max_tries

Maximum number of tries allowed

TYPE: int DEFAULT: 0

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented in the subclass.

Source code in faststream/broker/push_back_watcher.py
def __init__(\n    self,\n    max_tries: int = 0,\n    logger: Optional[Logger] = None,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        max_tries: Maximum number of tries allowed\n        logger: Optional logger object\n\n    Raises:\n        NotImplementedError: If the method is not implemented in the subclass.\n\n    \"\"\"\n    self.logger = logger\n    self.max_tries = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher.max_tries","title":"max_tries instance-attribute","text":"
max_tries: int = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher.add","title":"add abstractmethod","text":"
add(message_id: str) -> None\n

Add a message.

PARAMETER DESCRIPTION message_id

ID of the message to be added

TYPE: str

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/push_back_watcher.py
@abstractmethod\ndef add(self, message_id: str) -> None:\n    \"\"\"Add a message.\n\n    Args:\n        message_id: ID of the message to be added\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher.is_max","title":"is_max abstractmethod","text":"
is_max(message_id: str) -> bool\n

Check if the given message ID is the maximum.

PARAMETER DESCRIPTION message_id

The ID of the message to check.

TYPE: str

RETURNS DESCRIPTION bool

True if the given message ID is the maximum, False otherwise.

RAISES DESCRIPTION NotImplementedError

This method is meant to be overridden by subclasses.

Source code in faststream/broker/push_back_watcher.py
@abstractmethod\ndef is_max(self, message_id: str) -> bool:\n    \"\"\"Check if the given message ID is the maximum.\n\n    Args:\n        message_id: The ID of the message to check.\n\n    Returns:\n        True if the given message ID is the maximum, False otherwise.\n\n    Raises:\n        NotImplementedError: This method is meant to be overridden by subclasses.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher.remove","title":"remove abstractmethod","text":"
remove(message_id: str) -> None\n

Remove a message.

PARAMETER DESCRIPTION message_id

ID of the message to be removed

TYPE: str

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/push_back_watcher.py
@abstractmethod\ndef remove(self, message_id: str) -> None:\n    \"\"\"Remove a message.\n\n    Args:\n        message_id: ID of the message to be removed\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/","title":"CounterWatcher","text":"","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher","title":"faststream.broker.push_back_watcher.CounterWatcher","text":"
CounterWatcher(\n    max_tries: int = 3, logger: Optional[Logger] = None\n)\n

Bases: BaseWatcher

A class to watch and track the count of messages.

PARAMETER DESCRIPTION max_tries

int - maximum number of tries allowed

DEFAULT: 3

logger

Optional[Logger] - logger object for logging messages

DEFAULT: None

METHOD DESCRIPTION add

str) -> None - adds a message to the counter

is_max

str) -> bool - checks if the count of a message has reached the maximum tries

remove

str) -> None - removes a message from the counter

Initialize the class.

PARAMETER DESCRIPTION max_tries

maximum number of tries

TYPE: int DEFAULT: 3

logger

logger object (default: None)

TYPE: Optional[Logger] DEFAULT: None

Source code in faststream/broker/push_back_watcher.py
def __init__(\n    self,\n    max_tries: int = 3,\n    logger: Optional[Logger] = None,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        max_tries (int): maximum number of tries\n        logger (Optional[Logger]): logger object (default: None)\n\n    \"\"\"\n    super().__init__(logger=logger, max_tries=max_tries)\n    self.memory = Counter()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.max_tries","title":"max_tries instance-attribute","text":"
max_tries: int = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.memory","title":"memory instance-attribute","text":"
memory: CounterType[str] = Counter()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.add","title":"add","text":"
add(message_id: str) -> None\n

Increments the count of a message in the memory.

PARAMETER DESCRIPTION message_id

The ID of the message to be incremented.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def add(self, message_id: str) -> None:\n    \"\"\"Increments the count of a message in the memory.\n\n    Args:\n        message_id: The ID of the message to be incremented.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.memory[message_id] += 1\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.is_max","title":"is_max","text":"
is_max(message_id: str) -> bool\n

Check if the number of tries for a message has exceeded the maximum allowed tries.

PARAMETER DESCRIPTION message_id

The ID of the message

TYPE: str

RETURNS DESCRIPTION bool

True if the number of tries has exceeded the maximum allowed tries, False otherwise

Source code in faststream/broker/push_back_watcher.py
def is_max(self, message_id: str) -> bool:\n    \"\"\"Check if the number of tries for a message has exceeded the maximum allowed tries.\n\n    Args:\n        message_id: The ID of the message\n\n    Returns:\n        True if the number of tries has exceeded the maximum allowed tries, False otherwise\n\n    \"\"\"\n    is_max = self.memory[message_id] > self.max_tries\n    if self.logger is not None:\n        if is_max:\n            self.logger.error(f\"Already retried {self.max_tries} times. Skipped.\")\n        else:\n            self.logger.error(\"Error is occured. Pushing back to queue.\")\n    return is_max\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.remove","title":"remove","text":"
remove(message: str) -> None\n

Remove a message from memory.

PARAMETER DESCRIPTION message

The message to be removed.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def remove(self, message: str) -> None:\n    \"\"\"Remove a message from memory.\n\n    Args:\n        message: The message to be removed.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.memory[message] = 0\n    self.memory += Counter()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/","title":"EndlessWatcher","text":"","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher","title":"faststream.broker.push_back_watcher.EndlessWatcher","text":"
EndlessWatcher(\n    max_tries: int = 0, logger: Optional[Logger] = None\n)\n

Bases: BaseWatcher

Initialize the class.

PARAMETER DESCRIPTION max_tries

Maximum number of tries allowed

TYPE: int DEFAULT: 0

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented in the subclass.

Source code in faststream/broker/push_back_watcher.py
def __init__(\n    self,\n    max_tries: int = 0,\n    logger: Optional[Logger] = None,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        max_tries: Maximum number of tries allowed\n        logger: Optional logger object\n\n    Raises:\n        NotImplementedError: If the method is not implemented in the subclass.\n\n    \"\"\"\n    self.logger = logger\n    self.max_tries = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher.max_tries","title":"max_tries instance-attribute","text":"
max_tries: int = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher.add","title":"add","text":"
add(message_id: str) -> None\n

Add a message to the list.

PARAMETER DESCRIPTION message_id

ID of the message to be added

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def add(self, message_id: str) -> None:\n    \"\"\"Add a message to the list.\n\n    Args:\n        message_id: ID of the message to be added\n\n    Returns:\n        None\n\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher.is_max","title":"is_max","text":"
is_max(message_id: str) -> bool\n

Check if a message is the maximum.

PARAMETER DESCRIPTION message_id

ID of the message to check

TYPE: str

RETURNS DESCRIPTION bool

True if the message is the maximum, False otherwise

Source code in faststream/broker/push_back_watcher.py
def is_max(self, message_id: str) -> bool:\n    \"\"\"Check if a message is the maximum.\n\n    Args:\n        message_id: ID of the message to check\n\n    Returns:\n        True if the message is the maximum, False otherwise\n\n    \"\"\"\n    return False\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher.remove","title":"remove","text":"
remove(message_id: str) -> None\n

Remove a message.

PARAMETER DESCRIPTION message_id

The ID of the message to be removed.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def remove(self, message_id: str) -> None:\n    \"\"\"Remove a message.\n\n    Args:\n        message_id: The ID of the message to be removed.\n\n    Returns:\n        None\n\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/","title":"OneTryWatcher","text":"","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher","title":"faststream.broker.push_back_watcher.OneTryWatcher","text":"
OneTryWatcher(\n    max_tries: int = 0, logger: Optional[Logger] = None\n)\n

Bases: BaseWatcher

Initialize the class.

PARAMETER DESCRIPTION max_tries

Maximum number of tries allowed

TYPE: int DEFAULT: 0

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented in the subclass.

Source code in faststream/broker/push_back_watcher.py
def __init__(\n    self,\n    max_tries: int = 0,\n    logger: Optional[Logger] = None,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        max_tries: Maximum number of tries allowed\n        logger: Optional logger object\n\n    Raises:\n        NotImplementedError: If the method is not implemented in the subclass.\n\n    \"\"\"\n    self.logger = logger\n    self.max_tries = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher.max_tries","title":"max_tries instance-attribute","text":"
max_tries: int = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher.add","title":"add","text":"
add(message_id: str) -> None\n

Add a message.

PARAMETER DESCRIPTION message_id

ID of the message to be added

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def add(self, message_id: str) -> None:\n    \"\"\"Add a message.\n\n    Args:\n        message_id: ID of the message to be added\n\n    Returns:\n        None\n\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher.is_max","title":"is_max","text":"
is_max(message_id: str) -> bool\n

Check if the given message ID is the maximum.

PARAMETER DESCRIPTION message_id

The ID of the message to check.

TYPE: str

RETURNS DESCRIPTION bool

True if the given message ID is the maximum, False otherwise.

Source code in faststream/broker/push_back_watcher.py
def is_max(self, message_id: str) -> bool:\n    \"\"\"Check if the given message ID is the maximum.\n\n    Args:\n        message_id: The ID of the message to check.\n\n    Returns:\n        True if the given message ID is the maximum, False otherwise.\n\n    \"\"\"\n    return True\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher.remove","title":"remove","text":"
remove(message_id: str) -> None\n

Remove a message.

PARAMETER DESCRIPTION message_id

ID of the message to be removed

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def remove(self, message_id: str) -> None:\n    \"\"\"Remove a message.\n\n    Args:\n        message_id: ID of the message to be removed\n\n    Returns:\n        None\n\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/WatcherContext/","title":"WatcherContext","text":"","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/WatcherContext/#faststream.broker.push_back_watcher.WatcherContext","title":"faststream.broker.push_back_watcher.WatcherContext","text":"
WatcherContext(\n    message: Union[\n        SyncStreamMessage[MsgType], StreamMessage[MsgType]\n    ],\n    watcher: BaseWatcher,\n    **extra_ack_args: Any\n)\n

A class representing a context for a watcher.

METHOD DESCRIPTION __aenter__

called when entering the context

__aexit__

called when exiting the context

__ack

acknowledges the message

__nack

negatively acknowledges the message

__reject

rejects the message

Initialize a new instance of the class.

PARAMETER DESCRIPTION watcher

An instance of BaseWatcher.

TYPE: BaseWatcher

message

An instance of SyncStreamMessage or StreamMessage.

TYPE: Union[SyncStreamMessage[MsgType], StreamMessage[MsgType]]

**extra_ack_args

Additional arguments for acknowledgement.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/push_back_watcher.py
def __init__(\n    self,\n    message: Union[SyncStreamMessage[MsgType], StreamMessage[MsgType]],\n    watcher: BaseWatcher,\n    **extra_ack_args: Any,\n) -> None:\n    \"\"\"Initialize a new instance of the class.\n\n    Args:\n        watcher: An instance of BaseWatcher.\n        message: An instance of SyncStreamMessage or StreamMessage.\n        **extra_ack_args: Additional arguments for acknowledgement.\n\n    Attributes:\n        watcher: An instance of BaseWatcher.\n        message: An instance of SyncStreamMessage or StreamMessage.\n        extra_ack_args: Additional arguments for acknowledgement.\n\n    \"\"\"\n    self.watcher = watcher\n    self.message = message\n    self.extra_ack_args = extra_ack_args or {}\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/WatcherContext/#faststream.broker.push_back_watcher.WatcherContext.extra_ack_args","title":"extra_ack_args instance-attribute","text":"
extra_ack_args = extra_ack_args or {}\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/WatcherContext/#faststream.broker.push_back_watcher.WatcherContext.message","title":"message instance-attribute","text":"
message = message\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/WatcherContext/#faststream.broker.push_back_watcher.WatcherContext.watcher","title":"watcher instance-attribute","text":"
watcher = watcher\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRoute/","title":"BrokerRoute","text":"","boost":0.5},{"location":"api/faststream/broker/router/BrokerRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/","title":"BrokerRouter","text":"","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter","title":"faststream.broker.router.BrokerRouter","text":"
BrokerRouter(\n    prefix: str = \"\",\n    handlers: Sequence[\n        BrokerRoute[MsgType, SendableMessage]\n    ] = (),\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    include_in_schema: Optional[bool] = None,\n)\n

Bases: Generic[PublisherKeyType, MsgType]

A generic class representing a broker router.

METHOD DESCRIPTION _get_publisher_key

abstract method to get the publisher key

_update_publisher_prefix

abstract method to update the publisher prefix

__init__

constructor method

subscriber

abstract method to define a subscriber

_wrap_subscriber

method to wrap a subscriber function

publisher

abstract method to define a publisher

include_router

method to include a router

include_routers

method to include multiple routers

Initialize a class object.

PARAMETER DESCRIPTION prefix

Prefix for the object.

TYPE: str DEFAULT: ''

handlers

Handlers for the object.

TYPE: Sequence[BrokerRoute[MsgType, SendableMessage]] DEFAULT: ()

dependencies

Dependencies for the object.

TYPE: Sequence[Depends] DEFAULT: ()

middlewares

Middlewares for the object.

TYPE: Optional[Sequence[Callable[[StreamMessage[MsgType]], AsyncContextManager[None]]]] DEFAULT: None

parser

Parser for the object.

TYPE: Optional[CustomParser[MsgType]] DEFAULT: None

decoder

Decoder for the object.

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

Source code in faststream/broker/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[BrokerRoute[MsgType, SendableMessage]] = (),\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    include_in_schema: Optional[bool] = None,\n) -> None:\n    \"\"\"Initialize a class object.\n\n    Args:\n        prefix (str): Prefix for the object.\n        handlers (Sequence[BrokerRoute[MsgType, SendableMessage]]): Handlers for the object.\n        dependencies (Sequence[Depends]): Dependencies for the object.\n        middlewares (Optional[Sequence[Callable[[StreamMessage[MsgType]], AsyncContextManager[None]]]]): Middlewares for the object.\n        parser (Optional[CustomParser[MsgType]]): Parser for the object.\n        decoder (Optional[CustomDecoder[StreamMessage[MsgType]]]): Decoder for the object.\n\n    \"\"\"\n    self.prefix = prefix\n    self.include_in_schema = include_in_schema\n    self._handlers = list(handlers)\n    self._publishers = {}\n    self._dependencies = dependencies\n    self._middlewares = middlewares\n    self._parser = parser\n    self._decoder = decoder\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.subscriber","title":"subscriber abstractmethod","text":"
subscriber(\n    subj: str,\n    *args: Any,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    include_in_schema: Optional[bool] = None,\n    **kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function to subscribe to a subject.

PARAMETER DESCRIPTION subj

subject to subscribe to

*args

additional arguments

DEFAULT: ()

dependencies

sequence of dependencies

DEFAULT: ()

middlewares

optional sequence of middlewares

DEFAULT: None

parser

optional custom parser

DEFAULT: None

decoder

optional custom decoder

DEFAULT: None

**kwargs

additional keyword arguments

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable handler function

RAISES DESCRIPTION NotImplementedError

If the function is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef subscriber(\n    self,\n    subj: str,\n    *args: Any,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    include_in_schema: Optional[bool] = None,\n    **kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function to subscribe to a subject.\n\n    Args:\n        subj : subject to subscribe to\n        *args : additional arguments\n        dependencies : sequence of dependencies\n        middlewares : optional sequence of middlewares\n        parser : optional custom parser\n        decoder : optional custom decoder\n        **kwargs : additional keyword arguments\n\n    Returns:\n        A callable handler function\n\n    Raises:\n        NotImplementedError: If the function is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/schemas/NameRequired/","title":"NameRequired","text":"","boost":0.5},{"location":"api/faststream/broker/schemas/NameRequired/#faststream.broker.schemas.NameRequired","title":"faststream.broker.schemas.NameRequired","text":"
NameRequired(name: str, **kwargs: Any)\n

Bases: BaseModel

A class to represent a required name.

METHOD DESCRIPTION __eq__

object) -> bool: Check if the given value is equal to the current instance.

validate

Type[NameRequiredCls], value: Union[str, NameRequiredCls]) -> NameRequiredCls: Validate the given value and return a NameRequiredCls instance.

validate

Type[NameRequiredCls], value: None) -> None: Validate the given value and return None.

validate

Type[NameRequiredCls], value: Union[str, NameRequiredCls, None]) -> Optional[NameRequiredCls]: Validate the given value and return an optional NameRequiredCls instance.

This is a Python function.

PARAMETER DESCRIPTION name

The name of the object.

TYPE: str

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None.

Source code in faststream/broker/schemas.py
def __init__(self, name: str, **kwargs: Any) -> None:\n    \"\"\"This is a Python function.\n\n    Args:\n        name (str): The name of the object.\n        **kwargs (Any): Additional keyword arguments.\n\n    Returns:\n        None.\n\n    \"\"\"\n    super().__init__(name=name, **kwargs)\n
","boost":0.5},{"location":"api/faststream/broker/schemas/NameRequired/#faststream.broker.schemas.NameRequired.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/broker/schemas/NameRequired/#faststream.broker.schemas.NameRequired.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/broker/schemas/RawDecoced/","title":"RawDecoced","text":"","boost":0.5},{"location":"api/faststream/broker/schemas/RawDecoced/#faststream.broker.schemas.RawDecoced","title":"faststream.broker.schemas.RawDecoced","text":"

Bases: BaseModel

A class to represent a raw decoded message.

","boost":0.5},{"location":"api/faststream/broker/schemas/RawDecoced/#faststream.broker.schemas.RawDecoced.message","title":"message instance-attribute","text":"
message: Union[Json[Any], str]\n
","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/","title":"BaseSecurity","text":"","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/#faststream.security.BaseSecurity","title":"faststream.security.BaseSecurity","text":"
BaseSecurity(\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Base class for defining security configurations.

This class provides a base for defining security configurations for communication with a broker. It allows setting SSL encryption and provides methods to retrieve security requirements and schemas.

PARAMETER DESCRIPTION ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements in the form of a list of dictionaries.

get_schema

Get the security schema as a dictionary.

Source code in faststream/security.py
def __init__(\n    self,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    if ssl_context is not None:\n        use_ssl = True\n\n    self.use_ssl = use_ssl\n    self.ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/#faststream.security.BaseSecurity.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/#faststream.security.BaseSecurity.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/#faststream.security.BaseSecurity.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return []\n
","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/#faststream.security.BaseSecurity.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {}\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/","title":"SASLPlaintext","text":"","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext","title":"faststream.security.SASLPlaintext","text":"
SASLPlaintext(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/PLAINTEXT authentication.

This class defines security configuration for SASL/PLAINTEXT authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/PLAINTEXT authentication.

get_schema

Get the security schema for SASL/PLAINTEXT authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/PLAINTEXT authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/PLAINTEXT authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"user-password\": []}]\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/PLAINTEXT authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/PLAINTEXT authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"user-password\": {\"type\": \"userPassword\"}}\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/","title":"SASLScram256","text":"","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256","title":"faststream.security.SASLScram256","text":"
SASLScram256(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/SCRAM-SHA-256 authentication.

This class defines security configuration for SASL/SCRAM-SHA-256 authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/SCRAM-SHA-256 authentication.

get_schema

Get the security schema for SASL/SCRAM-SHA-256 authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/SCRAM-SHA-256 authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/SCRAM-SHA-256 authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"scram256\": []}]\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/SCRAM-SHA-256 authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/SCRAM-SHA-256 authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"scram256\": {\"type\": \"scramSha256\"}}\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/","title":"SASLScram512","text":"","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512","title":"faststream.security.SASLScram512","text":"
SASLScram512(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/SCRAM-SHA-512 authentication.

This class defines security configuration for SASL/SCRAM-SHA-512 authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/SCRAM-SHA-512 authentication.

get_schema

Get the security schema for SASL/SCRAM-SHA-512 authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/SCRAM-SHA-512 authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/SCRAM-SHA-512 authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"scram512\": []}]\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/SCRAM-SHA-512 authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/SCRAM-SHA-512 authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"scram512\": {\"type\": \"scramSha512\"}}\n
","boost":0.5},{"location":"api/faststream/broker/test/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/broker/test/TestApp/#faststream.broker.test.TestApp","title":"faststream.broker.test.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/broker/test/TestApp/#faststream.broker.test.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/","title":"TestBroker","text":"","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker","title":"faststream.broker.test.TestBroker","text":"
TestBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: Generic[Broker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber abstractmethod staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: Broker, publisher: Any\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/broker/test.py
@staticmethod\n@abstractmethod\ndef create_publisher_fake_subscriber(\n    broker: Broker, publisher: Any\n) -> HandlerCallWrapper[Any, Any, Any]:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.patch_publisher","title":"patch_publisher abstractmethod staticmethod","text":"
patch_publisher(broker: Broker, publisher: Any) -> None\n
Source code in faststream/broker/test.py
@staticmethod\n@abstractmethod\ndef patch_publisher(broker: Broker, publisher: Any) -> None:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber abstractmethod staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: Broker, publisher: Any\n) -> None\n
Source code in faststream/broker/test.py
@staticmethod\n@abstractmethod\ndef remove_publisher_fake_subscriber(broker: Broker, publisher: Any) -> None:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/test/call_handler/","title":"call_handler","text":"","boost":0.5},{"location":"api/faststream/broker/test/call_handler/#faststream.broker.test.call_handler","title":"faststream.broker.test.call_handler async","text":"
call_handler(\n    handler: AsyncHandler[Any],\n    message: Any,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[SendableMessage]\n

Asynchronously call a handler function.

PARAMETER DESCRIPTION handler

The handler function to be called.

TYPE: AsyncHandler[Any]

message

The message to be passed to the handler function.

TYPE: Any

rpc

Whether the call is a remote procedure call (RPC).

TYPE: bool DEFAULT: False

rpc_timeout

The timeout for the RPC, in seconds.

TYPE: Optional[float] DEFAULT: 30.0

raise_timeout

Whether to raise a timeout error if the RPC times out.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION Optional[SendableMessage]

The result of the handler function if rpc is True, otherwise None.

RAISES DESCRIPTION TimeoutError

If the RPC times out and raise_timeout is True.

Source code in faststream/broker/test.py
async def call_handler(\n    handler: AsyncHandler[Any],\n    message: Any,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[SendableMessage]:\n    \"\"\"Asynchronously call a handler function.\n\n    Args:\n        handler: The handler function to be called.\n        message: The message to be passed to the handler function.\n        rpc: Whether the call is a remote procedure call (RPC).\n        rpc_timeout: The timeout for the RPC, in seconds.\n        raise_timeout: Whether to raise a timeout error if the RPC times out.\n\n    Returns:\n        The result of the handler function if `rpc` is True, otherwise None.\n\n    Raises:\n        TimeoutError: If the RPC times out and `raise_timeout` is True.\n\n    \"\"\"\n    with timeout_scope(rpc_timeout, raise_timeout):\n        result = await handler.consume(message)\n\n        if rpc is True:\n            return result\n\n    return None\n
","boost":0.5},{"location":"api/faststream/broker/test/patch_broker_calls/","title":"patch_broker_calls","text":"","boost":0.5},{"location":"api/faststream/broker/test/patch_broker_calls/#faststream.broker.test.patch_broker_calls","title":"faststream.broker.test.patch_broker_calls","text":"
patch_broker_calls(broker: BrokerUsecase[Any, Any]) -> None\n

Patch broker calls.

PARAMETER DESCRIPTION broker

The broker to patch.

TYPE: BrokerUsecase[Any, Any]

RETURNS DESCRIPTION None

None.

Source code in faststream/broker/test.py
def patch_broker_calls(broker: BrokerUsecase[Any, Any]) -> None:\n    \"\"\"Patch broker calls.\n\n    Args:\n        broker: The broker to patch.\n\n    Returns:\n        None.\n\n    \"\"\"\n    broker.middlewares = tuple(\n        filter(  # type: ignore[assignment]\n            lambda x: not isinstance(x, CriticalLogMiddleware),\n            broker.middlewares,\n        )\n    )\n    broker._abc_start()\n\n    for handler in broker.handlers.values():\n        for f, _, _, _, _, _ in handler.calls:\n            f.set_test()\n
","boost":0.5},{"location":"api/faststream/broker/types/AsyncPublisherProtocol/","title":"AsyncPublisherProtocol","text":"","boost":0.5},{"location":"api/faststream/broker/types/AsyncPublisherProtocol/#faststream.broker.types.AsyncPublisherProtocol","title":"faststream.broker.types.AsyncPublisherProtocol","text":"

Bases: Protocol

A protocol for an asynchronous publisher.

METHOD DESCRIPTION publish

SendableMessage, correlation_id: Optional[str] = None, **kwargs: Any) -> Optional[SendableMessage]: Publishes a message asynchronously.

Args: message: The message to be published. correlation_id: The correlation ID for the message (optional). **kwargs: Additional keyword arguments.

Returns: The published message (optional).

","boost":0.5},{"location":"api/faststream/broker/types/AsyncPublisherProtocol/#faststream.broker.types.AsyncPublisherProtocol.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publishes a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

correlation_id

Optional correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message, or None if the message was not published.

Source code in faststream/broker/types.py
async def publish(\n    self,\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publishes a message.\n\n    Args:\n        message: The message to be published.\n        correlation_id: Optional correlation ID for the message.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message, or None if the message was not published.\n\n    \"\"\"\n    ...\n
","boost":0.5},{"location":"api/faststream/broker/utils/change_logger_handlers/","title":"change_logger_handlers","text":"","boost":0.5},{"location":"api/faststream/broker/utils/change_logger_handlers/#faststream.broker.utils.change_logger_handlers","title":"faststream.broker.utils.change_logger_handlers","text":"
change_logger_handlers(\n    logger: logging.Logger, fmt: str\n) -> None\n

Change the formatter of the logger handlers.

PARAMETER DESCRIPTION logger

The logger object.

TYPE: Logger

fmt

The format string for the formatter.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/utils.py
def change_logger_handlers(logger: logging.Logger, fmt: str) -> None:\n    \"\"\"Change the formatter of the logger handlers.\n\n    Args:\n        logger (logging.Logger): The logger object.\n        fmt (str): The format string for the formatter.\n\n    Returns:\n        None\n\n    \"\"\"\n    for handler in getattr(logger, \"handlers\", ()):\n        formatter = handler.formatter\n        if formatter is not None:  # pragma: no branch\n            use_colors = getattr(formatter, \"use_colors\", None)\n            if use_colors is not None:  # pragma: no branch\n                kwargs = {\"use_colors\": use_colors}\n            else:  # pragma: no cover\n                kwargs = {}\n            handler.setFormatter(type(formatter)(fmt, **kwargs))\n
","boost":0.5},{"location":"api/faststream/broker/utils/get_watcher/","title":"get_watcher","text":"","boost":0.5},{"location":"api/faststream/broker/utils/get_watcher/#faststream.broker.utils.get_watcher","title":"faststream.broker.utils.get_watcher","text":"
get_watcher(\n    logger: Optional[logging.Logger],\n    try_number: Union[bool, int] = True,\n) -> BaseWatcher\n

Get a watcher object based on the provided parameters.

PARAMETER DESCRIPTION logger

Optional logger object for logging messages.

TYPE: Optional[Logger]

try_number

Optional parameter to specify the type of watcher. - If set to True, an EndlessWatcher object will be returned. - If set to False, a OneTryWatcher object will be returned. - If set to an integer, a CounterWatcher object with the specified maximum number of tries will be returned.

TYPE: Union[bool, int] DEFAULT: True

RETURNS DESCRIPTION BaseWatcher

A watcher object based on the provided parameters.

Source code in faststream/broker/utils.py
def get_watcher(\n    logger: Optional[logging.Logger],\n    try_number: Union[bool, int] = True,\n) -> BaseWatcher:\n    \"\"\"Get a watcher object based on the provided parameters.\n\n    Args:\n        logger: Optional logger object for logging messages.\n        try_number: Optional parameter to specify the type of watcher.\n            - If set to True, an EndlessWatcher object will be returned.\n            - If set to False, a OneTryWatcher object will be returned.\n            - If set to an integer, a CounterWatcher object with the specified maximum number of tries will be returned.\n\n    Returns:\n        A watcher object based on the provided parameters.\n\n    \"\"\"\n    watcher: Optional[BaseWatcher]\n    if try_number is True:\n        watcher = EndlessWatcher()\n    elif try_number is False:\n        watcher = OneTryWatcher()\n    else:\n        watcher = CounterWatcher(logger=logger, max_tries=try_number)\n    return watcher\n
","boost":0.5},{"location":"api/faststream/broker/utils/set_message_context/","title":"set_message_context","text":"","boost":0.5},{"location":"api/faststream/broker/utils/set_message_context/#faststream.broker.utils.set_message_context","title":"faststream.broker.utils.set_message_context","text":"
set_message_context(\n    func: Callable[\n        [StreamMessage[MsgType]],\n        Awaitable[WrappedReturn[T_HandlerReturn]],\n    ]\n) -> Callable[\n    [StreamMessage[MsgType]],\n    Awaitable[WrappedReturn[T_HandlerReturn]],\n]\n

Sets the message context for a function.

PARAMETER DESCRIPTION func

The function to set the message context for.

TYPE: Callable[[StreamMessage[MsgType]], Awaitable[WrappedReturn[T_HandlerReturn]]]

RETURNS DESCRIPTION Callable[[StreamMessage[MsgType]], Awaitable[WrappedReturn[T_HandlerReturn]]]

The function with the message context set.

Source code in faststream/broker/utils.py
def set_message_context(\n    func: Callable[\n        [StreamMessage[MsgType]],\n        Awaitable[WrappedReturn[T_HandlerReturn]],\n    ],\n) -> Callable[[StreamMessage[MsgType]], Awaitable[WrappedReturn[T_HandlerReturn]]]:\n    \"\"\"Sets the message context for a function.\n\n    Args:\n        func: The function to set the message context for.\n\n    Returns:\n        The function with the message context set.\n\n    \"\"\"\n\n    @wraps(func)\n    async def set_message_wrapper(\n        message: StreamMessage[MsgType],\n    ) -> WrappedReturn[T_HandlerReturn]:\n        \"\"\"Wraps a function that handles a stream message.\n\n        Args:\n            message: The stream message to be handled.\n\n        Returns:\n            The wrapped return value of the handler function.\n\n        \"\"\"\n        with context.scope(\"message\", message):\n            return await func(message)\n\n    return set_message_wrapper\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/FakePublisher/","title":"FakePublisher","text":"","boost":0.5},{"location":"api/faststream/broker/wrapper/FakePublisher/#faststream.broker.wrapper.FakePublisher","title":"faststream.broker.wrapper.FakePublisher","text":"
FakePublisher(\n    method: Callable[..., Awaitable[SendableMessage]]\n)\n

A class to represent a fake publisher.

METHOD DESCRIPTION publish

asynchronously publishes a message with optional correlation ID and additional keyword arguments

Initialize an object.

PARAMETER DESCRIPTION method

A callable that takes any number of arguments and returns an awaitable sendable message.

TYPE: Callable[..., Awaitable[SendableMessage]]

Source code in faststream/broker/wrapper.py
def __init__(self, method: Callable[..., Awaitable[SendableMessage]]) -> None:\n    \"\"\"Initialize an object.\n\n    Args:\n        method: A callable that takes any number of arguments and returns an awaitable sendable message.\n\n    \"\"\"\n    self.method = method\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/FakePublisher/#faststream.broker.wrapper.FakePublisher.method","title":"method instance-attribute","text":"
method = method\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/FakePublisher/#faststream.broker.wrapper.FakePublisher.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

correlation_id

Optional correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message.

Source code in faststream/broker/wrapper.py
async def publish(\n    self,\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        correlation_id: Optional correlation ID for the message.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message.\n\n    \"\"\"\n    return await self.method(message, correlation_id=correlation_id, **kwargs)\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/","title":"HandlerCallWrapper","text":"","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper","title":"faststream.broker.wrapper.HandlerCallWrapper","text":"
HandlerCallWrapper(\n    call: Callable[P_HandlerParams, T_HandlerReturn]\n)\n

Bases: Generic[MsgType, P_HandlerParams, T_HandlerReturn]

A generic class to wrap handler calls.

METHOD DESCRIPTION __new__

Create a new instance of the class

__init__

Initialize the instance

__call__

Call the wrapped handler

set_wrapped

Set the wrapped handler call

call_wrapped

Call the wrapped handler

wait_call

Wait for the handler call to complete

Initialize a handler.

PARAMETER DESCRIPTION call

A callable object that represents the handler function.

TYPE: Callable[P_HandlerParams, T_HandlerReturn]

Source code in faststream/broker/wrapper.py
def __init__(\n    self,\n    call: Callable[P_HandlerParams, T_HandlerReturn],\n) -> None:\n    \"\"\"Initialize a handler.\n\n    Args:\n        call: A callable object that represents the handler function.\n\n    Attributes:\n        _original_call: The original handler function.\n        _wrapped_call: The wrapped handler function.\n        _publishers: A list of publishers.\n        mock: A MagicMock object.\n        __name__: The name of the handler function.\n\n    \"\"\"\n    if not isinstance(call, HandlerCallWrapper):\n        self._original_call = call\n        self._wrapped_call = None\n        self._publishers = []\n\n        self.mock = None\n        self.future = None\n        self.is_test = False\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.future","title":"future instance-attribute","text":"
future: Optional[asyncio.Future[Any]]\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.is_test","title":"is_test instance-attribute","text":"
is_test: bool\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.mock","title":"mock instance-attribute","text":"
mock: Optional[MagicMock]\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.call_wrapped","title":"call_wrapped","text":"
call_wrapped(\n    message: StreamMessage[MsgType],\n) -> Union[\n    Optional[WrappedReturn[T_HandlerReturn]],\n    Awaitable[Optional[WrappedReturn[T_HandlerReturn]]],\n]\n

Calls the wrapped function with the given message.

PARAMETER DESCRIPTION message

The message to be passed to the wrapped function.

TYPE: StreamMessage[MsgType]

RETURNS DESCRIPTION Union[Optional[WrappedReturn[T_HandlerReturn]], Awaitable[Optional[WrappedReturn[T_HandlerReturn]]]]

The result of the wrapped function call.

RAISES DESCRIPTION AssertionError

If set_wrapped has not been called before calling this function.

AssertionError

If the broker has not been started before calling this function.

Source code in faststream/broker/wrapper.py
def call_wrapped(\n    self,\n    message: StreamMessage[MsgType],\n) -> Union[\n    Optional[WrappedReturn[T_HandlerReturn]],\n    Awaitable[Optional[WrappedReturn[T_HandlerReturn]]],\n]:\n    \"\"\"Calls the wrapped function with the given message.\n\n    Args:\n        message: The message to be passed to the wrapped function.\n\n    Returns:\n        The result of the wrapped function call.\n\n    Raises:\n        AssertionError: If `set_wrapped` has not been called before calling this function.\n        AssertionError: If the broker has not been started before calling this function.\n\n    \"\"\"\n    assert self._wrapped_call, \"You should use `set_wrapped` first\"  # nosec B101\n    if self.is_test:\n        assert self.mock  # nosec B101\n        self.mock(message.decoded_body)\n    return self._wrapped_call(message)\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.refresh","title":"refresh","text":"
refresh(with_mock: bool = False) -> None\n
Source code in faststream/broker/wrapper.py
def refresh(self, with_mock: bool = False) -> None:\n    self.future = asyncio.Future()\n    if with_mock and self.mock is not None:\n        self.mock.reset_mock()\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/wrapper.py
def reset_test(self) -> None:\n    self.is_test = False\n    self.mock = None\n    self.future = None\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.set_test","title":"set_test","text":"
set_test() -> None\n
Source code in faststream/broker/wrapper.py
def set_test(self) -> None:\n    self.is_test = True\n    if self.mock is None:\n        self.mock = MagicMock()\n    self.refresh(with_mock=True)\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.set_wrapped","title":"set_wrapped","text":"
set_wrapped(\n    wrapped: WrappedHandlerCall[MsgType, T_HandlerReturn]\n) -> None\n

Set the wrapped handler call.

PARAMETER DESCRIPTION wrapped

The wrapped handler call to set

TYPE: WrappedHandlerCall[MsgType, T_HandlerReturn]

Source code in faststream/broker/wrapper.py
def set_wrapped(\n    self, wrapped: WrappedHandlerCall[MsgType, T_HandlerReturn]\n) -> None:\n    \"\"\"Set the wrapped handler call.\n\n    Args:\n        wrapped: The wrapped handler call to set\n\n    \"\"\"\n    self._wrapped_call = wrapped\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.trigger","title":"trigger","text":"
trigger(\n    result: Any = None,\n    error: Optional[BaseException] = None,\n) -> None\n
Source code in faststream/broker/wrapper.py
def trigger(\n    self,\n    result: Any = None,\n    error: Optional[BaseException] = None,\n) -> None:\n    if not self.is_test:\n        return\n\n    assert (  # nosec B101\n        self.future is not None\n    ), \"You can use this method only with TestClient\"\n\n    if self.future.done():\n        self.future = asyncio.Future()\n\n    if error:\n        self.future.set_exception(error)\n    else:\n        self.future.set_result(result)\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.wait_call","title":"wait_call async","text":"
wait_call(timeout: Optional[float] = None) -> None\n

Waits for a call with an optional timeout.

PARAMETER DESCRIPTION timeout

Optional timeout in seconds

TYPE: Optional[float] DEFAULT: None

RAISES DESCRIPTION AssertionError

If the broker is not started

RETURNS DESCRIPTION None

None

Source code in faststream/broker/wrapper.py
async def wait_call(self, timeout: Optional[float] = None) -> None:\n    \"\"\"Waits for a call with an optional timeout.\n\n    Args:\n        timeout: Optional timeout in seconds\n\n    Raises:\n        AssertionError: If the broker is not started\n\n    Returns:\n        None\n\n    \"\"\"\n    assert (  # nosec B101\n        self.future is not None\n    ), \"You can use this method only with TestClient\"\n    with anyio.fail_after(timeout):\n        await self.future\n
","boost":0.5},{"location":"api/faststream/cli/docs/app/gen/","title":"gen","text":"","boost":0.5},{"location":"api/faststream/cli/docs/app/gen/#faststream.cli.docs.app.gen","title":"faststream.cli.docs.app.gen","text":"
gen(\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] - path to your application\",\n    ),\n    yaml: bool = typer.Option(\n        False,\n        \"--yaml\",\n        is_flag=True,\n        help=\"generate `asyncapi.yaml` schema\",\n    ),\n    out: Optional[str] = typer.Option(\n        None, help=\"output filename\"\n    ),\n) -> None\n

Generate project AsyncAPI schema

Source code in faststream/cli/docs/app.py
@docs_app.command(name=\"gen\")\ndef gen(\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] - path to your application\",\n    ),\n    yaml: bool = typer.Option(\n        False,\n        \"--yaml\",\n        is_flag=True,\n        help=\"generate `asyncapi.yaml` schema\",\n    ),\n    out: Optional[str] = typer.Option(\n        None,\n        help=\"output filename\",\n    ),\n) -> None:\n    \"\"\"Generate project AsyncAPI schema\"\"\"\n    _, app_obj = import_from_string(app)\n    raw_schema = get_app_schema(app_obj)\n\n    if yaml:\n        try:\n            schema = raw_schema.to_yaml()\n        except ImportError as e:  # pragma: no cover\n            typer.echo(INSTALL_YAML, err=True)\n            raise typer.Exit(1) from e\n\n        name = out or \"asyncapi.yaml\"\n\n        with open(name, \"w\") as f:\n            f.write(schema)\n\n    else:\n        schema = raw_schema.to_jsonable()\n        name = out or \"asyncapi.json\"\n\n        with open(name, \"w\") as f:\n            json.dump(schema, f, indent=2)\n\n    typer.echo(f\"Your project AsyncAPI scheme was placed to `{name}`\")\n
","boost":0.5},{"location":"api/faststream/cli/docs/app/serve/","title":"serve","text":"","boost":0.5},{"location":"api/faststream/cli/docs/app/serve/#faststream.cli.docs.app.serve","title":"faststream.cli.docs.app.serve","text":"
serve(\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] or [asyncapi.yaml/.json] - path to your application or documentation\",\n    ),\n    host: str = typer.Option(\n        \"localhost\", help=\"documentation hosting address\"\n    ),\n    port: int = typer.Option(\n        8000, help=\"documentation hosting port\"\n    ),\n    reload: bool = typer.Option(\n        False,\n        \"--reload\",\n        is_flag=True,\n        help=\"Restart documentation at directory files changes\",\n    ),\n) -> None\n

Serve project AsyncAPI schema

Source code in faststream/cli/docs/app.py
@docs_app.command(name=\"serve\")\ndef serve(\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] or [asyncapi.yaml/.json] - path to your application or documentation\",\n    ),\n    host: str = typer.Option(\n        \"localhost\",\n        help=\"documentation hosting address\",\n    ),\n    port: int = typer.Option(\n        8000,\n        help=\"documentation hosting port\",\n    ),\n    reload: bool = typer.Option(\n        False,\n        \"--reload\",\n        is_flag=True,\n        help=\"Restart documentation at directory files changes\",\n    ),\n) -> None:\n    \"\"\"Serve project AsyncAPI schema\"\"\"\n\n    if \":\" in app:\n        module, _ = import_from_string(app)\n\n        module_parent = module.parent\n        extra_extensions: Sequence[str] = ()\n\n    else:\n        module_parent = Path.cwd()\n        schema_filepath = module_parent / app\n        extra_extensions = (schema_filepath.suffix,)\n\n    if reload is True:\n        try:\n            from faststream.cli.supervisors.watchfiles import WatchReloader\n\n        except ImportError:\n            warnings.warn(INSTALL_WATCHFILES, category=ImportWarning, stacklevel=1)\n            _parse_and_serve(app, host, port)\n\n        else:\n            WatchReloader(\n                target=_parse_and_serve,\n                args=(app, host, port),\n                reload_dirs=(str(module_parent),),\n                extra_extensions=extra_extensions,\n            ).run()\n\n    else:\n        _parse_and_serve(app, host, port)\n
","boost":0.5},{"location":"api/faststream/cli/main/main/","title":"main","text":"","boost":0.5},{"location":"api/faststream/cli/main/main/#faststream.cli.main.main","title":"faststream.cli.main.main","text":"
main(\n    version: Optional[bool] = typer.Option(\n        False,\n        \"-v\",\n        \"--version\",\n        callback=version_callback,\n        is_eager=True,\n        help=\"Show current platform, python and FastStream version\",\n    )\n) -> None\n

Generate, run and manage FastStream apps to greater development experience

Source code in faststream/cli/main.py
@cli.callback()\ndef main(\n    version: Optional[bool] = typer.Option(\n        False,\n        \"-v\",\n        \"--version\",\n        callback=version_callback,\n        is_eager=True,\n        help=\"Show current platform, python and FastStream version\",\n    ),\n) -> None:\n    \"\"\"\n    Generate, run and manage FastStream apps to greater development experience\n    \"\"\"\n
","boost":0.5},{"location":"api/faststream/cli/main/run/","title":"run","text":"","boost":0.5},{"location":"api/faststream/cli/main/run/#faststream.cli.main.run","title":"faststream.cli.main.run","text":"
run(\n    ctx: typer.Context,\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] - path to your application\",\n    ),\n    workers: int = typer.Option(\n        1,\n        show_default=False,\n        help=\"Run [workers] applications with process spawning\",\n    ),\n    log_level: LogLevels = typer.Option(\n        LogLevels.info,\n        case_sensitive=False,\n        show_default=False,\n        help=\"[INFO] default\",\n    ),\n    reload: bool = typer.Option(\n        False,\n        \"--reload\",\n        is_flag=True,\n        help=\"Restart app at directory files changes\",\n    ),\n    watch_extensions: List[str] = typer.Option(\n        (),\n        \"--extension\",\n        \"--reload-extension\",\n        \"--reload-ext\",\n        \"--ext\",\n        help=\"List of file extensions to watch by\",\n    ),\n    app_dir: str = typer.Option(\n        \".\",\n        \"--app-dir\",\n        help=\"Look for APP in the specified directory, by adding this to the PYTHONPATH. Defaults to the current working directory.\",\n    ),\n) -> None\n

Run [MODULE:APP] FastStream application

Source code in faststream/cli/main.py
@cli.command(\n    context_settings={\"allow_extra_args\": True, \"ignore_unknown_options\": True}\n)\ndef run(\n    ctx: typer.Context,\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] - path to your application\",\n    ),\n    workers: int = typer.Option(\n        1,\n        show_default=False,\n        help=\"Run [workers] applications with process spawning\",\n    ),\n    log_level: LogLevels = typer.Option(\n        LogLevels.info,\n        case_sensitive=False,\n        show_default=False,\n        help=\"[INFO] default\",\n    ),\n    reload: bool = typer.Option(\n        False,\n        \"--reload\",\n        is_flag=True,\n        help=\"Restart app at directory files changes\",\n    ),\n    watch_extensions: List[str] = typer.Option(\n        (),\n        \"--extension\",\n        \"--reload-extension\",\n        \"--reload-ext\",\n        \"--ext\",\n        help=\"List of file extensions to watch by\",\n    ),\n    app_dir: str = typer.Option(\n        \".\",\n        \"--app-dir\",\n        help=(\n            \"Look for APP in the specified directory, by adding this to the PYTHONPATH.\"\n            \" Defaults to the current working directory.\"\n        ),\n    ),\n) -> None:\n    \"\"\"Run [MODULE:APP] FastStream application\"\"\"\n    if watch_extensions and not reload:\n        typer.echo(\n            \"Extra reload extensions has no effect without `--reload` flag.\"\n            \"\\nProbably, you forgot it?\"\n        )\n\n    app, extra = parse_cli_args(app, *ctx.args)\n    casted_log_level = get_log_level(log_level)\n\n    if app_dir:  # pragma: no branch\n        sys.path.insert(0, app_dir)\n\n    args = (app, extra, casted_log_level)\n\n    if reload and workers > 1:\n        raise ValueError(\"You can't use reload option with multiprocessing\")\n\n    if reload is True:\n        try:\n            from faststream.cli.supervisors.watchfiles import WatchReloader\n        except ImportError:\n            warnings.warn(INSTALL_WATCHFILES, category=ImportWarning, stacklevel=1)\n            _run(*args)\n\n        else:\n            module_path, _ = import_from_string(app)\n\n            WatchReloader(\n                target=_run,\n                args=args,\n                reload_dirs=[str(module_path)] + ([app_dir] if app_dir else []),\n            ).run()\n\n    elif workers > 1:\n        from faststream.cli.supervisors.multiprocess import Multiprocess\n\n        Multiprocess(\n            target=_run,\n            args=(*args, logging.DEBUG),\n            workers=workers,\n        ).run()\n\n    else:\n        _run(*args)\n
","boost":0.5},{"location":"api/faststream/cli/main/version_callback/","title":"version_callback","text":"","boost":0.5},{"location":"api/faststream/cli/main/version_callback/#faststream.cli.main.version_callback","title":"faststream.cli.main.version_callback","text":"
version_callback(version: bool) -> None\n

Callback function for displaying version information.

PARAMETER DESCRIPTION version

If True, display version information

TYPE: bool

RETURNS DESCRIPTION None

None

Source code in faststream/cli/main.py
def version_callback(version: bool) -> None:\n    \"\"\"Callback function for displaying version information.\n\n    Args:\n        version: If True, display version information\n\n    Returns:\n        None\n\n    \"\"\"\n    if version is True:\n        import platform\n\n        typer.echo(\n            \"Running FastStream %s with %s %s on %s\"\n            % (\n                __version__,\n                platform.python_implementation(),\n                platform.python_version(),\n                platform.system(),\n            )\n        )\n\n        raise typer.Exit()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/","title":"BaseReload","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload","title":"faststream.cli.supervisors.basereload.BaseReload","text":"
BaseReload(\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    reload_delay: Optional[float] = 0.5,\n)\n

A base class for implementing a reloader process.

METHOD DESCRIPTION run

Runs the reloader process.

startup

Performs startup operations for the reloader process.

restart

Restarts the process.

shutdown

Shuts down the reloader process.

_stop_process

Stops the spawned process.

_start_process

Starts the spawned process.

should_restart

Determines whether the process should be restarted.

Initialize a class instance.

PARAMETER DESCRIPTION target

The target callable object

TYPE: DecoratedCallable

args

Tuple of arguments to be passed to the target callable

TYPE: Tuple[Any, ...]

reload_delay

Optional delay in seconds before reloading the target callable (default is 0.5 seconds)

TYPE: Optional[float] DEFAULT: 0.5

RETURNS DESCRIPTION None

None

Source code in faststream/cli/supervisors/basereload.py
def __init__(\n    self,\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    reload_delay: Optional[float] = 0.5,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        target: The target callable object\n        args: Tuple of arguments to be passed to the target callable\n        reload_delay: Optional delay in seconds before reloading the target callable (default is 0.5 seconds)\n\n    Returns:\n        None\n\n    \"\"\"\n    self._target = target\n    self._args = args\n\n    self.should_exit = threading.Event()\n    self.pid = os.getpid()\n    self.reload_delay = reload_delay\n\n    set_exit(lambda *_: self.should_exit.set())\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.pid","title":"pid instance-attribute","text":"
pid: int = os.getpid()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.reload_delay","title":"reload_delay instance-attribute","text":"
reload_delay: Optional[float] = reload_delay\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.reloader_name","title":"reloader_name class-attribute instance-attribute","text":"
reloader_name: str = ''\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.should_exit","title":"should_exit instance-attribute","text":"
should_exit: threading.Event = threading.Event()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.restart","title":"restart","text":"
restart() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def restart(self) -> None:\n    self._stop_process()\n    logger.info(\"Process successfully reloaded\")\n    self._process = self._start_process()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.run","title":"run","text":"
run() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def run(self) -> None:\n    self.startup()\n    while not self.should_exit.wait(self.reload_delay):\n        if self.should_restart():  # pragma: no branch\n            self.restart()\n    self.shutdown()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.should_restart","title":"should_restart","text":"
should_restart() -> bool\n
Source code in faststream/cli/supervisors/basereload.py
def should_restart(self) -> bool:\n    raise NotImplementedError(\"Reload strategies should override should_restart()\")\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.shutdown","title":"shutdown","text":"
shutdown() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def shutdown(self) -> None:\n    self._stop_process()\n    logger.info(f\"Stopping reloader process [{self.pid}]\")\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.startup","title":"startup","text":"
startup() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def startup(self) -> None:\n    logger.info(f\"Started reloader process [{self.pid}] using {self.reloader_name}\")\n    self._process = self._start_process()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/","title":"Multiprocess","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess","title":"faststream.cli.supervisors.multiprocess.Multiprocess","text":"
Multiprocess(\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    workers: int,\n)\n

Bases: BaseReload

A class to represent a multiprocess.

METHOD DESCRIPTION startup

starts the parent process and creates worker processes

shutdown

terminates and joins all worker processes, and stops the parent process

Initialize a new instance of the class.

PARAMETER DESCRIPTION target

The target callable object to be executed.

TYPE: DecoratedCallable

args

The arguments to be passed to the target callable.

TYPE: Tuple[Any, ...]

workers

The number of workers to be used.

TYPE: int

RETURNS DESCRIPTION None

None.

Source code in faststream/cli/supervisors/multiprocess.py
def __init__(\n    self,\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    workers: int,\n) -> None:\n    \"\"\"Initialize a new instance of the class.\n\n    Args:\n        target: The target callable object to be executed.\n        args: The arguments to be passed to the target callable.\n        workers: The number of workers to be used.\n\n    Returns:\n        None.\n\n    \"\"\"\n    super().__init__(target, args, None)\n\n    self.workers = workers\n    self.processes: List[SpawnProcess] = []\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.pid","title":"pid instance-attribute","text":"
pid: int = os.getpid()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.processes","title":"processes instance-attribute","text":"
processes: List[SpawnProcess] = []\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.reload_delay","title":"reload_delay instance-attribute","text":"
reload_delay: Optional[float] = reload_delay\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.reloader_name","title":"reloader_name class-attribute instance-attribute","text":"
reloader_name: str = ''\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.should_exit","title":"should_exit instance-attribute","text":"
should_exit: threading.Event = threading.Event()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.workers","title":"workers instance-attribute","text":"
workers = workers\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.restart","title":"restart","text":"
restart() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def restart(self) -> None:\n    self._stop_process()\n    logger.info(\"Process successfully reloaded\")\n    self._process = self._start_process()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.run","title":"run","text":"
run() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def run(self) -> None:\n    self.startup()\n    while not self.should_exit.wait(self.reload_delay):\n        if self.should_restart():  # pragma: no branch\n            self.restart()\n    self.shutdown()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.should_restart","title":"should_restart","text":"
should_restart() -> bool\n
Source code in faststream/cli/supervisors/basereload.py
def should_restart(self) -> bool:\n    raise NotImplementedError(\"Reload strategies should override should_restart()\")\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.shutdown","title":"shutdown","text":"
shutdown() -> None\n
Source code in faststream/cli/supervisors/multiprocess.py
def shutdown(self) -> None:\n    for process in self.processes:\n        process.terminate()\n        logger.info(f\"Stopping child process [{process.pid}]\")\n        process.join()\n\n    logger.info(f\"Stopping parent process [{self.pid}]\")\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.startup","title":"startup","text":"
startup() -> None\n
Source code in faststream/cli/supervisors/multiprocess.py
def startup(self) -> None:\n    logger.info(f\"Started parent process [{self.pid}]\")\n\n    for _ in range(self.workers):\n        process = self._start_process()\n        logger.info(f\"Started child process [{process.pid}]\")\n        self.processes.append(process)\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/get_subprocess/","title":"get_subprocess","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/get_subprocess/#faststream.cli.supervisors.utils.get_subprocess","title":"faststream.cli.supervisors.utils.get_subprocess","text":"
get_subprocess(\n    target: DecoratedCallableNone, args: Any\n) -> SpawnProcess\n

Spawn a subprocess.

PARAMETER DESCRIPTION target

The target function to be executed in the subprocess.

TYPE: DecoratedCallableNone

args

The arguments to be passed to the target function.

TYPE: Any

RETURNS DESCRIPTION SpawnProcess

The spawned subprocess.

RAISES DESCRIPTION OSError

If there is an error getting the file descriptor of sys.stdin.

Source code in faststream/cli/supervisors/utils.py
def get_subprocess(target: DecoratedCallableNone, args: Any) -> SpawnProcess:\n    \"\"\"Spawn a subprocess.\n\n    Args:\n        target: The target function to be executed in the subprocess.\n        args: The arguments to be passed to the target function.\n\n    Returns:\n        The spawned subprocess.\n\n    Raises:\n        OSError: If there is an error getting the file descriptor of sys.stdin.\n\n    \"\"\"\n    stdin_fileno: Optional[int]\n    try:\n        stdin_fileno = sys.stdin.fileno()\n    except OSError:\n        stdin_fileno = None\n\n    return spawn.Process(\n        target=subprocess_started,\n        args=args,\n        kwargs={\"t\": target, \"stdin_fileno\": stdin_fileno},\n    )\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/set_exit/","title":"set_exit","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/set_exit/#faststream.cli.supervisors.utils.set_exit","title":"faststream.cli.supervisors.utils.set_exit","text":"
set_exit(\n    func: Callable[[int, Optional[FrameType]], Any]\n) -> None\n

Set exit handler for signals.

PARAMETER DESCRIPTION func

A callable object that takes an integer and an optional frame type as arguments and returns any value.

TYPE: Callable[[int, Optional[FrameType]], Any]

RETURNS DESCRIPTION None

None

Source code in faststream/cli/supervisors/utils.py
def set_exit(func: Callable[[int, Optional[FrameType]], Any]) -> None:\n    \"\"\"Set exit handler for signals.\n\n    Args:\n        func: A callable object that takes an integer and an optional frame type as arguments and returns any value.\n\n    Returns:\n        None\n\n    \"\"\"\n    for sig in HANDLED_SIGNALS:\n        signal.signal(sig, func)\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/subprocess_started/","title":"subprocess_started","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/subprocess_started/#faststream.cli.supervisors.utils.subprocess_started","title":"faststream.cli.supervisors.utils.subprocess_started","text":"
subprocess_started(\n    *args: Any,\n    t: DecoratedCallableNone,\n    stdin_fileno: Optional[int]\n) -> None\n

Start a subprocess.

PARAMETER DESCRIPTION *args

Arguments to be passed to the subprocess.

TYPE: Any DEFAULT: ()

t

The decorated callable function.

TYPE: DecoratedCallableNone

stdin_fileno

File descriptor for the standard input of the subprocess.

TYPE: Optional[int]

RETURNS DESCRIPTION None

None

Source code in faststream/cli/supervisors/utils.py
def subprocess_started(\n    *args: Any,\n    t: DecoratedCallableNone,\n    stdin_fileno: Optional[int],\n) -> None:\n    \"\"\"Start a subprocess.\n\n    Args:\n        *args: Arguments to be passed to the subprocess.\n        t: The decorated callable function.\n        stdin_fileno: File descriptor for the standard input of the subprocess.\n\n    Returns:\n        None\n\n    \"\"\"\n    if stdin_fileno is not None:  # pragma: no cover\n        sys.stdin = os.fdopen(stdin_fileno)\n    t(*args)\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/ExtendedFilter/","title":"ExtendedFilter","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/ExtendedFilter/#faststream.cli.supervisors.watchfiles.ExtendedFilter","title":"faststream.cli.supervisors.watchfiles.ExtendedFilter","text":"
ExtendedFilter(\n    *,\n    ignore_paths: Optional[\n        Sequence[Union[str, Path]]\n    ] = None,\n    extra_extensions: Sequence[str] = ()\n)\n

Bases: PythonFilter

A class that extends the watchfiles.PythonFilter class.

METHOD DESCRIPTION __init__

Initializes the ExtendedFilter object Args: ignore_paths : Optional sequence of paths to ignore extra_extensions : Sequence of extra extensions to include

Returns: None

Initialize the class.

PARAMETER DESCRIPTION ignore_paths

Optional sequence of paths to ignore.

TYPE: Optional[Sequence[Union[str, Path]]] DEFAULT: None

extra_extensions

Sequence of extra extensions.

TYPE: Sequence[str] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/cli/supervisors/watchfiles.py
def __init__(\n    self,\n    *,\n    ignore_paths: Optional[Sequence[Union[str, Path]]] = None,\n    extra_extensions: Sequence[str] = (),\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        ignore_paths: Optional sequence of paths to ignore.\n        extra_extensions: Sequence of extra extensions.\n\n    Returns:\n        None\n\n    \"\"\"\n    super().__init__(ignore_paths=ignore_paths, extra_extensions=extra_extensions)\n    self.ignore_dirs = self.ignore_dirs + (\n        \"venv\",\n        \"env\",\n        \".github\",\n        \".mypy_cache\",\n        \".pytest_cache\",\n        \".ruff_cache\",\n        \"__pycache__\",\n    )\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/ExtendedFilter/#faststream.cli.supervisors.watchfiles.ExtendedFilter.ignore_dirs","title":"ignore_dirs instance-attribute","text":"
ignore_dirs: Tuple[str, ...] = self.ignore_dirs + (\n    \"venv\",\n    \"env\",\n    \".github\",\n    \".mypy_cache\",\n    \".pytest_cache\",\n    \".ruff_cache\",\n    \"__pycache__\",\n)\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/","title":"WatchReloader","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader","title":"faststream.cli.supervisors.watchfiles.WatchReloader","text":"
WatchReloader(\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    reload_dirs: Sequence[Union[Path, str]],\n    reload_delay: float = 0.3,\n    extra_extensions: Sequence[str] = (),\n)\n

Bases: BaseReload

A class to reload a target function when files in specified directories change.

METHOD DESCRIPTION should_restart

Checks if any files in the watched directories have changed and returns True if a change is detected, False otherwise.

Initialize a WatchFilesReloader object.

PARAMETER DESCRIPTION target

The target callable to be executed.

TYPE: DecoratedCallable

args

The arguments to be passed to the target callable.

TYPE: Tuple[Any, ...]

reload_dirs

A sequence of directories to watch for changes.

TYPE: Sequence[Union[Path, str]]

reload_delay

The delay in seconds between checking for changes. Default is 0.3.

TYPE: float DEFAULT: 0.3

RETURNS DESCRIPTION None

None.

Source code in faststream/cli/supervisors/watchfiles.py
def __init__(\n    self,\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    reload_dirs: Sequence[Union[Path, str]],\n    reload_delay: float = 0.3,\n    extra_extensions: Sequence[str] = (),\n) -> None:\n    \"\"\"Initialize a WatchFilesReloader object.\n\n    Args:\n        target: The target callable to be executed.\n        args: The arguments to be passed to the target callable.\n        reload_dirs: A sequence of directories to watch for changes.\n        reload_delay: The delay in seconds between checking for changes. Default is 0.3.\n\n    Returns:\n        None.\n\n    \"\"\"\n    super().__init__(target, args, reload_delay)\n    self.reloader_name = \"WatchFiles\"\n    self.reload_dirs = reload_dirs\n    self.watcher = watchfiles.watch(\n        *reload_dirs,\n        step=int(reload_delay * 1000),\n        watch_filter=ExtendedFilter(extra_extensions=extra_extensions),\n        stop_event=self.should_exit,\n        yield_on_timeout=True,\n    )\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.pid","title":"pid instance-attribute","text":"
pid: int = os.getpid()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.reload_delay","title":"reload_delay instance-attribute","text":"
reload_delay: Optional[float] = reload_delay\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.reload_dirs","title":"reload_dirs instance-attribute","text":"
reload_dirs = reload_dirs\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.reloader_name","title":"reloader_name instance-attribute","text":"
reloader_name = 'WatchFiles'\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.should_exit","title":"should_exit instance-attribute","text":"
should_exit: threading.Event = threading.Event()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.watcher","title":"watcher instance-attribute","text":"
watcher = watchfiles.watch(\n    *reload_dirs,\n    step=int(reload_delay * 1000),\n    watch_filter=ExtendedFilter(\n        extra_extensions=extra_extensions\n    ),\n    stop_event=self.should_exit,\n    yield_on_timeout=True\n)\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.restart","title":"restart","text":"
restart() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def restart(self) -> None:\n    self._stop_process()\n    logger.info(\"Process successfully reloaded\")\n    self._process = self._start_process()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.run","title":"run","text":"
run() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def run(self) -> None:\n    self.startup()\n    while not self.should_exit.wait(self.reload_delay):\n        if self.should_restart():  # pragma: no branch\n            self.restart()\n    self.shutdown()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.should_restart","title":"should_restart","text":"
should_restart() -> bool\n
Source code in faststream/cli/supervisors/watchfiles.py
def should_restart(self) -> bool:\n    for changes in self.watcher:  # pragma: no branch\n        if changes:  # pragma: no branch\n            unique_paths = {Path(c[1]).name for c in changes}\n            message = \"WatchReloader detected file change in '%s'. Reloading...\"\n            logger.info(message % tuple(unique_paths))\n            return True\n    return False  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.shutdown","title":"shutdown","text":"
shutdown() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def shutdown(self) -> None:\n    self._stop_process()\n    logger.info(f\"Stopping reloader process [{self.pid}]\")\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.startup","title":"startup","text":"
startup() -> None\n
Source code in faststream/cli/supervisors/watchfiles.py
def startup(self) -> None:\n    logger.info(f\"Will watch for changes in these directories: {self.reload_dirs}\")\n    super().startup()\n
","boost":0.5},{"location":"api/faststream/cli/utils/imports/get_app_path/","title":"get_app_path","text":"","boost":0.5},{"location":"api/faststream/cli/utils/imports/get_app_path/#faststream.cli.utils.imports.get_app_path","title":"faststream.cli.utils.imports.get_app_path","text":"
get_app_path(app: str) -> Tuple[Path, str]\n

Get the application path.

PARAMETER DESCRIPTION app

The name of the application in the format \"module:app_name\".

TYPE: str

RETURNS DESCRIPTION Tuple[Path, str]

Tuple[Path, str]: A tuple containing the path to the module and the name of the application.

RAISES DESCRIPTION ValueError

If the given app is not in the format \"module:app_name\".

Source code in faststream/cli/utils/imports.py
def get_app_path(app: str) -> Tuple[Path, str]:\n    \"\"\"Get the application path.\n\n    Args:\n        app (str): The name of the application in the format \"module:app_name\".\n\n    Returns:\n        Tuple[Path, str]: A tuple containing the path to the module and the name of the application.\n\n    Raises:\n        ValueError: If the given app is not in the format \"module:app_name\".\n\n    \"\"\"\n    if \":\" not in app:\n        raise ValueError(f\"{app} is not a FastStream\")\n\n    module, app_name = app.split(\":\", 2)\n\n    mod_path = Path.cwd()\n    for i in module.split(\".\"):\n        mod_path = mod_path / i\n\n    return mod_path, app_name\n
","boost":0.5},{"location":"api/faststream/cli/utils/imports/import_from_string/","title":"import_from_string","text":"","boost":0.5},{"location":"api/faststream/cli/utils/imports/import_from_string/#faststream.cli.utils.imports.import_from_string","title":"faststream.cli.utils.imports.import_from_string","text":"
import_from_string(\n    import_str: str,\n) -> Tuple[Path, FastStream]\n

Import FastStream application from module specified by a string.

PARAMETER DESCRIPTION import_str

A string in the format \":\" specifying the module and faststream application to import.

TYPE: str

RETURNS DESCRIPTION Tuple[Path, FastStream]

Tuple[ModuleType, FastStream]: A tuple containing the imported module and the faststream application.

RAISES DESCRIPTION BadParameter

Raised if the given value is not of type string, if the import string is not in the format \":\", if the module is not found, or if the faststream appliation is not found in the module. Source code in faststream/cli/utils/imports.py

def import_from_string(import_str: str) -> Tuple[Path, FastStream]:\n    \"\"\"\n    Import FastStream application from module specified by a string.\n\n    Parameters:\n        import_str (str): A string in the format \"<module>:<attribute>\" specifying the module and faststream application to import.\n\n    Returns:\n        Tuple[ModuleType, FastStream]: A tuple containing the imported module and the faststream application.\n\n    Raises:\n        typer.BadParameter: Raised if the given value is not of type string, if the import string is not in the format\n            \"<module>:<attribute>\", if the module is not found, or if the faststream appliation is not found in the module.\n    \"\"\"\n    if not isinstance(import_str, str):\n        raise typer.BadParameter(\"Given value is not of type string\")\n\n    module_str, _, attrs_str = import_str.partition(\":\")\n    if not module_str or not attrs_str:\n        raise typer.BadParameter(\n            f'Import string \"{import_str}\" must be in format \"<module>:<attribute>\"'\n        )\n\n    try:\n        module = importlib.import_module(  # nosemgrep: python.lang.security.audit.non-literal-import.non-literal-import\n            module_str\n        )\n\n    except ModuleNotFoundError:\n        module_path, app_name = get_app_path(import_str)\n        instance = try_import_app(module_path, app_name)\n\n    else:\n        attr = module\n        try:\n            for attr_str in attrs_str.split(\".\"):\n                attr = getattr(attr, attr_str)\n            instance = attr  # type: ignore[assignment]\n\n        except AttributeError as e:\n            typer.echo(e, err=True)\n            raise typer.BadParameter(\n                f'Attribute \"{attrs_str}\" not found in module \"{module_str}\".'\n            ) from e\n\n        if module.__file__:\n            module_path = Path(module.__file__).resolve().parent\n        else:\n            module_path = Path.cwd()\n\n    return module_path, instance\n
","boost":0.5},{"location":"api/faststream/cli/utils/imports/import_object/","title":"import_object","text":"","boost":0.5},{"location":"api/faststream/cli/utils/imports/import_object/#faststream.cli.utils.imports.import_object","title":"faststream.cli.utils.imports.import_object","text":"
import_object(module: Path, app: str) -> object\n

Import an object from a module.

PARAMETER DESCRIPTION module

The path to the module file.

TYPE: Path

app

The name of the object to import.

TYPE: str

RETURNS DESCRIPTION object

The imported object.

RAISES DESCRIPTION FileNotFoundError

If the module file is not found.

ValueError

If the module has no loader.

AttributeError

If the object is not found in the module.

Source code in faststream/cli/utils/imports.py
def import_object(module: Path, app: str) -> object:\n    \"\"\"Import an object from a module.\n\n    Args:\n        module: The path to the module file.\n        app: The name of the object to import.\n\n    Returns:\n        The imported object.\n\n    Raises:\n        FileNotFoundError: If the module file is not found.\n        ValueError: If the module has no loader.\n        AttributeError: If the object is not found in the module.\n\n    \"\"\"\n    spec = spec_from_file_location(\n        \"mode\",\n        f\"{module}.py\",\n        submodule_search_locations=[str(module.parent.absolute())],\n    )\n\n    if spec is None:  # pragma: no cover\n        raise FileNotFoundError(module)\n\n    mod = module_from_spec(spec)\n    loader = spec.loader\n\n    if loader is None:  # pragma: no cover\n        raise ValueError(f\"{spec} has no loader\")\n\n    loader.exec_module(mod)\n\n    try:\n        obj = getattr(mod, app)\n    except AttributeError as e:\n        raise FileNotFoundError(module) from e\n\n    return obj\n
","boost":0.5},{"location":"api/faststream/cli/utils/imports/try_import_app/","title":"try_import_app","text":"","boost":0.5},{"location":"api/faststream/cli/utils/imports/try_import_app/#faststream.cli.utils.imports.try_import_app","title":"faststream.cli.utils.imports.try_import_app","text":"
try_import_app(module: Path, app: str) -> FastStream\n

Tries to import a FastStream app from a module.

PARAMETER DESCRIPTION module

Path to the module containing the app.

TYPE: Path

app

Name of the FastStream app.

TYPE: str

RETURNS DESCRIPTION FastStream

The imported FastStream app object.

RAISES DESCRIPTION FileNotFoundError

If the module file is not found.

BadParameter

If the module or app name is not provided correctly.

Source code in faststream/cli/utils/imports.py
def try_import_app(module: Path, app: str) -> FastStream:\n    \"\"\"Tries to import a FastStream app from a module.\n\n    Args:\n        module: Path to the module containing the app.\n        app: Name of the FastStream app.\n\n    Returns:\n        The imported FastStream app object.\n\n    Raises:\n        FileNotFoundError: If the module file is not found.\n        typer.BadParameter: If the module or app name is not provided correctly.\n\n    \"\"\"\n    try:\n        app_object = import_object(module, app)\n\n    except FileNotFoundError as e:\n        typer.echo(e, err=True)\n        raise typer.BadParameter(\n            \"Please, input module like [python_file:faststream_app_name] or [module:attribute]\"\n        ) from e\n\n    else:\n        return app_object  # type: ignore\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/","title":"LogLevels","text":"","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels","title":"faststream.cli.utils.logs.LogLevels","text":"

Bases: str, Enum

A class to represent log levels.

","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels.critical","title":"critical class-attribute instance-attribute","text":"
critical = 'critical'\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels.debug","title":"debug class-attribute instance-attribute","text":"
debug = 'debug'\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels.error","title":"error class-attribute instance-attribute","text":"
error = 'error'\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels.info","title":"info class-attribute instance-attribute","text":"
info = 'info'\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels.warning","title":"warning class-attribute instance-attribute","text":"
warning = 'warning'\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/get_log_level/","title":"get_log_level","text":"","boost":0.5},{"location":"api/faststream/cli/utils/logs/get_log_level/#faststream.cli.utils.logs.get_log_level","title":"faststream.cli.utils.logs.get_log_level","text":"
get_log_level(level: Union[LogLevels, str, int]) -> int\n

Get the log level.

PARAMETER DESCRIPTION level

The log level to get. Can be an integer, a LogLevels enum value, or a string.

TYPE: Union[LogLevels, str, int]

RETURNS DESCRIPTION int

The log level as an integer.

Source code in faststream/cli/utils/logs.py
def get_log_level(level: Union[LogLevels, str, int]) -> int:\n    \"\"\"Get the log level.\n\n    Args:\n        level: The log level to get. Can be an integer, a LogLevels enum value, or a string.\n\n    Returns:\n        The log level as an integer.\n\n    \"\"\"\n    if isinstance(level, int):\n        return level\n\n    if isinstance(level, LogLevels):\n        return LOG_LEVELS[level.value]\n\n    if isinstance(level, str):  # pragma: no branch\n        return LOG_LEVELS[level.lower()]\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/set_log_level/","title":"set_log_level","text":"","boost":0.5},{"location":"api/faststream/cli/utils/logs/set_log_level/#faststream.cli.utils.logs.set_log_level","title":"faststream.cli.utils.logs.set_log_level","text":"
set_log_level(level: int, app: FastStream) -> None\n

Sets the log level for an application.

PARAMETER DESCRIPTION level

The log level to set.

TYPE: int

app

The application object.

TYPE: FastStream

RETURNS DESCRIPTION None

None

Source code in faststream/cli/utils/logs.py
def set_log_level(level: int, app: FastStream) -> None:\n    \"\"\"Sets the log level for an application.\n\n    Args:\n        level (int): The log level to set.\n        app (FastStream): The application object.\n\n    Returns:\n        None\n\n    \"\"\"\n    if app.logger and isinstance(app.logger, logging.Logger):\n        app.logger.setLevel(level)\n\n    broker_logger: Optional[logging.Logger] = getattr(app.broker, \"logger\", None)\n    if broker_logger is not None and isinstance(broker_logger, logging.Logger):\n        broker_logger.setLevel(level)\n
","boost":0.5},{"location":"api/faststream/cli/utils/parser/parse_cli_args/","title":"parse_cli_args","text":"","boost":0.5},{"location":"api/faststream/cli/utils/parser/parse_cli_args/#faststream.cli.utils.parser.parse_cli_args","title":"faststream.cli.utils.parser.parse_cli_args","text":"
parse_cli_args(\n    *args: str,\n) -> Tuple[str, Dict[str, SettingField]]\n

Parses command line arguments.

PARAMETER DESCRIPTION *args

Command line arguments as strings.

TYPE: str DEFAULT: ()

RETURNS DESCRIPTION Tuple[str, Dict[str, SettingField]]

A tuple containing the application name and a dictionary of additional keyword arguments.

Source code in faststream/cli/utils/parser.py
def parse_cli_args(*args: str) -> Tuple[str, Dict[str, SettingField]]:\n    \"\"\"Parses command line arguments.\n\n    Args:\n        *args: Command line arguments as strings.\n\n    Returns:\n        A tuple containing the application name and a dictionary of additional keyword arguments.\n    \"\"\"\n    extra_kwargs: Dict[str, SettingField] = {}\n\n    k: str = \"\"\n    v: SettingField\n\n    field_args: List[str] = []\n    app = \"\"\n    for item in reduce(\n        lambda acc, x: acc + x.split(\"=\"),  # type: ignore\n        args,\n        [],\n    ) + [\"-\"]:\n        if \":\" in item:\n            app = item\n\n        else:\n            if \"-\" in item:\n                if k:\n                    k = k.strip().lstrip(\"-\").replace(\"-\", \"_\")\n\n                    if len(field_args) == 0:\n                        v = not k.startswith(\"no_\")\n                    elif len(field_args) == 1:\n                        v = field_args[0]\n                    else:\n                        v = field_args\n\n                    key = remove_prefix(k, \"no_\")\n                    if (exists := extra_kwargs.get(key)) is not None:\n                        if not isinstance(exists, list):\n                            v = [exists, v]\n                        else:\n                            v = exists + [v]\n\n                    extra_kwargs[key] = v\n                    field_args = []\n\n                k = item\n\n            else:\n                field_args.append(item)\n\n    return app, extra_kwargs\n
","boost":0.5},{"location":"api/faststream/cli/utils/parser/remove_prefix/","title":"remove_prefix","text":"","boost":0.5},{"location":"api/faststream/cli/utils/parser/remove_prefix/#faststream.cli.utils.parser.remove_prefix","title":"faststream.cli.utils.parser.remove_prefix","text":"
remove_prefix(text: str, prefix: str) -> str\n

Removes a prefix from a given text.

Python 3.8 compatibility function

PARAMETER DESCRIPTION text

The text from which the prefix will be removed.

TYPE: str

prefix

The prefix to be removed from the text.

TYPE: str

RETURNS DESCRIPTION str

The text with the prefix removed. If the text does not start with the prefix, the original text is returned.

TYPE: str

Source code in faststream/cli/utils/parser.py
def remove_prefix(text: str, prefix: str) -> str:\n    \"\"\"Removes a prefix from a given text.\n\n    Python 3.8 compatibility function\n\n    Args:\n        text (str): The text from which the prefix will be removed.\n        prefix (str): The prefix to be removed from the text.\n\n    Returns:\n        str: The text with the prefix removed. If the text does not start with the prefix, the original text is returned.\n    \"\"\"\n    if text.startswith(prefix):\n        return text[len(prefix) :]\n    return text\n
","boost":0.5},{"location":"api/faststream/constants/ContentTypes/","title":"ContentTypes","text":"","boost":0.5},{"location":"api/faststream/constants/ContentTypes/#faststream.constants.ContentTypes","title":"faststream.constants.ContentTypes","text":"

Bases: str, Enum

A class to represent content types.

","boost":0.5},{"location":"api/faststream/constants/ContentTypes/#faststream.constants.ContentTypes.json","title":"json class-attribute instance-attribute","text":"
json = 'application/json'\n
","boost":0.5},{"location":"api/faststream/constants/ContentTypes/#faststream.constants.ContentTypes.text","title":"text class-attribute instance-attribute","text":"
text = 'text/plain'\n
","boost":0.5},{"location":"api/faststream/exceptions/AckMessage/","title":"AckMessage","text":"","boost":0.5},{"location":"api/faststream/exceptions/AckMessage/#faststream.exceptions.AckMessage","title":"faststream.exceptions.AckMessage","text":"

Bases: HandlerException

Raise it to ack a message immediately

","boost":0.5},{"location":"api/faststream/exceptions/HandlerException/","title":"HandlerException","text":"","boost":0.5},{"location":"api/faststream/exceptions/HandlerException/#faststream.exceptions.HandlerException","title":"faststream.exceptions.HandlerException","text":"

Bases: Exception

Base Handler Exception

","boost":0.5},{"location":"api/faststream/exceptions/NackMessage/","title":"NackMessage","text":"","boost":0.5},{"location":"api/faststream/exceptions/NackMessage/#faststream.exceptions.NackMessage","title":"faststream.exceptions.NackMessage","text":"

Bases: HandlerException

Raise it to nack a message immediately

","boost":0.5},{"location":"api/faststream/exceptions/RejectMessage/","title":"RejectMessage","text":"","boost":0.5},{"location":"api/faststream/exceptions/RejectMessage/#faststream.exceptions.RejectMessage","title":"faststream.exceptions.RejectMessage","text":"

Bases: HandlerException

Raise it to reject a message immediately

","boost":0.5},{"location":"api/faststream/exceptions/SkipMessage/","title":"SkipMessage","text":"","boost":0.5},{"location":"api/faststream/exceptions/SkipMessage/#faststream.exceptions.SkipMessage","title":"faststream.exceptions.SkipMessage","text":"

Bases: Exception

Watcher Instruction to skip message

","boost":0.5},{"location":"api/faststream/exceptions/StopConsume/","title":"StopConsume","text":"","boost":0.5},{"location":"api/faststream/exceptions/StopConsume/#faststream.exceptions.StopConsume","title":"faststream.exceptions.StopConsume","text":"

Bases: Exception

Raise it to stop Handler consuming

","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/","title":"KafkaBroker","text":"","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker","title":"faststream.kafka.KafkaBroker","text":"
KafkaBroker(\n    bootstrap_servers: Union[\n        str, Iterable[str]\n    ] = \"localhost\",\n    *,\n    protocol: str = None,\n    protocol_version: str = \"auto\",\n    client_id: str = \"faststream-\" + __version__,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: KafkaLoggingMixin, BrokerAsyncUsecase[ConsumerRecord, ConsumerConnectionParams]

KafkaBroker is a class for managing Kafka message consumption and publishing. It extends BrokerAsyncUsecase to handle asynchronous operations.

PARAMETER DESCRIPTION bootstrap_servers

Kafka bootstrap server(s).

TYPE: Union[str, Iterable[str]] DEFAULT: 'localhost'

protocol

The protocol used (default is \"kafka\").

TYPE: str DEFAULT: None

protocol_version

The Kafka protocol version (default is \"auto\").

TYPE: str DEFAULT: 'auto'

client_id

The client ID for the Kafka client.

TYPE: str DEFAULT: 'faststream-' + __version__

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

METHOD DESCRIPTION connect

Establishes a connection to Kafka.

start

Starts the KafkaBroker and message handlers.

publish

Publishes a message to Kafka.

Initialize a KafkaBroker instance.

PARAMETER DESCRIPTION bootstrap_servers

Kafka bootstrap server(s).

TYPE: Union[str, Iterable[str]] DEFAULT: 'localhost'

protocol

The protocol used (default is \"kafka\").

TYPE: str DEFAULT: None

protocol_version

The Kafka protocol version (default is \"auto\").

TYPE: str DEFAULT: 'auto'

client_id

The client ID for the Kafka client.

TYPE: str DEFAULT: 'faststream-' + __version__

security

Security protocol to use in communication with the broker (default is None).

TYPE: Optional[BaseSecurity] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/kafka/broker.py
def __init__(\n    self,\n    bootstrap_servers: Union[str, Iterable[str]] = \"localhost\",\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: str = \"auto\",\n    client_id: str = \"faststream-\" + __version__,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Initialize a KafkaBroker instance.\n\n    Args:\n        bootstrap_servers (Union[str, Iterable[str]]): Kafka bootstrap server(s).\n        protocol (str): The protocol used (default is \"kafka\").\n        protocol_version (str): The Kafka protocol version (default is \"auto\").\n        client_id (str): The client ID for the Kafka client.\n        security (Optional[BaseSecurity]): Security protocol to use in communication with the broker (default is None).\n        **kwargs: Additional keyword arguments.\n    \"\"\"\n    if protocol is None:\n        if security is not None and security.use_ssl:\n            protocol = \"kafka-secure\"\n        else:\n            protocol = \"kafka\"\n\n    super().__init__(\n        url=[bootstrap_servers]\n        if isinstance(bootstrap_servers, str)\n        else list(bootstrap_servers),\n        protocol=protocol,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n        client_id=client_id,\n        bootstrap_servers=bootstrap_servers,\n    )\n    self.client_id = client_id\n    self._producer = None\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.client_id","title":"client_id instance-attribute","text":"
client_id = client_id\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[str, Handler]\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.url","title":"url instance-attribute","text":"
url: List[str]\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.connect","title":"connect async","text":"
connect(\n    *args: Any, **kwargs: Any\n) -> ConsumerConnectionParams\n

Establishes a connection to Kafka and returns connection parameters.

PARAMETER DESCRIPTION *args

Additional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION ConsumerConnectionParams

The connection parameters.

TYPE: ConsumerConnectionParams

Source code in faststream/kafka/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> ConsumerConnectionParams:\n    \"\"\"\n    Establishes a connection to Kafka and returns connection parameters.\n\n    Args:\n        *args: Additional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        ConsumerConnectionParams: The connection parameters.\n    \"\"\"\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.publish","title":"publish async","text":"
publish(*args: Any, **kwargs: Any) -> None\n

Publish a message to Kafka.

PARAMETER DESCRIPTION *args

Positional arguments for message publishing.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments for message publishing.

TYPE: Any DEFAULT: {}

RAISES DESCRIPTION RuntimeError

If KafkaBroker is not started yet.

Source code in faststream/kafka/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Publish a message to Kafka.\n\n    Args:\n        *args: Positional arguments for message publishing.\n        **kwargs: Keyword arguments for message publishing.\n\n    Raises:\n        RuntimeError: If KafkaBroker is not started yet.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.publish_batch","title":"publish_batch async","text":"
publish_batch(*args: Any, **kwargs: Any) -> None\n

Publish a batch of messages to Kafka.

PARAMETER DESCRIPTION *args

Positional arguments for message publishing.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments for message publishing.

TYPE: Any DEFAULT: {}

RAISES DESCRIPTION RuntimeError

If KafkaBroker is not started yet.

Source code in faststream/kafka/broker.py
async def publish_batch(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Publish a batch of messages to Kafka.\n\n    Args:\n        *args: Positional arguments for message publishing.\n        **kwargs: Keyword arguments for message publishing.\n\n    Raises:\n        RuntimeError: If KafkaBroker is not started yet.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    await self._producer.publish_batch(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.publisher","title":"publisher","text":"
publisher(\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n

Create a message publisher for the specified topic.

PARAMETER DESCRIPTION topic

The topic to publish messages to.

TYPE: str

key

Message key.

TYPE: Optional[bytes] DEFAULT: None

partition

Partition to send the message to.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

Message timestamp in milliseconds.

TYPE: Optional[int] DEFAULT: None

headers

Message headers.

TYPE: Optional[Dict[str, str]] DEFAULT: None

reply_to

The topic to which responses should be sent.

TYPE: str DEFAULT: ''

batch

Whether to publish messages in batches.

TYPE: bool DEFAULT: False

title

AsyncAPI title.

TYPE: Optional[str] DEFAULT: None

description

AsyncAPI description.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION Publisher

A message publisher.

TYPE: Publisher

Source code in faststream/kafka/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"\n    Create a message publisher for the specified topic.\n\n    Args:\n        topic (str): The topic to publish messages to.\n        key (Optional[bytes]): Message key.\n        partition (Optional[int]): Partition to send the message to.\n        timestamp_ms (Optional[int]): Message timestamp in milliseconds.\n        headers (Optional[Dict[str, str]]): Message headers.\n        reply_to (str): The topic to which responses should be sent.\n        batch (bool): Whether to publish messages in batches.\n        title (Optional[str]): AsyncAPI title.\n        description (Optional[str]): AsyncAPI description.\n\n    Returns:\n        Publisher: A message publisher.\n    \"\"\"\n    publisher = self._publishers.get(\n        topic,\n        Publisher(\n            topic=topic,\n            client_id=self.client_id,\n            key=key,\n            batch=batch,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(topic, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.start","title":"start async","text":"
start() -> None\n

Start the KafkaBroker and message handlers.

Source code in faststream/kafka/broker.py
async def start(self) -> None:\n    \"\"\"\n    Start the KafkaBroker and message handlers.\n    \"\"\"\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n\n    for handler in self.handlers.values():\n        c = self._get_log_context(None, handler.topics, handler.group_id)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(**(self._connection or {}))\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.subscriber","title":"subscriber","text":"
subscriber(\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    value_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\", \"earliest\", \"none\"\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[\n        AbstractPartitionAssignor\n    ] = (RoundRobinPartitionAssignor),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\", \"read_committed\"\n    ] = \"read_uncommitted\",\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        Union[\n            CustomParser[\n                aiokafka.ConsumerRecord, KafkaMessage\n            ],\n            CustomParser[\n                Tuple[aiokafka.ConsumerRecord, ...],\n                KafkaMessage,\n            ],\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[\n            StreamMessage[\n                Tuple[aiokafka.ConsumerRecord, ...]\n            ]\n        ],\n    ] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    Union[\n        HandlerCallWrapper[\n            aiokafka.ConsumerRecord,\n            P_HandlerParams,\n            T_HandlerReturn,\n        ],\n        HandlerCallWrapper[\n            Tuple[aiokafka.ConsumerRecord, ...],\n            P_HandlerParams,\n            T_HandlerReturn,\n        ],\n    ],\n]\n

Create a message subscriber for the specified topics.

PARAMETER DESCRIPTION *topics

The topics to subscribe to.

TYPE: str DEFAULT: ()

group_id

The Kafka consumer group ID.

TYPE: Optional[str] DEFAULT: None

key_deserializer

Key deserializer function.

TYPE: Optional[Callable[[bytes], Any]] DEFAULT: None

value_deserializer

Value deserializer function.

TYPE: Optional[Callable[[bytes], Any]] DEFAULT: None

fetch_max_wait_ms

The maximum time to wait for data.

TYPE: int DEFAULT: 500

fetch_max_bytes

The maximum number of bytes to fetch.

TYPE: int DEFAULT: 52428800

fetch_min_bytes

The minimum number of bytes to fetch.

TYPE: int DEFAULT: 1

max_partition_fetch_bytes

The maximum bytes to fetch for a partition.

TYPE: int DEFAULT: 1 * 1024 * 1024

auto_offset_reset

Auto offset reset policy.

TYPE: Literal['latest', 'earliest', 'none'] DEFAULT: 'latest'

auto_commit

Whether to enable auto-commit.

TYPE: bool DEFAULT: True

auto_commit_interval_ms

Auto-commit interval in milliseconds.

TYPE: int DEFAULT: 5000

check_crcs

Whether to check CRCs.

TYPE: bool DEFAULT: True

partition_assignment_strategy

Partition assignment strategy.

TYPE: Sequence[AbstractPartitionAssignor] DEFAULT: (RoundRobinPartitionAssignor)

max_poll_interval_ms

Maximum poll interval in milliseconds.

TYPE: int DEFAULT: 300000

rebalance_timeout_ms

Rebalance timeout in milliseconds.

TYPE: Optional[int] DEFAULT: None

session_timeout_ms

Session timeout in milliseconds.

TYPE: int DEFAULT: 10000

heartbeat_interval_ms

Heartbeat interval in milliseconds.

TYPE: int DEFAULT: 3000

consumer_timeout_ms

Consumer timeout in milliseconds.

TYPE: int DEFAULT: 200

max_poll_records

Maximum number of records to poll.

TYPE: Optional[int] DEFAULT: None

exclude_internal_topics

Whether to exclude internal topics.

TYPE: bool DEFAULT: True

isolation_level

Isolation level.

TYPE: Literal['read_uncommitted', 'read_committed'] DEFAULT: 'read_uncommitted'

dependencies

Additional dependencies for message handling.

TYPE: Sequence[Depends] DEFAULT: ()

parser

Message parser.

TYPE: Optional[Union[CustomParser[ConsumerRecord], CustomParser[Tuple[ConsumerRecord, ...]]]] DEFAULT: None

decoder

Message decoder.

TYPE: Optional[CustomDecoder] DEFAULT: None

middlewares

Message middlewares.

TYPE: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]] DEFAULT: None

filter

Message filter.

TYPE: Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[ConsumerRecord, ...]]]] DEFAULT: default_filter

batch

Whether to process messages in batches.

TYPE: bool DEFAULT: False

max_records

Maximum number of records to process in each batch.

TYPE: Optional[int] DEFAULT: None

batch_timeout_ms

Batch timeout in milliseconds.

TYPE: int DEFAULT: 200

no_ack

Whether not to ack/nack/reject messages.

TYPE: bool DEFAULT: False

title

AsyncAPI title.

TYPE: Optional[str] DEFAULT: None

description

AsyncAPI description.

TYPE: Optional[str] DEFAULT: None

**original_kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Callable

A decorator that wraps a message handler function.

TYPE: Callable[[Callable[P_HandlerParams, T_HandlerReturn]], Union[HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[Tuple[ConsumerRecord, ...], P_HandlerParams, T_HandlerReturn]]]

Source code in faststream/kafka/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[Callable[[bytes], Any]] = None,\n    value_deserializer: Optional[Callable[[bytes], Any]] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\",\n        \"earliest\",\n        \"none\",\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[AbstractPartitionAssignor] = (\n        RoundRobinPartitionAssignor,\n    ),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\",\n        \"read_committed\",\n    ] = \"read_uncommitted\",\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        Union[\n            CustomParser[aiokafka.ConsumerRecord, KafkaMessage],\n            CustomParser[Tuple[aiokafka.ConsumerRecord, ...], KafkaMessage],\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord],\n                BaseMiddleware,\n            ]\n        ]\n    ] = None,\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[aiokafka.ConsumerRecord, ...]]],\n    ] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    Union[\n        HandlerCallWrapper[\n            aiokafka.ConsumerRecord, P_HandlerParams, T_HandlerReturn\n        ],\n        HandlerCallWrapper[\n            Tuple[aiokafka.ConsumerRecord, ...], P_HandlerParams, T_HandlerReturn\n        ],\n    ],\n]:\n    \"\"\"\n    Create a message subscriber for the specified topics.\n\n    Args:\n        *topics (str): The topics to subscribe to.\n        group_id (Optional[str]): The Kafka consumer group ID.\n        key_deserializer (Optional[Callable[[bytes], Any]]): Key deserializer function.\n        value_deserializer (Optional[Callable[[bytes], Any]]): Value deserializer function.\n        fetch_max_wait_ms (int): The maximum time to wait for data.\n        fetch_max_bytes (int): The maximum number of bytes to fetch.\n        fetch_min_bytes (int): The minimum number of bytes to fetch.\n        max_partition_fetch_bytes (int): The maximum bytes to fetch for a partition.\n        auto_offset_reset (Literal[\"latest\", \"earliest\", \"none\"]): Auto offset reset policy.\n        auto_commit (bool): Whether to enable auto-commit.\n        auto_commit_interval_ms (int): Auto-commit interval in milliseconds.\n        check_crcs (bool): Whether to check CRCs.\n        partition_assignment_strategy (Sequence[AbstractPartitionAssignor]): Partition assignment strategy.\n        max_poll_interval_ms (int): Maximum poll interval in milliseconds.\n        rebalance_timeout_ms (Optional[int]): Rebalance timeout in milliseconds.\n        session_timeout_ms (int): Session timeout in milliseconds.\n        heartbeat_interval_ms (int): Heartbeat interval in milliseconds.\n        consumer_timeout_ms (int): Consumer timeout in milliseconds.\n        max_poll_records (Optional[int]): Maximum number of records to poll.\n        exclude_internal_topics (bool): Whether to exclude internal topics.\n        isolation_level (Literal[\"read_uncommitted\", \"read_committed\"]): Isolation level.\n        dependencies (Sequence[Depends]): Additional dependencies for message handling.\n        parser (Optional[Union[CustomParser[aiokafka.ConsumerRecord], CustomParser[Tuple[aiokafka.ConsumerRecord, ...]]]]): Message parser.\n        decoder (Optional[CustomDecoder]): Message decoder.\n        middlewares (Optional[Sequence[Callable[[aiokafka.ConsumerRecord], BaseMiddleware]]]): Message middlewares.\n        filter (Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[aiokafka.ConsumerRecord, ...]]]]): Message filter.\n        batch (bool): Whether to process messages in batches.\n        max_records (Optional[int]): Maximum number of records to process in each batch.\n        batch_timeout_ms (int): Batch timeout in milliseconds.\n        no_ack (bool): Whether not to ack/nack/reject messages.\n        title (Optional[str]): AsyncAPI title.\n        description (Optional[str]): AsyncAPI description.\n        **original_kwargs: Additional keyword arguments.\n\n    Returns:\n        Callable: A decorator that wraps a message handler function.\n    \"\"\"\n    super().subscriber()\n\n    self._setup_log_context(topics, group_id)\n\n    if not auto_commit and not group_id:\n        raise ValueError(\"You should install `group_id` with manual commit mode\")\n\n    key = Handler.get_routing_hash(topics, group_id)\n    builder = partial(\n        aiokafka.AIOKafkaConsumer,\n        key_deserializer=key_deserializer,\n        value_deserializer=value_deserializer,\n        fetch_max_wait_ms=fetch_max_wait_ms,\n        fetch_max_bytes=fetch_max_bytes,\n        fetch_min_bytes=fetch_min_bytes,\n        max_partition_fetch_bytes=max_partition_fetch_bytes,\n        auto_offset_reset=auto_offset_reset,\n        enable_auto_commit=auto_commit,\n        auto_commit_interval_ms=auto_commit_interval_ms,\n        check_crcs=check_crcs,\n        partition_assignment_strategy=partition_assignment_strategy,\n        max_poll_interval_ms=max_poll_interval_ms,\n        rebalance_timeout_ms=rebalance_timeout_ms,\n        session_timeout_ms=session_timeout_ms,\n        heartbeat_interval_ms=heartbeat_interval_ms,\n        consumer_timeout_ms=consumer_timeout_ms,\n        max_poll_records=max_poll_records,\n        exclude_internal_topics=exclude_internal_topics,\n        isolation_level=isolation_level,\n    )\n    handler = self.handlers.get(\n        key,\n        Handler(\n            *topics,\n            log_context_builder=partial(\n                self._get_log_context,\n                topics=topics,\n                group_id=group_id,\n            ),\n            is_manual=not auto_commit,\n            group_id=group_id,\n            client_id=self.client_id,\n            builder=builder,\n            description=description,\n            title=title,\n            batch=batch,\n            batch_timeout_ms=batch_timeout_ms,\n            max_records=max_records,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n        ),\n    )\n\n    self.handlers[key] = handler\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[\n        aiokafka.ConsumerRecord, P_HandlerParams, T_HandlerReturn\n    ]:\n        \"\"\"A wrapper function for a consumer handler.\n\n        Args:\n            func : The consumer handler function to be wrapped.\n\n        Returns:\n            The wrapped handler call.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        handler_call, dependant = self._wrap_handler(\n            func=func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRoute/","title":"KafkaRoute","text":"","boost":0.5},{"location":"api/faststream/kafka/KafkaRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/","title":"KafkaRouter","text":"","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter","title":"faststream.kafka.KafkaRouter","text":"
KafkaRouter(\n    prefix: str = \"\",\n    handlers: Sequence[KafkaRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[aiokafka.ConsumerRecord, KafkaMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[KafkaMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: KafkaRouter

A class to represent a Kafka router.

METHOD DESCRIPTION _get_publisher_key

Get the key for a publisher

_update_publisher_prefix

Update the prefix of a publisher

publisher

Create a new publisher

Source code in faststream/kafka/router.py
        publisher: The publisher object.\n\n    Returns:\n        The publisher key.\n\n    \"\"\"\n    return publisher.topic\n\n@override\n@staticmethod\ndef _update_publisher_prefix(  # type: ignore[override]\n    prefix: str,\n    publisher: Publisher,\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.publisher","title":"publisher","text":"
publisher(\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n

Publishes a message to a topic.

PARAMETER DESCRIPTION topic

The topic to publish the message to.

TYPE: str

key

The key associated with the message.

TYPE: bytes DEFAULT: None

partition

The partition to publish the message to.

TYPE: int DEFAULT: None

timestamp_ms

The timestamp of the message in milliseconds.

TYPE: int DEFAULT: None

headers

Additional headers for the message.

TYPE: Dict[str, str] DEFAULT: None

reply_to

The topic to reply to.

TYPE: str DEFAULT: ''

batch

Whether to publish the message as part of a batch.

TYPE: bool DEFAULT: False

title

The title of the message.

TYPE: str DEFAULT: None

description

The description of the message.

TYPE: str DEFAULT: None

RETURNS DESCRIPTION Publisher

The publisher object used to publish the message.

TYPE: Publisher

Source code in faststream/kafka/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"Publishes a message to a topic.\n\n    Args:\n        topic (str): The topic to publish the message to.\n        key (bytes, optional): The key associated with the message.\n        partition (int, optional): The partition to publish the message to.\n        timestamp_ms (int, optional): The timestamp of the message in milliseconds.\n        headers (Dict[str, str], optional): Additional headers for the message.\n        reply_to (str, optional): The topic to reply to.\n        batch (bool, optional): Whether to publish the message as part of a batch.\n        title (str, optional): The title of the message.\n        description (str, optional): The description of the message.\n\n    Returns:\n        Publisher: The publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            topic=topic,\n            key=key,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            batch=batch,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.subscriber","title":"subscriber","text":"
subscriber(\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    value_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\", \"earliest\", \"none\"\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[\n        AbstractPartitionAssignor\n    ] = (RoundRobinPartitionAssignor),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\", \"read_committed\"\n    ] = \"read_uncommitted\",\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[aiokafka.ConsumerRecord, KafkaMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[KafkaMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Filter[KafkaMessage] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    retry: Union[bool, int] = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aiokafka.ConsumerRecord,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n
Source code in faststream/kafka/router.py
    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"Publishes a message to a topic.\n\n    Args:\n        topic (str): The topic to publish the message to.\n        key (bytes, optional): The key associated with the message.\n        partition (int, optional): The partition to publish the message to.\n        timestamp_ms (int, optional): The timestamp of the message in milliseconds.\n        headers (Dict[str, str], optional): Additional headers for the message.\n        reply_to (str, optional): The topic to reply to.\n        batch (bool, optional): Whether to publish the message as part of a batch.\n        title (str, optional): The title of the message.\n        description (str, optional): The description of the message.\n\n    Returns:\n        Publisher: The publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            topic=topic,\n            key=key,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            batch=batch,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/kafka/TestApp/#faststream.broker.test.TestApp","title":"faststream.broker.test.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/kafka/TestApp/#faststream.broker.test.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/","title":"TestKafkaBroker","text":"","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker","title":"faststream.kafka.TestKafkaBroker","text":"
TestKafkaBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[KafkaBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/kafka/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: KafkaBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(  # type: ignore[call-overload,misc]\n        publisher.topic,\n        batch=publisher.batch,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f  # type: ignore[no-any-return]\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: KafkaBroker, publisher: Any\n) -> None\n
Source code in faststream/kafka/test.py
@staticmethod\ndef patch_publisher(broker: KafkaBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> None\n
Source code in faststream/kafka/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> None:\n    broker.handlers.pop(publisher.topic, None)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/","title":"Handler","text":"","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler","title":"faststream.kafka.asyncapi.Handler","text":"
Handler(\n    *topics: str,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    group_id: Optional[str] = None,\n    client_id: str = \"faststream-\" + __version__,\n    builder: Callable[..., AIOKafkaConsumer],\n    is_manual: bool = False,\n    batch: bool = False,\n    batch_timeout_ms: int = 200,\n    max_records: Optional[int] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True\n)\n

Bases: LogicHandler, AsyncAPIOperation

A class to handle logic and async API operations.

METHOD DESCRIPTION schema

Returns a dictionary of channels.

Initialize a Kafka consumer for the specified topics.

PARAMETER DESCRIPTION *topics

Variable length argument list of topics to consume from.

TYPE: str DEFAULT: ()

group_id

Optional group ID for the consumer.

TYPE: Optional[str] DEFAULT: None

client_id

Client ID for the consumer.

TYPE: str DEFAULT: 'faststream-' + __version__

builder

Callable that constructs an AIOKafkaConsumer instance.

TYPE: Callable[..., AIOKafkaConsumer]

batch

Flag indicating whether to consume messages in batches.

TYPE: bool DEFAULT: False

batch_timeout_ms

Timeout in milliseconds for batch consumption.

TYPE: int DEFAULT: 200

max_records

Maximum number of records to consume in a batch.

TYPE: Optional[int] DEFAULT: None

title

Optional title for the consumer.

TYPE: Optional[str] DEFAULT: None

description

Optional description for the consumer.

TYPE: Optional[str] DEFAULT: None

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/kafka/handler.py
@override\ndef __init__(\n    self,\n    *topics: str,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # Kafka information\n    group_id: Optional[str] = None,\n    client_id: str = \"faststream-\" + __version__,\n    builder: Callable[..., AIOKafkaConsumer],\n    is_manual: bool = False,\n    batch: bool = False,\n    batch_timeout_ms: int = 200,\n    max_records: Optional[int] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    \"\"\"Initialize a Kafka consumer for the specified topics.\n\n    Args:\n        *topics: Variable length argument list of topics to consume from.\n        group_id: Optional group ID for the consumer.\n        client_id: Client ID for the consumer.\n        builder: Callable that constructs an AIOKafkaConsumer instance.\n        batch: Flag indicating whether to consume messages in batches.\n        batch_timeout_ms: Timeout in milliseconds for batch consumption.\n        max_records: Maximum number of records to consume in a batch.\n        title: Optional title for the consumer.\n        description: Optional description for the consumer.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.group_id = group_id\n    self.client_id = client_id\n    self.topics = topics\n\n    self.batch = batch\n    self.batch_timeout_ms = batch_timeout_ms\n    self.max_records = max_records\n    self.is_manual = is_manual\n\n    self.builder = builder\n    self.task = None\n    self.consumer = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = batch\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.batch_timeout_ms","title":"batch_timeout_ms instance-attribute","text":"
batch_timeout_ms = batch_timeout_ms\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.builder","title":"builder instance-attribute","text":"
builder = builder\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.client_id","title":"client_id instance-attribute","text":"
client_id = client_id\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.consumer","title":"consumer class-attribute instance-attribute","text":"
consumer: Optional[AIOKafkaConsumer] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.group_id","title":"group_id class-attribute instance-attribute","text":"
group_id: Optional[str] = group_id\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.is_manual","title":"is_manual instance-attribute","text":"
is_manual = is_manual\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.max_records","title":"max_records instance-attribute","text":"
max_records = max_records\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.task","title":"task class-attribute instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.topics","title":"topics instance-attribute","text":"
topics: Sequence[str] = topics\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        ConsumerRecord, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: CustomParser[\n        Union[ConsumerRecord, Tuple[ConsumerRecord, ...]],\n        KafkaMessage,\n    ],\n    decoder: Optional[CustomDecoder[KafkaMessage]],\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[ConsumerRecord, ...]]],\n    ],\n    middlewares: Optional[\n        Sequence[Callable[[ConsumerRecord], BaseMiddleware]]\n    ]\n) -> None\n

Adds a call to the handler.

PARAMETER DESCRIPTION handler

The handler function to be called.

TYPE: HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn]

dependant

The dependant model.

TYPE: CallModel[P_HandlerParams, T_HandlerReturn]

parser

Optional custom parser for parsing the input.

TYPE: CustomParser[Union[ConsumerRecord, Tuple[ConsumerRecord, ...]], KafkaMessage]

decoder

Optional custom decoder for decoding the input.

TYPE: Optional[CustomDecoder[KafkaMessage]]

filter

The filter for filtering the input.

TYPE: Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[ConsumerRecord, ...]]]]

middlewares

Optional sequence of middlewares to be applied.

TYPE: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]]

RETURNS DESCRIPTION None

None

Source code in faststream/kafka/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: CustomParser[\n        Union[ConsumerRecord, Tuple[ConsumerRecord, ...]], KafkaMessage\n    ],\n    decoder: Optional[CustomDecoder[KafkaMessage]],\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[ConsumerRecord, ...]]],\n    ],\n    middlewares: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]],\n) -> None:\n    \"\"\"Adds a call to the handler.\n\n    Args:\n        handler: The handler function to be called.\n        dependant: The dependant model.\n        parser: Optional custom parser for parsing the input.\n        decoder: Optional custom decoder for decoding the input.\n        filter: The filter for filtering the input.\n        middlewares: Optional sequence of middlewares to be applied.\n\n    Returns:\n        None\n\n    \"\"\"\n    parser_ = resolve_custom_func(  # type: ignore[type-var]\n        parser,  # type: ignore[arg-type]\n        (\n            AioKafkaParser.parse_message_batch  # type: ignore[arg-type]\n            if self.batch\n            else AioKafkaParser.parse_message\n        ),\n    )\n    decoder_ = resolve_custom_func(\n        decoder,  # type: ignore[arg-type]\n        (\n            AioKafkaParser.decode_message_batch  # type: ignore[arg-type]\n            if self.batch\n            else AioKafkaParser.decode_message\n        ),\n    )\n    super().add_call(\n        handler=handler,\n        parser=parser_,\n        decoder=decoder_,\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/kafka/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.consumer is not None:\n        await self.consumer.stop()\n        self.consumer = None\n\n    if self.task is not None:\n        self.task.cancel()\n        self.task = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(\n    topics: Sequence[str], group_id: Optional[str] = None\n) -> str\n
Source code in faststream/kafka/handler.py
@staticmethod\ndef get_routing_hash(topics: Sequence[str], group_id: Optional[str] = None) -> str:\n    return \"\".join((*topics, group_id or \"\"))\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/kafka/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    channels = {}\n\n    payloads = self.get_payloads()\n\n    for t in self.topics:\n        handler_name = self._title or f\"{t}:{self.call_name}\"\n        channels[handler_name] = Channel(\n            description=self.description,\n            subscribe=Operation(\n                message=Message(\n                    title=f\"{handler_name}:Message\",\n                    payload=resolve_payloads(payloads),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(kafka=kafka.ChannelBinding(topic=t)),\n        )\n\n    return channels\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.start","title":"start async","text":"
start(\n    **consumer_kwargs: Unpack[ConsumerConnectionParams],\n) -> None\n

Start the consumer.

PARAMETER DESCRIPTION **consumer_kwargs

Additional keyword arguments to pass to the consumer.

TYPE: Unpack[ConsumerConnectionParams] DEFAULT: {}

RETURNS DESCRIPTION None

None

Source code in faststream/kafka/handler.py
@override\nasync def start(  # type: ignore[override]\n    self,\n    **consumer_kwargs: Unpack[ConsumerConnectionParams],\n) -> None:\n    \"\"\"Start the consumer.\n\n    Args:\n        **consumer_kwargs: Additional keyword arguments to pass to the consumer.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.consumer = consumer = self.builder(\n        *self.topics,\n        group_id=self.group_id,\n        client_id=self.client_id,\n        **consumer_kwargs,\n    )\n    await consumer.start()\n    self.task = asyncio.create_task(self._consume())\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/","title":"Publisher","text":"","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher","title":"faststream.kafka.asyncapi.Publisher","text":"

Bases: LogicPublisher, AsyncAPIOperation

A class representing a publisher.

METHOD DESCRIPTION schema

returns the schema for the publisher

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported

","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = field(default=False)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.client_id","title":"client_id class-attribute instance-attribute","text":"
client_id: str = field(default='faststream-' + __version__)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.key","title":"key class-attribute instance-attribute","text":"
key: Optional[bytes] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.name","title":"name property","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.partition","title":"partition class-attribute instance-attribute","text":"
partition: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = ''\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.timestamp_ms","title":"timestamp_ms class-attribute instance-attribute","text":"
timestamp_ms: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.topic","title":"topic class-attribute instance-attribute","text":"
topic: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.publish","title":"publish async","text":"
publish(\n    *messages: SendableMessage,\n    message: SendableMessage = \"\",\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None\n) -> None\n

Publish messages to a topic.

PARAMETER DESCRIPTION *messages

Variable length argument list of SendableMessage objects.

TYPE: SendableMessage DEFAULT: ()

message

A SendableMessage object. Default is an empty string.

TYPE: SendableMessage DEFAULT: ''

key

Optional bytes object representing the message key.

TYPE: Optional[bytes] DEFAULT: None

partition

Optional integer representing the partition to publish the message to.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

Optional integer representing the timestamp of the message in milliseconds.

TYPE: Optional[int] DEFAULT: None

headers

Optional dictionary of header key-value pairs.

TYPE: Optional[Dict[str, str]] DEFAULT: None

correlation_id

Optional string representing the correlation ID of the message.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION AssertionError

If _producer is not set up.

AssertionError

If batch flag is not set and there are multiple messages.

ValueError

If message is not a sequence when messages is empty.

Source code in faststream/kafka/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *messages: SendableMessage,\n    message: SendableMessage = \"\",\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n) -> None:\n    \"\"\"Publish messages to a topic.\n\n    Args:\n        *messages: Variable length argument list of SendableMessage objects.\n        message: A SendableMessage object. Default is an empty string.\n        key: Optional bytes object representing the message key.\n        partition: Optional integer representing the partition to publish the message to.\n        timestamp_ms: Optional integer representing the timestamp of the message in milliseconds.\n        headers: Optional dictionary of header key-value pairs.\n        correlation_id: Optional string representing the correlation ID of the message.\n\n    Returns:\n        None\n\n    Raises:\n        AssertionError: If `_producer` is not set up.\n        AssertionError: If `batch` flag is not set and there are multiple messages.\n        ValueError: If `message` is not a sequence when `messages` is empty.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    assert (  # nosec B101\n        self.batch or len(messages) < 2\n    ), \"You can't send multiple messages without `batch` flag\"\n    assert self.topic, \"You have to specify outgoing topic\"  # nosec B101\n\n    if not self.batch:\n        return await self._producer.publish(\n            message=next(iter(messages), message),\n            topic=self.topic,\n            key=key or self.key,\n            partition=partition or self.partition,\n            timestamp_ms=timestamp_ms or self.timestamp_ms,\n            correlation_id=correlation_id,\n            headers=headers or self.headers,\n            reply_to=self.reply_to or \"\",\n        )\n    else:\n        to_send: Sequence[SendableMessage]\n        if not messages:\n            if not isinstance(message, Sequence):\n                raise ValueError(\n                    f\"Message: {message} should be Sequence type to send in batch\"\n                )\n            else:\n                to_send = message\n        else:\n            to_send = messages\n\n        await self._producer.publish_batch(\n            *to_send,\n            topic=self.topic,\n            partition=partition or self.partition,\n            timestamp_ms=timestamp_ms or self.timestamp_ms,\n            headers=headers or self.headers,\n        )\n        return None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/kafka/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    return {\n        self.name: Channel(\n            description=self.description,\n            publish=Operation(\n                message=Message(\n                    title=f\"{self.name}:Message\",\n                    payload=resolve_payloads(payloads, \"Publisher\"),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(kafka=kafka.ChannelBinding(topic=self.topic)),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/","title":"KafkaBroker","text":"","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker","title":"faststream.kafka.broker.KafkaBroker","text":"
KafkaBroker(\n    bootstrap_servers: Union[\n        str, Iterable[str]\n    ] = \"localhost\",\n    *,\n    protocol: str = None,\n    protocol_version: str = \"auto\",\n    client_id: str = \"faststream-\" + __version__,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: KafkaLoggingMixin, BrokerAsyncUsecase[ConsumerRecord, ConsumerConnectionParams]

KafkaBroker is a class for managing Kafka message consumption and publishing. It extends BrokerAsyncUsecase to handle asynchronous operations.

PARAMETER DESCRIPTION bootstrap_servers

Kafka bootstrap server(s).

TYPE: Union[str, Iterable[str]] DEFAULT: 'localhost'

protocol

The protocol used (default is \"kafka\").

TYPE: str DEFAULT: None

protocol_version

The Kafka protocol version (default is \"auto\").

TYPE: str DEFAULT: 'auto'

client_id

The client ID for the Kafka client.

TYPE: str DEFAULT: 'faststream-' + __version__

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

METHOD DESCRIPTION connect

Establishes a connection to Kafka.

start

Starts the KafkaBroker and message handlers.

publish

Publishes a message to Kafka.

Initialize a KafkaBroker instance.

PARAMETER DESCRIPTION bootstrap_servers

Kafka bootstrap server(s).

TYPE: Union[str, Iterable[str]] DEFAULT: 'localhost'

protocol

The protocol used (default is \"kafka\").

TYPE: str DEFAULT: None

protocol_version

The Kafka protocol version (default is \"auto\").

TYPE: str DEFAULT: 'auto'

client_id

The client ID for the Kafka client.

TYPE: str DEFAULT: 'faststream-' + __version__

security

Security protocol to use in communication with the broker (default is None).

TYPE: Optional[BaseSecurity] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/kafka/broker.py
def __init__(\n    self,\n    bootstrap_servers: Union[str, Iterable[str]] = \"localhost\",\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: str = \"auto\",\n    client_id: str = \"faststream-\" + __version__,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Initialize a KafkaBroker instance.\n\n    Args:\n        bootstrap_servers (Union[str, Iterable[str]]): Kafka bootstrap server(s).\n        protocol (str): The protocol used (default is \"kafka\").\n        protocol_version (str): The Kafka protocol version (default is \"auto\").\n        client_id (str): The client ID for the Kafka client.\n        security (Optional[BaseSecurity]): Security protocol to use in communication with the broker (default is None).\n        **kwargs: Additional keyword arguments.\n    \"\"\"\n    if protocol is None:\n        if security is not None and security.use_ssl:\n            protocol = \"kafka-secure\"\n        else:\n            protocol = \"kafka\"\n\n    super().__init__(\n        url=[bootstrap_servers]\n        if isinstance(bootstrap_servers, str)\n        else list(bootstrap_servers),\n        protocol=protocol,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n        client_id=client_id,\n        bootstrap_servers=bootstrap_servers,\n    )\n    self.client_id = client_id\n    self._producer = None\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.client_id","title":"client_id instance-attribute","text":"
client_id = client_id\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[str, Handler]\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.url","title":"url instance-attribute","text":"
url: List[str]\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.connect","title":"connect async","text":"
connect(\n    *args: Any, **kwargs: Any\n) -> ConsumerConnectionParams\n

Establishes a connection to Kafka and returns connection parameters.

PARAMETER DESCRIPTION *args

Additional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION ConsumerConnectionParams

The connection parameters.

TYPE: ConsumerConnectionParams

Source code in faststream/kafka/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> ConsumerConnectionParams:\n    \"\"\"\n    Establishes a connection to Kafka and returns connection parameters.\n\n    Args:\n        *args: Additional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        ConsumerConnectionParams: The connection parameters.\n    \"\"\"\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.publish","title":"publish async","text":"
publish(*args: Any, **kwargs: Any) -> None\n

Publish a message to Kafka.

PARAMETER DESCRIPTION *args

Positional arguments for message publishing.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments for message publishing.

TYPE: Any DEFAULT: {}

RAISES DESCRIPTION RuntimeError

If KafkaBroker is not started yet.

Source code in faststream/kafka/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Publish a message to Kafka.\n\n    Args:\n        *args: Positional arguments for message publishing.\n        **kwargs: Keyword arguments for message publishing.\n\n    Raises:\n        RuntimeError: If KafkaBroker is not started yet.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.publish_batch","title":"publish_batch async","text":"
publish_batch(*args: Any, **kwargs: Any) -> None\n

Publish a batch of messages to Kafka.

PARAMETER DESCRIPTION *args

Positional arguments for message publishing.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments for message publishing.

TYPE: Any DEFAULT: {}

RAISES DESCRIPTION RuntimeError

If KafkaBroker is not started yet.

Source code in faststream/kafka/broker.py
async def publish_batch(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Publish a batch of messages to Kafka.\n\n    Args:\n        *args: Positional arguments for message publishing.\n        **kwargs: Keyword arguments for message publishing.\n\n    Raises:\n        RuntimeError: If KafkaBroker is not started yet.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    await self._producer.publish_batch(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.publisher","title":"publisher","text":"
publisher(\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n

Create a message publisher for the specified topic.

PARAMETER DESCRIPTION topic

The topic to publish messages to.

TYPE: str

key

Message key.

TYPE: Optional[bytes] DEFAULT: None

partition

Partition to send the message to.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

Message timestamp in milliseconds.

TYPE: Optional[int] DEFAULT: None

headers

Message headers.

TYPE: Optional[Dict[str, str]] DEFAULT: None

reply_to

The topic to which responses should be sent.

TYPE: str DEFAULT: ''

batch

Whether to publish messages in batches.

TYPE: bool DEFAULT: False

title

AsyncAPI title.

TYPE: Optional[str] DEFAULT: None

description

AsyncAPI description.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION Publisher

A message publisher.

TYPE: Publisher

Source code in faststream/kafka/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"\n    Create a message publisher for the specified topic.\n\n    Args:\n        topic (str): The topic to publish messages to.\n        key (Optional[bytes]): Message key.\n        partition (Optional[int]): Partition to send the message to.\n        timestamp_ms (Optional[int]): Message timestamp in milliseconds.\n        headers (Optional[Dict[str, str]]): Message headers.\n        reply_to (str): The topic to which responses should be sent.\n        batch (bool): Whether to publish messages in batches.\n        title (Optional[str]): AsyncAPI title.\n        description (Optional[str]): AsyncAPI description.\n\n    Returns:\n        Publisher: A message publisher.\n    \"\"\"\n    publisher = self._publishers.get(\n        topic,\n        Publisher(\n            topic=topic,\n            client_id=self.client_id,\n            key=key,\n            batch=batch,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(topic, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.start","title":"start async","text":"
start() -> None\n

Start the KafkaBroker and message handlers.

Source code in faststream/kafka/broker.py
async def start(self) -> None:\n    \"\"\"\n    Start the KafkaBroker and message handlers.\n    \"\"\"\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n\n    for handler in self.handlers.values():\n        c = self._get_log_context(None, handler.topics, handler.group_id)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(**(self._connection or {}))\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.subscriber","title":"subscriber","text":"
subscriber(\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    value_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\", \"earliest\", \"none\"\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[\n        AbstractPartitionAssignor\n    ] = (RoundRobinPartitionAssignor),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\", \"read_committed\"\n    ] = \"read_uncommitted\",\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        Union[\n            CustomParser[\n                aiokafka.ConsumerRecord, KafkaMessage\n            ],\n            CustomParser[\n                Tuple[aiokafka.ConsumerRecord, ...],\n                KafkaMessage,\n            ],\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[\n            StreamMessage[\n                Tuple[aiokafka.ConsumerRecord, ...]\n            ]\n        ],\n    ] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    Union[\n        HandlerCallWrapper[\n            aiokafka.ConsumerRecord,\n            P_HandlerParams,\n            T_HandlerReturn,\n        ],\n        HandlerCallWrapper[\n            Tuple[aiokafka.ConsumerRecord, ...],\n            P_HandlerParams,\n            T_HandlerReturn,\n        ],\n    ],\n]\n

Create a message subscriber for the specified topics.

PARAMETER DESCRIPTION *topics

The topics to subscribe to.

TYPE: str DEFAULT: ()

group_id

The Kafka consumer group ID.

TYPE: Optional[str] DEFAULT: None

key_deserializer

Key deserializer function.

TYPE: Optional[Callable[[bytes], Any]] DEFAULT: None

value_deserializer

Value deserializer function.

TYPE: Optional[Callable[[bytes], Any]] DEFAULT: None

fetch_max_wait_ms

The maximum time to wait for data.

TYPE: int DEFAULT: 500

fetch_max_bytes

The maximum number of bytes to fetch.

TYPE: int DEFAULT: 52428800

fetch_min_bytes

The minimum number of bytes to fetch.

TYPE: int DEFAULT: 1

max_partition_fetch_bytes

The maximum bytes to fetch for a partition.

TYPE: int DEFAULT: 1 * 1024 * 1024

auto_offset_reset

Auto offset reset policy.

TYPE: Literal['latest', 'earliest', 'none'] DEFAULT: 'latest'

auto_commit

Whether to enable auto-commit.

TYPE: bool DEFAULT: True

auto_commit_interval_ms

Auto-commit interval in milliseconds.

TYPE: int DEFAULT: 5000

check_crcs

Whether to check CRCs.

TYPE: bool DEFAULT: True

partition_assignment_strategy

Partition assignment strategy.

TYPE: Sequence[AbstractPartitionAssignor] DEFAULT: (RoundRobinPartitionAssignor)

max_poll_interval_ms

Maximum poll interval in milliseconds.

TYPE: int DEFAULT: 300000

rebalance_timeout_ms

Rebalance timeout in milliseconds.

TYPE: Optional[int] DEFAULT: None

session_timeout_ms

Session timeout in milliseconds.

TYPE: int DEFAULT: 10000

heartbeat_interval_ms

Heartbeat interval in milliseconds.

TYPE: int DEFAULT: 3000

consumer_timeout_ms

Consumer timeout in milliseconds.

TYPE: int DEFAULT: 200

max_poll_records

Maximum number of records to poll.

TYPE: Optional[int] DEFAULT: None

exclude_internal_topics

Whether to exclude internal topics.

TYPE: bool DEFAULT: True

isolation_level

Isolation level.

TYPE: Literal['read_uncommitted', 'read_committed'] DEFAULT: 'read_uncommitted'

dependencies

Additional dependencies for message handling.

TYPE: Sequence[Depends] DEFAULT: ()

parser

Message parser.

TYPE: Optional[Union[CustomParser[ConsumerRecord], CustomParser[Tuple[ConsumerRecord, ...]]]] DEFAULT: None

decoder

Message decoder.

TYPE: Optional[CustomDecoder] DEFAULT: None

middlewares

Message middlewares.

TYPE: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]] DEFAULT: None

filter

Message filter.

TYPE: Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[ConsumerRecord, ...]]]] DEFAULT: default_filter

batch

Whether to process messages in batches.

TYPE: bool DEFAULT: False

max_records

Maximum number of records to process in each batch.

TYPE: Optional[int] DEFAULT: None

batch_timeout_ms

Batch timeout in milliseconds.

TYPE: int DEFAULT: 200

no_ack

Whether not to ack/nack/reject messages.

TYPE: bool DEFAULT: False

title

AsyncAPI title.

TYPE: Optional[str] DEFAULT: None

description

AsyncAPI description.

TYPE: Optional[str] DEFAULT: None

**original_kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Callable

A decorator that wraps a message handler function.

TYPE: Callable[[Callable[P_HandlerParams, T_HandlerReturn]], Union[HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[Tuple[ConsumerRecord, ...], P_HandlerParams, T_HandlerReturn]]]

Source code in faststream/kafka/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[Callable[[bytes], Any]] = None,\n    value_deserializer: Optional[Callable[[bytes], Any]] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\",\n        \"earliest\",\n        \"none\",\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[AbstractPartitionAssignor] = (\n        RoundRobinPartitionAssignor,\n    ),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\",\n        \"read_committed\",\n    ] = \"read_uncommitted\",\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        Union[\n            CustomParser[aiokafka.ConsumerRecord, KafkaMessage],\n            CustomParser[Tuple[aiokafka.ConsumerRecord, ...], KafkaMessage],\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord],\n                BaseMiddleware,\n            ]\n        ]\n    ] = None,\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[aiokafka.ConsumerRecord, ...]]],\n    ] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    Union[\n        HandlerCallWrapper[\n            aiokafka.ConsumerRecord, P_HandlerParams, T_HandlerReturn\n        ],\n        HandlerCallWrapper[\n            Tuple[aiokafka.ConsumerRecord, ...], P_HandlerParams, T_HandlerReturn\n        ],\n    ],\n]:\n    \"\"\"\n    Create a message subscriber for the specified topics.\n\n    Args:\n        *topics (str): The topics to subscribe to.\n        group_id (Optional[str]): The Kafka consumer group ID.\n        key_deserializer (Optional[Callable[[bytes], Any]]): Key deserializer function.\n        value_deserializer (Optional[Callable[[bytes], Any]]): Value deserializer function.\n        fetch_max_wait_ms (int): The maximum time to wait for data.\n        fetch_max_bytes (int): The maximum number of bytes to fetch.\n        fetch_min_bytes (int): The minimum number of bytes to fetch.\n        max_partition_fetch_bytes (int): The maximum bytes to fetch for a partition.\n        auto_offset_reset (Literal[\"latest\", \"earliest\", \"none\"]): Auto offset reset policy.\n        auto_commit (bool): Whether to enable auto-commit.\n        auto_commit_interval_ms (int): Auto-commit interval in milliseconds.\n        check_crcs (bool): Whether to check CRCs.\n        partition_assignment_strategy (Sequence[AbstractPartitionAssignor]): Partition assignment strategy.\n        max_poll_interval_ms (int): Maximum poll interval in milliseconds.\n        rebalance_timeout_ms (Optional[int]): Rebalance timeout in milliseconds.\n        session_timeout_ms (int): Session timeout in milliseconds.\n        heartbeat_interval_ms (int): Heartbeat interval in milliseconds.\n        consumer_timeout_ms (int): Consumer timeout in milliseconds.\n        max_poll_records (Optional[int]): Maximum number of records to poll.\n        exclude_internal_topics (bool): Whether to exclude internal topics.\n        isolation_level (Literal[\"read_uncommitted\", \"read_committed\"]): Isolation level.\n        dependencies (Sequence[Depends]): Additional dependencies for message handling.\n        parser (Optional[Union[CustomParser[aiokafka.ConsumerRecord], CustomParser[Tuple[aiokafka.ConsumerRecord, ...]]]]): Message parser.\n        decoder (Optional[CustomDecoder]): Message decoder.\n        middlewares (Optional[Sequence[Callable[[aiokafka.ConsumerRecord], BaseMiddleware]]]): Message middlewares.\n        filter (Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[aiokafka.ConsumerRecord, ...]]]]): Message filter.\n        batch (bool): Whether to process messages in batches.\n        max_records (Optional[int]): Maximum number of records to process in each batch.\n        batch_timeout_ms (int): Batch timeout in milliseconds.\n        no_ack (bool): Whether not to ack/nack/reject messages.\n        title (Optional[str]): AsyncAPI title.\n        description (Optional[str]): AsyncAPI description.\n        **original_kwargs: Additional keyword arguments.\n\n    Returns:\n        Callable: A decorator that wraps a message handler function.\n    \"\"\"\n    super().subscriber()\n\n    self._setup_log_context(topics, group_id)\n\n    if not auto_commit and not group_id:\n        raise ValueError(\"You should install `group_id` with manual commit mode\")\n\n    key = Handler.get_routing_hash(topics, group_id)\n    builder = partial(\n        aiokafka.AIOKafkaConsumer,\n        key_deserializer=key_deserializer,\n        value_deserializer=value_deserializer,\n        fetch_max_wait_ms=fetch_max_wait_ms,\n        fetch_max_bytes=fetch_max_bytes,\n        fetch_min_bytes=fetch_min_bytes,\n        max_partition_fetch_bytes=max_partition_fetch_bytes,\n        auto_offset_reset=auto_offset_reset,\n        enable_auto_commit=auto_commit,\n        auto_commit_interval_ms=auto_commit_interval_ms,\n        check_crcs=check_crcs,\n        partition_assignment_strategy=partition_assignment_strategy,\n        max_poll_interval_ms=max_poll_interval_ms,\n        rebalance_timeout_ms=rebalance_timeout_ms,\n        session_timeout_ms=session_timeout_ms,\n        heartbeat_interval_ms=heartbeat_interval_ms,\n        consumer_timeout_ms=consumer_timeout_ms,\n        max_poll_records=max_poll_records,\n        exclude_internal_topics=exclude_internal_topics,\n        isolation_level=isolation_level,\n    )\n    handler = self.handlers.get(\n        key,\n        Handler(\n            *topics,\n            log_context_builder=partial(\n                self._get_log_context,\n                topics=topics,\n                group_id=group_id,\n            ),\n            is_manual=not auto_commit,\n            group_id=group_id,\n            client_id=self.client_id,\n            builder=builder,\n            description=description,\n            title=title,\n            batch=batch,\n            batch_timeout_ms=batch_timeout_ms,\n            max_records=max_records,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n        ),\n    )\n\n    self.handlers[key] = handler\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[\n        aiokafka.ConsumerRecord, P_HandlerParams, T_HandlerReturn\n    ]:\n        \"\"\"A wrapper function for a consumer handler.\n\n        Args:\n            func : The consumer handler function to be wrapped.\n\n        Returns:\n            The wrapped handler call.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        handler_call, dependant = self._wrap_handler(\n            func=func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/kafka/fastapi/Context/#faststream.broker.fastapi.context.Context","title":"faststream.broker.fastapi.context.Context","text":"
Context(name: str) -> Any\n
Source code in faststream/broker/fastapi/context.py
def Context(name: str) -> Any:\n    return params.Depends(\n        lambda: context.resolve(name),\n        use_cache=True,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/","title":"KafkaRouter","text":"","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter","title":"faststream.kafka.fastapi.KafkaRouter","text":"
KafkaRouter(\n    bootstrap_servers: Union[\n        str, Iterable[str]\n    ] = \"localhost\",\n    *,\n    client_id: str = \"faststream-\" + __version__,\n    request_timeout_ms: int = 40 * 1000,\n    retry_backoff_ms: int = 100,\n    metadata_max_age_ms: int = 5 * 60 * 1000,\n    api_version: str = \"auto\",\n    connections_max_idle_ms: int = 540000,\n    security: Optional[BaseSecurity] = None,\n    acks: Union[\n        Literal[0, 1, -1, \"all\"], object\n    ] = _missing,\n    key_serializer: Optional[Callable[[Any], bytes]] = None,\n    value_serializer: Optional[\n        Callable[[Any], bytes]\n    ] = None,\n    compression_type: Optional[\n        Literal[\"gzip\", \"snappy\", \"lz4\", \"zstd\"]\n    ] = None,\n    max_batch_size: int = 16384,\n    partitioner: Callable[\n        [bytes, List[Partition], List[Partition]], Partition\n    ] = DefaultPartitioner(),\n    max_request_size: int = 1048576,\n    linger_ms: int = 0,\n    send_backoff_ms: int = 100,\n    enable_idempotence: bool = False,\n    transactional_id: Optional[str] = None,\n    transaction_timeout_ms: int = 60000,\n    loop: Optional[AbstractEventLoop] = None,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id),\n    graceful_timeout: Optional[float] = None,\n    apply_types: bool = True,\n    validate: bool = True,\n    decoder: Optional[CustomDecoder[KafkaMessage]] = None,\n    parser: Optional[\n        CustomParser[aiokafka.ConsumerRecord, KafkaMessage]\n    ] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    asyncapi_url: Union[str, List[str], None] = None,\n    protocol: str = \"kafka\",\n    protocol_version: str = \"auto\",\n    description: Optional[str] = None,\n    asyncapi_tags: Optional[Sequence[asyncapi.Tag]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    setup_state: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any\n)\n

Bases: StreamRouter[ConsumerRecord]

A class to route Kafka streams.

METHOD DESCRIPTION _setup_log_context

sets up the log context for the main broker and including broker

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.broker","title":"broker instance-attribute","text":"
broker: KafkaBroker\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.broker_class","title":"broker_class class-attribute instance-attribute","text":"
broker_class: Type[KafkaBroker] = KB\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any\n) -> HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n]\n

Add an API message queue route.

PARAMETER DESCRIPTION path

The path of the route.

TYPE: Union[NameRequired, str]

*extra

Additional path segments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint function to be called for this route.

TYPE: Callable[P_HandlerParams, T_HandlerReturn]

dependencies

The dependencies required by the endpoint function.

TYPE: Sequence[Depends]

**broker_kwargs

Additional keyword arguments to be passed to the broker.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]

The handler call wrapper for the route.

Source code in faststream/broker/fastapi/router.py
def add_api_mq_route(\n    self,\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any,\n) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n    \"\"\"Add an API message queue route.\n\n    Args:\n        path: The path of the route.\n        *extra: Additional path segments.\n        endpoint: The endpoint function to be called for this route.\n        dependencies: The dependencies required by the endpoint function.\n        **broker_kwargs: Additional keyword arguments to be passed to the broker.\n\n    Returns:\n        The handler call wrapper for the route.\n\n    \"\"\"\n    route: StreamRoute[MsgType, P_HandlerParams, T_HandlerReturn] = StreamRoute(\n        path,\n        *extra,\n        endpoint=endpoint,\n        dependencies=dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        broker=self.broker,\n        **broker_kwargs,\n    )\n    self.routes.append(route)\n    return route.handler\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.publisher","title":"publisher","text":"
publisher(\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.subscriber","title":"subscriber","text":"
subscriber(\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function decorator for subscribing to a message queue.

PARAMETER DESCRIPTION path

The path to subscribe to. Can be a string or a NameRequired object.

*extra

Additional path segments. Can be a NameRequired object or a string.

DEFAULT: ()

dependencies

Optional sequence of dependencies.

DEFAULT: None

**broker_kwargs

Additional keyword arguments for the broker.

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable decorator that adds the decorated function as an endpoint for the specified path.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def subscriber(\n    self,\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function decorator for subscribing to a message queue.\n\n    Args:\n        path : The path to subscribe to. Can be a string or a `NameRequired` object.\n        *extra : Additional path segments. Can be a `NameRequired` object or a string.\n        dependencies : Optional sequence of dependencies.\n        **broker_kwargs : Additional keyword arguments for the broker.\n\n    Returns:\n        A callable decorator that adds the decorated function as an endpoint for the specified path.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    def decorator(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n        \"\"\"A decorator function.\n\n        Args:\n            func: The function to be decorated.\n\n        Returns:\n            The decorated function.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        return self.add_api_mq_route(\n            path,\n            *extra,\n            endpoint=func,\n            dependencies=current_dependencies,\n            **broker_kwargs,\n        )\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/","title":"LogicHandler","text":"","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler","title":"faststream.kafka.handler.LogicHandler","text":"
LogicHandler(\n    *topics: str,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    group_id: Optional[str] = None,\n    client_id: str = \"faststream-\" + __version__,\n    builder: Callable[..., AIOKafkaConsumer],\n    is_manual: bool = False,\n    batch: bool = False,\n    batch_timeout_ms: int = 200,\n    max_records: Optional[int] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True\n)\n

Bases: AsyncHandler[ConsumerRecord]

A class to handle logic for consuming messages from Kafka.

METHOD DESCRIPTION __init__

constructor method for the LogicHandler class

start

method to start consuming messages from Kafka

close

method to close the Kafka consumer and cancel the consuming task

add_call

method to add a handler call for processing consumed messages

_consume

method to consume messages from Kafka and call the appropriate handler

Initialize a Kafka consumer for the specified topics.

PARAMETER DESCRIPTION *topics

Variable length argument list of topics to consume from.

TYPE: str DEFAULT: ()

group_id

Optional group ID for the consumer.

TYPE: Optional[str] DEFAULT: None

client_id

Client ID for the consumer.

TYPE: str DEFAULT: 'faststream-' + __version__

builder

Callable that constructs an AIOKafkaConsumer instance.

TYPE: Callable[..., AIOKafkaConsumer]

batch

Flag indicating whether to consume messages in batches.

TYPE: bool DEFAULT: False

batch_timeout_ms

Timeout in milliseconds for batch consumption.

TYPE: int DEFAULT: 200

max_records

Maximum number of records to consume in a batch.

TYPE: Optional[int] DEFAULT: None

title

Optional title for the consumer.

TYPE: Optional[str] DEFAULT: None

description

Optional description for the consumer.

TYPE: Optional[str] DEFAULT: None

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/kafka/handler.py
@override\ndef __init__(\n    self,\n    *topics: str,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # Kafka information\n    group_id: Optional[str] = None,\n    client_id: str = \"faststream-\" + __version__,\n    builder: Callable[..., AIOKafkaConsumer],\n    is_manual: bool = False,\n    batch: bool = False,\n    batch_timeout_ms: int = 200,\n    max_records: Optional[int] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    \"\"\"Initialize a Kafka consumer for the specified topics.\n\n    Args:\n        *topics: Variable length argument list of topics to consume from.\n        group_id: Optional group ID for the consumer.\n        client_id: Client ID for the consumer.\n        builder: Callable that constructs an AIOKafkaConsumer instance.\n        batch: Flag indicating whether to consume messages in batches.\n        batch_timeout_ms: Timeout in milliseconds for batch consumption.\n        max_records: Maximum number of records to consume in a batch.\n        title: Optional title for the consumer.\n        description: Optional description for the consumer.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.group_id = group_id\n    self.client_id = client_id\n    self.topics = topics\n\n    self.batch = batch\n    self.batch_timeout_ms = batch_timeout_ms\n    self.max_records = max_records\n    self.is_manual = is_manual\n\n    self.builder = builder\n    self.task = None\n    self.consumer = None\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = batch\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.batch_timeout_ms","title":"batch_timeout_ms instance-attribute","text":"
batch_timeout_ms = batch_timeout_ms\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.builder","title":"builder instance-attribute","text":"
builder = builder\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.client_id","title":"client_id instance-attribute","text":"
client_id = client_id\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.consumer","title":"consumer class-attribute instance-attribute","text":"
consumer: Optional[AIOKafkaConsumer] = None\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.group_id","title":"group_id class-attribute instance-attribute","text":"
group_id: Optional[str] = group_id\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.is_manual","title":"is_manual instance-attribute","text":"
is_manual = is_manual\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.max_records","title":"max_records instance-attribute","text":"
max_records = max_records\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.task","title":"task class-attribute instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.topics","title":"topics instance-attribute","text":"
topics: Sequence[str] = topics\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        ConsumerRecord, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: CustomParser[\n        Union[ConsumerRecord, Tuple[ConsumerRecord, ...]],\n        KafkaMessage,\n    ],\n    decoder: Optional[CustomDecoder[KafkaMessage]],\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[ConsumerRecord, ...]]],\n    ],\n    middlewares: Optional[\n        Sequence[Callable[[ConsumerRecord], BaseMiddleware]]\n    ]\n) -> None\n

Adds a call to the handler.

PARAMETER DESCRIPTION handler

The handler function to be called.

TYPE: HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn]

dependant

The dependant model.

TYPE: CallModel[P_HandlerParams, T_HandlerReturn]

parser

Optional custom parser for parsing the input.

TYPE: CustomParser[Union[ConsumerRecord, Tuple[ConsumerRecord, ...]], KafkaMessage]

decoder

Optional custom decoder for decoding the input.

TYPE: Optional[CustomDecoder[KafkaMessage]]

filter

The filter for filtering the input.

TYPE: Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[ConsumerRecord, ...]]]]

middlewares

Optional sequence of middlewares to be applied.

TYPE: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]]

RETURNS DESCRIPTION None

None

Source code in faststream/kafka/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: CustomParser[\n        Union[ConsumerRecord, Tuple[ConsumerRecord, ...]], KafkaMessage\n    ],\n    decoder: Optional[CustomDecoder[KafkaMessage]],\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[ConsumerRecord, ...]]],\n    ],\n    middlewares: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]],\n) -> None:\n    \"\"\"Adds a call to the handler.\n\n    Args:\n        handler: The handler function to be called.\n        dependant: The dependant model.\n        parser: Optional custom parser for parsing the input.\n        decoder: Optional custom decoder for decoding the input.\n        filter: The filter for filtering the input.\n        middlewares: Optional sequence of middlewares to be applied.\n\n    Returns:\n        None\n\n    \"\"\"\n    parser_ = resolve_custom_func(  # type: ignore[type-var]\n        parser,  # type: ignore[arg-type]\n        (\n            AioKafkaParser.parse_message_batch  # type: ignore[arg-type]\n            if self.batch\n            else AioKafkaParser.parse_message\n        ),\n    )\n    decoder_ = resolve_custom_func(\n        decoder,  # type: ignore[arg-type]\n        (\n            AioKafkaParser.decode_message_batch  # type: ignore[arg-type]\n            if self.batch\n            else AioKafkaParser.decode_message\n        ),\n    )\n    super().add_call(\n        handler=handler,\n        parser=parser_,\n        decoder=decoder_,\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/kafka/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.consumer is not None:\n        await self.consumer.stop()\n        self.consumer = None\n\n    if self.task is not None:\n        self.task.cancel()\n        self.task = None\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(\n    topics: Sequence[str], group_id: Optional[str] = None\n) -> str\n
Source code in faststream/kafka/handler.py
@staticmethod\ndef get_routing_hash(topics: Sequence[str], group_id: Optional[str] = None) -> str:\n    return \"\".join((*topics, group_id or \"\"))\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.start","title":"start async","text":"
start(\n    **consumer_kwargs: Unpack[ConsumerConnectionParams],\n) -> None\n

Start the consumer.

PARAMETER DESCRIPTION **consumer_kwargs

Additional keyword arguments to pass to the consumer.

TYPE: Unpack[ConsumerConnectionParams] DEFAULT: {}

RETURNS DESCRIPTION None

None

Source code in faststream/kafka/handler.py
@override\nasync def start(  # type: ignore[override]\n    self,\n    **consumer_kwargs: Unpack[ConsumerConnectionParams],\n) -> None:\n    \"\"\"Start the consumer.\n\n    Args:\n        **consumer_kwargs: Additional keyword arguments to pass to the consumer.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.consumer = consumer = self.builder(\n        *self.topics,\n        group_id=self.group_id,\n        client_id=self.client_id,\n        **consumer_kwargs,\n    )\n    await consumer.start()\n    self.task = asyncio.create_task(self._consume())\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/","title":"KafkaMessage","text":"","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage","title":"faststream.kafka.message.KafkaMessage","text":"
KafkaMessage(\n    *args: Any,\n    consumer: aiokafka.AIOKafkaConsumer,\n    is_manual: bool = False,\n    **kwargs: Any\n)\n

Bases: StreamMessage[ConsumerRecord]

Represents a Kafka message in the FastStream framework.

This class extends StreamMessage and is specialized for handling Kafka ConsumerRecord objects.

METHOD DESCRIPTION ack

Acknowledge the Kafka message.

nack

Negative acknowledgment of the Kafka message.

reject

Reject the Kafka message.

Source code in faststream/kafka/message.py
def __init__(\n    self,\n    *args: Any,\n    consumer: aiokafka.AIOKafkaConsumer,\n    is_manual: bool = False,\n    **kwargs: Any,\n) -> None:\n    super().__init__(*args, **kwargs)\n\n    self.is_manual = is_manual\n    self.consumer = consumer\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.consumer","title":"consumer instance-attribute","text":"
consumer = consumer\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.is_manual","title":"is_manual instance-attribute","text":"
is_manual = is_manual\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.ack","title":"ack async","text":"
ack(**kwargs: Any) -> None\n

Acknowledge the Kafka message.

PARAMETER DESCRIPTION **kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

This method does not return a value.

TYPE: None

Source code in faststream/kafka/message.py
async def ack(self, **kwargs: Any) -> None:\n    \"\"\"\n    Acknowledge the Kafka message.\n\n    Args:\n        **kwargs (Any): Additional keyword arguments.\n\n    Returns:\n        None: This method does not return a value.\n    \"\"\"\n    if self.is_manual and not self.commited:\n        await self.consumer.commit()\n        await super().ack()\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.nack","title":"nack async","text":"
nack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def nack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.reject","title":"reject async","text":"
reject(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def reject(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/","title":"AioKafkaParser","text":"","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/#faststream.kafka.parser.AioKafkaParser","title":"faststream.kafka.parser.AioKafkaParser","text":"","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/#faststream.kafka.parser.AioKafkaParser.decode_message","title":"decode_message async staticmethod","text":"
decode_message(\n    msg: StreamMessage[ConsumerRecord],\n) -> DecodedMessage\n

Decodes a message.

PARAMETER DESCRIPTION msg

The message to be decoded.

TYPE: StreamMessage[ConsumerRecord]

RETURNS DESCRIPTION DecodedMessage

The decoded message.

Source code in faststream/kafka/parser.py
@staticmethod\nasync def decode_message(msg: StreamMessage[ConsumerRecord]) -> DecodedMessage:\n    \"\"\"Decodes a message.\n\n    Args:\n        msg: The message to be decoded.\n\n    Returns:\n        The decoded message.\n\n    \"\"\"\n    return decode_message(msg)\n
","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/#faststream.kafka.parser.AioKafkaParser.decode_message_batch","title":"decode_message_batch async classmethod","text":"
decode_message_batch(\n    msg: StreamMessage[Tuple[ConsumerRecord, ...]]\n) -> List[DecodedMessage]\n

Decode a batch of messages.

PARAMETER DESCRIPTION msg

A stream message containing a tuple of consumer records.

TYPE: StreamMessage[Tuple[ConsumerRecord, ...]]

RETURNS DESCRIPTION List[DecodedMessage]

A list of decoded messages.

Source code in faststream/kafka/parser.py
@classmethod\nasync def decode_message_batch(\n    cls, msg: StreamMessage[Tuple[ConsumerRecord, ...]]\n) -> List[DecodedMessage]:\n    \"\"\"Decode a batch of messages.\n\n    Args:\n        msg: A stream message containing a tuple of consumer records.\n\n    Returns:\n        A list of decoded messages.\n\n    \"\"\"\n    return [decode_message(await cls.parse_message(m)) for m in msg.raw_message]\n
","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/#faststream.kafka.parser.AioKafkaParser.parse_message","title":"parse_message async staticmethod","text":"
parse_message(\n    message: ConsumerRecord,\n) -> StreamMessage[ConsumerRecord]\n

Parses a Kafka message.

PARAMETER DESCRIPTION message

The Kafka message to parse.

TYPE: ConsumerRecord

RETURNS DESCRIPTION StreamMessage[ConsumerRecord]

A StreamMessage object representing the parsed message.

Source code in faststream/kafka/parser.py
@staticmethod\nasync def parse_message(\n    message: ConsumerRecord,\n) -> StreamMessage[ConsumerRecord]:\n    \"\"\"Parses a Kafka message.\n\n    Args:\n        message: The Kafka message to parse.\n\n    Returns:\n        A StreamMessage object representing the parsed message.\n\n    \"\"\"\n    headers = {i: j.decode() for i, j in message.headers}\n    handler = context.get_local(\"handler_\")\n    return KafkaMessage(\n        body=message.value,\n        headers=headers,\n        reply_to=headers.get(\"reply_to\", \"\"),\n        content_type=headers.get(\"content-type\"),\n        message_id=f\"{message.offset}-{message.timestamp}\",\n        correlation_id=headers.get(\"correlation_id\", str(uuid4())),\n        raw_message=message,\n        consumer=handler.consumer,\n        is_manual=handler.is_manual,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/#faststream.kafka.parser.AioKafkaParser.parse_message_batch","title":"parse_message_batch async staticmethod","text":"
parse_message_batch(\n    message: Tuple[ConsumerRecord, ...]\n) -> KafkaMessage\n

Parses a batch of messages from a Kafka consumer.

PARAMETER DESCRIPTION message

A tuple of ConsumerRecord objects representing the messages to parse.

RETURNS DESCRIPTION KafkaMessage

A StreamMessage object containing the parsed messages.

RAISES DESCRIPTION NotImplementedError

If any of the messages are silent (i.e., have no sound).

Static Method

This method is a static method. It does not require an instance of the class to be called.

Source code in faststream/kafka/parser.py
@staticmethod\nasync def parse_message_batch(\n    message: Tuple[ConsumerRecord, ...],\n) -> KafkaMessage:\n    \"\"\"Parses a batch of messages from a Kafka consumer.\n\n    Args:\n        message : A tuple of ConsumerRecord objects representing the messages to parse.\n\n    Returns:\n        A StreamMessage object containing the parsed messages.\n\n    Raises:\n        NotImplementedError: If any of the messages are silent (i.e., have no sound).\n\n    Static Method:\n        This method is a static method. It does not require an instance of the class to be called.\n\n    \"\"\"\n    first = message[0]\n    last = message[-1]\n    headers = {i: j.decode() for i, j in first.headers}\n    handler = context.get_local(\"handler_\")\n    return KafkaMessage(\n        body=[m.value for m in message],\n        headers=headers,\n        reply_to=headers.get(\"reply_to\", \"\"),\n        content_type=headers.get(\"content-type\"),\n        message_id=f\"{first.offset}-{last.offset}-{first.timestamp}\",\n        correlation_id=headers.get(\"correlation_id\", str(uuid4())),\n        raw_message=message,\n        consumer=handler.consumer,\n        is_manual=handler.is_manual,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/producer/AioKafkaFastProducer/","title":"AioKafkaFastProducer","text":"","boost":0.5},{"location":"api/faststream/kafka/producer/AioKafkaFastProducer/#faststream.kafka.producer.AioKafkaFastProducer","title":"faststream.kafka.producer.AioKafkaFastProducer","text":"
AioKafkaFastProducer(producer: AIOKafkaProducer)\n

A class to represent a fast Kafka producer.

METHOD DESCRIPTION publish

Publishes a message to a Kafka topic.

stop

Stops the Kafka producer.

publish_batch

Publishes a batch of messages to a Kafka topic.

Initialize the class.

PARAMETER DESCRIPTION producer

An instance of AIOKafkaProducer.

TYPE: AIOKafkaProducer

Source code in faststream/kafka/producer.py
def __init__(\n    self,\n    producer: AIOKafkaProducer,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        producer: An instance of AIOKafkaProducer.\n\n    \"\"\"\n    self._producer = producer\n
","boost":0.5},{"location":"api/faststream/kafka/producer/AioKafkaFastProducer/#faststream.kafka.producer.AioKafkaFastProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\"\n) -> None\n

Publish a message to a topic.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

topic

The topic to publish the message to.

TYPE: str

key

The key associated with the message.

TYPE: Optional[bytes] DEFAULT: None

partition

The partition to which the message should be sent.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

The timestamp of the message in milliseconds.

TYPE: Optional[int] DEFAULT: None

headers

Additional headers to be included with the message.

TYPE: Optional[Dict[str, str]] DEFAULT: None

correlation_id

The correlation ID of the message.

TYPE: Optional[str] DEFAULT: None

reply_to

The topic to which the reply should be sent.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION AssertionError

If the broker is not connected.

Source code in faststream/kafka/producer.py
async def publish(\n    self,\n    message: SendableMessage,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\",\n) -> None:\n    \"\"\"Publish a message to a topic.\n\n    Args:\n        message: The message to be published.\n        topic: The topic to publish the message to.\n        key: The key associated with the message.\n        partition: The partition to which the message should be sent.\n        timestamp_ms: The timestamp of the message in milliseconds.\n        headers: Additional headers to be included with the message.\n        correlation_id: The correlation ID of the message.\n        reply_to: The topic to which the reply should be sent.\n\n    Returns:\n        None\n\n    Raises:\n        AssertionError: If the broker is not connected.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n\n    message, content_type = encode_message(message)\n\n    headers_to_send = {\n        \"content-type\": content_type or \"\",\n        \"correlation_id\": correlation_id or str(uuid4()),\n        **(headers or {}),\n    }\n\n    if reply_to:\n        headers_to_send.update({\"reply_to\": reply_to})\n\n    await self._producer.send(\n        topic=topic,\n        value=message,\n        key=key,\n        partition=partition,\n        timestamp_ms=timestamp_ms,\n        headers=[(i, (j or \"\").encode()) for i, j in headers_to_send.items()],\n    )\n\n    return None\n
","boost":0.5},{"location":"api/faststream/kafka/producer/AioKafkaFastProducer/#faststream.kafka.producer.AioKafkaFastProducer.publish_batch","title":"publish_batch async","text":"
publish_batch(\n    *msgs: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None\n) -> None\n

Publish a batch of messages to a topic.

PARAMETER DESCRIPTION *msgs

Variable length argument list of messages to be sent.

TYPE: SendableMessage DEFAULT: ()

topic

The topic to which the messages should be published.

TYPE: str

partition

The partition to which the messages should be sent. Defaults to None.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

The timestamp to be associated with the messages. Defaults to None.

TYPE: Optional[int] DEFAULT: None

headers

Additional headers to be included with the messages. Defaults to None.

TYPE: Optional[Dict[str, str]] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION AssertionError

If the broker is not connected.

Source code in faststream/kafka/producer.py
async def publish_batch(\n    self,\n    *msgs: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n) -> None:\n    \"\"\"Publish a batch of messages to a topic.\n\n    Args:\n        *msgs: Variable length argument list of messages to be sent.\n        topic: The topic to which the messages should be published.\n        partition: The partition to which the messages should be sent. Defaults to None.\n        timestamp_ms: The timestamp to be associated with the messages. Defaults to None.\n        headers: Additional headers to be included with the messages. Defaults to None.\n\n    Returns:\n        None\n\n    Raises:\n        AssertionError: If the broker is not connected.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n\n    batch = self._producer.create_batch()\n\n    for msg in msgs:\n        message, content_type = encode_message(msg)\n\n        headers_to_send = {\n            \"content-type\": content_type or \"\",\n            **(headers or {}),\n        }\n\n        batch.append(\n            key=None,\n            value=message,\n            timestamp=timestamp_ms,\n            headers=[(i, j.encode()) for i, j in headers_to_send.items()],\n        )\n\n    await self._producer.send_batch(batch, topic, partition=partition)\n
","boost":0.5},{"location":"api/faststream/kafka/producer/AioKafkaFastProducer/#faststream.kafka.producer.AioKafkaFastProducer.stop","title":"stop async","text":"
stop() -> None\n
Source code in faststream/kafka/producer.py
async def stop(self) -> None:\n    if self._producer is not None:  # pragma: no branch\n        await self._producer.stop()\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/","title":"LogicPublisher","text":"","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher","title":"faststream.kafka.publisher.LogicPublisher dataclass","text":"

Bases: ABCPublisher[ConsumerRecord]

A class to publish messages to a Kafka topic.

METHOD DESCRIPTION publish

Publishes messages to the Kafka topic

RAISES DESCRIPTION AssertionError

If _producer is not set up or if multiple messages are sent without the batch flag

","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = field(default=False)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.client_id","title":"client_id class-attribute instance-attribute","text":"
client_id: str = field(default='faststream-' + __version__)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.key","title":"key class-attribute instance-attribute","text":"
key: Optional[bytes] = None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.partition","title":"partition class-attribute instance-attribute","text":"
partition: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = ''\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.timestamp_ms","title":"timestamp_ms class-attribute instance-attribute","text":"
timestamp_ms: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.topic","title":"topic class-attribute instance-attribute","text":"
topic: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.publish","title":"publish async","text":"
publish(\n    *messages: SendableMessage,\n    message: SendableMessage = \"\",\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None\n) -> None\n

Publish messages to a topic.

PARAMETER DESCRIPTION *messages

Variable length argument list of SendableMessage objects.

TYPE: SendableMessage DEFAULT: ()

message

A SendableMessage object. Default is an empty string.

TYPE: SendableMessage DEFAULT: ''

key

Optional bytes object representing the message key.

TYPE: Optional[bytes] DEFAULT: None

partition

Optional integer representing the partition to publish the message to.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

Optional integer representing the timestamp of the message in milliseconds.

TYPE: Optional[int] DEFAULT: None

headers

Optional dictionary of header key-value pairs.

TYPE: Optional[Dict[str, str]] DEFAULT: None

correlation_id

Optional string representing the correlation ID of the message.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION AssertionError

If _producer is not set up.

AssertionError

If batch flag is not set and there are multiple messages.

ValueError

If message is not a sequence when messages is empty.

Source code in faststream/kafka/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *messages: SendableMessage,\n    message: SendableMessage = \"\",\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n) -> None:\n    \"\"\"Publish messages to a topic.\n\n    Args:\n        *messages: Variable length argument list of SendableMessage objects.\n        message: A SendableMessage object. Default is an empty string.\n        key: Optional bytes object representing the message key.\n        partition: Optional integer representing the partition to publish the message to.\n        timestamp_ms: Optional integer representing the timestamp of the message in milliseconds.\n        headers: Optional dictionary of header key-value pairs.\n        correlation_id: Optional string representing the correlation ID of the message.\n\n    Returns:\n        None\n\n    Raises:\n        AssertionError: If `_producer` is not set up.\n        AssertionError: If `batch` flag is not set and there are multiple messages.\n        ValueError: If `message` is not a sequence when `messages` is empty.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    assert (  # nosec B101\n        self.batch or len(messages) < 2\n    ), \"You can't send multiple messages without `batch` flag\"\n    assert self.topic, \"You have to specify outgoing topic\"  # nosec B101\n\n    if not self.batch:\n        return await self._producer.publish(\n            message=next(iter(messages), message),\n            topic=self.topic,\n            key=key or self.key,\n            partition=partition or self.partition,\n            timestamp_ms=timestamp_ms or self.timestamp_ms,\n            correlation_id=correlation_id,\n            headers=headers or self.headers,\n            reply_to=self.reply_to or \"\",\n        )\n    else:\n        to_send: Sequence[SendableMessage]\n        if not messages:\n            if not isinstance(message, Sequence):\n                raise ValueError(\n                    f\"Message: {message} should be Sequence type to send in batch\"\n                )\n            else:\n                to_send = message\n        else:\n            to_send = messages\n\n        await self._producer.publish_batch(\n            *to_send,\n            topic=self.topic,\n            partition=partition or self.partition,\n            timestamp_ms=timestamp_ms or self.timestamp_ms,\n            headers=headers or self.headers,\n        )\n        return None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/","title":"KafkaRouter","text":"","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter","title":"faststream.kafka.router.KafkaRouter","text":"
KafkaRouter(\n    prefix: str = \"\",\n    handlers: Sequence[KafkaRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[aiokafka.ConsumerRecord, KafkaMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[KafkaMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: KafkaRouter

A class to represent a Kafka router.

METHOD DESCRIPTION _get_publisher_key

Get the key for a publisher

_update_publisher_prefix

Update the prefix of a publisher

publisher

Create a new publisher

Source code in faststream/kafka/router.py
        publisher: The publisher object.\n\n    Returns:\n        The publisher key.\n\n    \"\"\"\n    return publisher.topic\n\n@override\n@staticmethod\ndef _update_publisher_prefix(  # type: ignore[override]\n    prefix: str,\n    publisher: Publisher,\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.publisher","title":"publisher","text":"
publisher(\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n

Publishes a message to a topic.

PARAMETER DESCRIPTION topic

The topic to publish the message to.

TYPE: str

key

The key associated with the message.

TYPE: bytes DEFAULT: None

partition

The partition to publish the message to.

TYPE: int DEFAULT: None

timestamp_ms

The timestamp of the message in milliseconds.

TYPE: int DEFAULT: None

headers

Additional headers for the message.

TYPE: Dict[str, str] DEFAULT: None

reply_to

The topic to reply to.

TYPE: str DEFAULT: ''

batch

Whether to publish the message as part of a batch.

TYPE: bool DEFAULT: False

title

The title of the message.

TYPE: str DEFAULT: None

description

The description of the message.

TYPE: str DEFAULT: None

RETURNS DESCRIPTION Publisher

The publisher object used to publish the message.

TYPE: Publisher

Source code in faststream/kafka/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"Publishes a message to a topic.\n\n    Args:\n        topic (str): The topic to publish the message to.\n        key (bytes, optional): The key associated with the message.\n        partition (int, optional): The partition to publish the message to.\n        timestamp_ms (int, optional): The timestamp of the message in milliseconds.\n        headers (Dict[str, str], optional): Additional headers for the message.\n        reply_to (str, optional): The topic to reply to.\n        batch (bool, optional): Whether to publish the message as part of a batch.\n        title (str, optional): The title of the message.\n        description (str, optional): The description of the message.\n\n    Returns:\n        Publisher: The publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            topic=topic,\n            key=key,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            batch=batch,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.subscriber","title":"subscriber","text":"
subscriber(\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    value_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\", \"earliest\", \"none\"\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[\n        AbstractPartitionAssignor\n    ] = (RoundRobinPartitionAssignor),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\", \"read_committed\"\n    ] = \"read_uncommitted\",\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[aiokafka.ConsumerRecord, KafkaMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[KafkaMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Filter[KafkaMessage] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    retry: Union[bool, int] = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aiokafka.ConsumerRecord,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n
Source code in faststream/kafka/router.py
    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"Publishes a message to a topic.\n\n    Args:\n        topic (str): The topic to publish the message to.\n        key (bytes, optional): The key associated with the message.\n        partition (int, optional): The partition to publish the message to.\n        timestamp_ms (int, optional): The timestamp of the message in milliseconds.\n        headers (Dict[str, str], optional): Additional headers for the message.\n        reply_to (str, optional): The topic to reply to.\n        batch (bool, optional): Whether to publish the message as part of a batch.\n        title (str, optional): The title of the message.\n        description (str, optional): The description of the message.\n\n    Returns:\n        Publisher: The publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            topic=topic,\n            key=key,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            batch=batch,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/security/parse_security/","title":"parse_security","text":"","boost":0.5},{"location":"api/faststream/kafka/security/parse_security/#faststream.kafka.security.parse_security","title":"faststream.kafka.security.parse_security","text":"
parse_security(security: Optional[BaseSecurity]) -> AnyDict\n
Source code in faststream/kafka/security.py
def parse_security(security: Optional[BaseSecurity]) -> AnyDict:\n    if security is None:\n        return {}\n    elif type(security) == BaseSecurity:\n        return _parse_base_security(security)\n    elif type(security) == SASLPlaintext:\n        return _parse_sasl_plaintext(security)\n    elif type(security) == SASLScram256:\n        return _parse_sasl_scram256(security)\n    elif type(security) == SASLScram512:\n        return _parse_sasl_scram512(security)\n    else:\n        raise NotImplementedError(f\"KafkaBroker does not support {type(security)}\")\n
","boost":0.5},{"location":"api/faststream/kafka/shared/logging/KafkaLoggingMixin/","title":"KafkaLoggingMixin","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/logging/KafkaLoggingMixin/#faststream.kafka.shared.logging.KafkaLoggingMixin","title":"faststream.kafka.shared.logging.KafkaLoggingMixin","text":"
KafkaLoggingMixin(\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any\n)\n

Bases: LoggingMixin

A class that provides logging functionality for Kafka.

METHOD DESCRIPTION __init__

initializes the KafkaLoggingMixin object

_get_log_context

returns the log context for a given message and topics

fmt

returns the log format string

_setup_log_context

sets up the log context for a given list of topics

Initialize the class.

PARAMETER DESCRIPTION *args

Variable length argument list

TYPE: Any DEFAULT: ()

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: access_logger

log_level

Log level (default: logging.INFO)

TYPE: int DEFAULT: INFO

log_fmt

Optional log format string

TYPE: Optional[str] DEFAULT: None

**kwargs

Arbitrary keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None

Source code in faststream/kafka/shared/logging.py
def __init__(\n    self,\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        *args: Variable length argument list\n        logger: Optional logger object\n        log_level: Log level (default: logging.INFO)\n        log_fmt: Optional log format string\n        **kwargs: Arbitrary keyword arguments\n\n    Returns:\n        None\n\n    \"\"\"\n    super().__init__(\n        *args,\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n        **kwargs,\n    )\n    self._max_topic_len = 4\n    self._max_group_len = 0\n
","boost":0.5},{"location":"api/faststream/kafka/shared/logging/KafkaLoggingMixin/#faststream.kafka.shared.logging.KafkaLoggingMixin.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/logging/KafkaLoggingMixin/#faststream.kafka.shared.logging.KafkaLoggingMixin.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/kafka/shared/logging/KafkaLoggingMixin/#faststream.kafka.shared.logging.KafkaLoggingMixin.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/","title":"ABCPublisher","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher","title":"faststream.kafka.shared.publisher.ABCPublisher dataclass","text":"

Bases: ABC, BasePublisher[MsgType]

A class representing an ABCPublisher.

","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = None\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.key","title":"key class-attribute instance-attribute","text":"
key: Optional[bytes] = None\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.partition","title":"partition class-attribute instance-attribute","text":"
partition: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = ''\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.timestamp_ms","title":"timestamp_ms class-attribute instance-attribute","text":"
timestamp_ms: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.topic","title":"topic class-attribute instance-attribute","text":"
topic: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.publish","title":"publish abstractmethod async","text":"
publish(\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

correlation_id

Optional correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/publisher.py
@abstractmethod\nasync def publish(\n    self,\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        correlation_id: Optional correlation ID for the message.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/","title":"BrokerRouter","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter","title":"faststream.broker.router.BrokerRouter","text":"
BrokerRouter(\n    prefix: str = \"\",\n    handlers: Sequence[\n        BrokerRoute[MsgType, SendableMessage]\n    ] = (),\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    include_in_schema: Optional[bool] = None,\n)\n

Bases: Generic[PublisherKeyType, MsgType]

A generic class representing a broker router.

METHOD DESCRIPTION _get_publisher_key

abstract method to get the publisher key

_update_publisher_prefix

abstract method to update the publisher prefix

__init__

constructor method

subscriber

abstract method to define a subscriber

_wrap_subscriber

method to wrap a subscriber function

publisher

abstract method to define a publisher

include_router

method to include a router

include_routers

method to include multiple routers

Initialize a class object.

PARAMETER DESCRIPTION prefix

Prefix for the object.

TYPE: str DEFAULT: ''

handlers

Handlers for the object.

TYPE: Sequence[BrokerRoute[MsgType, SendableMessage]] DEFAULT: ()

dependencies

Dependencies for the object.

TYPE: Sequence[Depends] DEFAULT: ()

middlewares

Middlewares for the object.

TYPE: Optional[Sequence[Callable[[StreamMessage[MsgType]], AsyncContextManager[None]]]] DEFAULT: None

parser

Parser for the object.

TYPE: Optional[CustomParser[MsgType]] DEFAULT: None

decoder

Decoder for the object.

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

Source code in faststream/broker/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[BrokerRoute[MsgType, SendableMessage]] = (),\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    include_in_schema: Optional[bool] = None,\n) -> None:\n    \"\"\"Initialize a class object.\n\n    Args:\n        prefix (str): Prefix for the object.\n        handlers (Sequence[BrokerRoute[MsgType, SendableMessage]]): Handlers for the object.\n        dependencies (Sequence[Depends]): Dependencies for the object.\n        middlewares (Optional[Sequence[Callable[[StreamMessage[MsgType]], AsyncContextManager[None]]]]): Middlewares for the object.\n        parser (Optional[CustomParser[MsgType]]): Parser for the object.\n        decoder (Optional[CustomDecoder[StreamMessage[MsgType]]]): Decoder for the object.\n\n    \"\"\"\n    self.prefix = prefix\n    self.include_in_schema = include_in_schema\n    self._handlers = list(handlers)\n    self._publishers = {}\n    self._dependencies = dependencies\n    self._middlewares = middlewares\n    self._parser = parser\n    self._decoder = decoder\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.subscriber","title":"subscriber abstractmethod","text":"
subscriber(\n    subj: str,\n    *args: Any,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    include_in_schema: Optional[bool] = None,\n    **kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function to subscribe to a subject.

PARAMETER DESCRIPTION subj

subject to subscribe to

*args

additional arguments

DEFAULT: ()

dependencies

sequence of dependencies

DEFAULT: ()

middlewares

optional sequence of middlewares

DEFAULT: None

parser

optional custom parser

DEFAULT: None

decoder

optional custom decoder

DEFAULT: None

**kwargs

additional keyword arguments

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable handler function

RAISES DESCRIPTION NotImplementedError

If the function is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef subscriber(\n    self,\n    subj: str,\n    *args: Any,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    include_in_schema: Optional[bool] = None,\n    **kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function to subscribe to a subject.\n\n    Args:\n        subj : subject to subscribe to\n        *args : additional arguments\n        dependencies : sequence of dependencies\n        middlewares : optional sequence of middlewares\n        parser : optional custom parser\n        decoder : optional custom decoder\n        **kwargs : additional keyword arguments\n\n    Returns:\n        A callable handler function\n\n    Raises:\n        NotImplementedError: If the function is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRoute/","title":"KafkaRoute","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/","title":"KafkaRouter","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter","title":"faststream.kafka.shared.router.KafkaRouter","text":"
KafkaRouter(\n    prefix: str = \"\",\n    handlers: Sequence[\n        KafkaRoute[ConsumerRecord, SendableMessage]\n    ] = (),\n    **kwargs: Any\n)\n

Bases: BrokerRouter[str, ConsumerRecord]

A class to represent a Kafka router.

METHOD DESCRIPTION subscriber

decorator for subscribing to topics and handling messages

Initialize the class.

PARAMETER DESCRIPTION prefix

Prefix string.

TYPE: str DEFAULT: ''

handlers

Sequence of KafkaRoute objects.

TYPE: Sequence[BrokerRoute[ConsumerRecord, SendableMessage]] DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/kafka/shared/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[KafkaRoute[ConsumerRecord, SendableMessage]] = (),\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        prefix (str): Prefix string.\n        handlers (Sequence[KafkaRoute[ConsumerRecord, SendableMessage]]): Sequence of KafkaRoute objects.\n        **kwargs (Any): Additional keyword arguments.\n\n    \"\"\"\n    for h in handlers:\n        h.args = tuple(prefix + x for x in h.args)\n    super().__init__(prefix, handlers, **kwargs)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.subscriber","title":"subscriber","text":"
subscriber(\n    *topics: str, **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        ConsumerRecord, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function to subscribe to topics.

PARAMETER DESCRIPTION *topics

variable number of topic names

DEFAULT: ()

**broker_kwargs

keyword arguments for the broker

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn]]

A callable function that wraps the handler function

Source code in faststream/kafka/shared/router.py
def subscriber(\n    self,\n    *topics: str,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function to subscribe to topics.\n\n    Args:\n        *topics : variable number of topic names\n        **broker_kwargs : keyword arguments for the broker\n\n    Returns:\n        A callable function that wraps the handler function\n\n    \"\"\"\n    return self._wrap_subscriber(\n        *(self.prefix + x for x in topics),\n        **broker_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/","title":"ConsumerConnectionParams","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams","title":"faststream.kafka.shared.schemas.ConsumerConnectionParams","text":"

Bases: TypedDict

A class to represent the connection parameters for a consumer.

","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.api_version","title":"api_version instance-attribute","text":"
api_version: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.bootstrap_servers","title":"bootstrap_servers instance-attribute","text":"
bootstrap_servers: Required[Union[str, List[str]]]\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.client_id","title":"client_id instance-attribute","text":"
client_id: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.connections_max_idle_ms","title":"connections_max_idle_ms instance-attribute","text":"
connections_max_idle_ms: int\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.loop","title":"loop instance-attribute","text":"
loop: Optional[AbstractEventLoop]\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.metadata_max_age_ms","title":"metadata_max_age_ms instance-attribute","text":"
metadata_max_age_ms: int\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.request_timeout_ms","title":"request_timeout_ms instance-attribute","text":"
request_timeout_ms: int\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.retry_backoff_ms","title":"retry_backoff_ms instance-attribute","text":"
retry_backoff_ms: int\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_kerberos_domain_name","title":"sasl_kerberos_domain_name instance-attribute","text":"
sasl_kerberos_domain_name: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_kerberos_service_name","title":"sasl_kerberos_service_name instance-attribute","text":"
sasl_kerberos_service_name: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_mechanism","title":"sasl_mechanism instance-attribute","text":"
sasl_mechanism: Literal[\n    \"PLAIN\",\n    \"GSSAPI\",\n    \"SCRAM-SHA-256\",\n    \"SCRAM-SHA-512\",\n    \"OAUTHBEARER\",\n]\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_oauth_token_provider","title":"sasl_oauth_token_provider instance-attribute","text":"
sasl_oauth_token_provider: AbstractTokenProvider\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_plain_password","title":"sasl_plain_password instance-attribute","text":"
sasl_plain_password: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_plain_username","title":"sasl_plain_username instance-attribute","text":"
sasl_plain_username: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.security_protocol","title":"security_protocol instance-attribute","text":"
security_protocol: Literal['SSL', 'PLAINTEXT']\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context: ssl.SSLContext\n
","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/","title":"FakeProducer","text":"","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/#faststream.kafka.test.FakeProducer","title":"faststream.kafka.test.FakeProducer","text":"
FakeProducer(broker: KafkaBroker)\n

Bases: AioKafkaFastProducer

A fake Kafka producer for testing purposes.

This class extends AioKafkaFastProducer and is used to simulate Kafka message publishing during tests.

Initialize the FakeProducer.

PARAMETER DESCRIPTION broker

The KafkaBroker instance to associate with this FakeProducer.

TYPE: KafkaBroker

Source code in faststream/kafka/test.py
def __init__(self, broker: KafkaBroker) -> None:\n    \"\"\"\n    Initialize the FakeProducer.\n\n    Args:\n        broker (KafkaBroker): The KafkaBroker instance to associate with this FakeProducer.\n    \"\"\"\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/#faststream.kafka.test.FakeProducer.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/#faststream.kafka.test.FakeProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\",\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False\n) -> Optional[SendableMessage]\n

Publish a message to the Kafka broker.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

topic

The Kafka topic to publish the message to.

TYPE: str

key

The message key. Defaults to None.

TYPE: Optional[bytes] DEFAULT: None

partition

The Kafka partition to use. Defaults to None.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

The message timestamp in milliseconds. Defaults to None.

TYPE: Optional[int] DEFAULT: None

headers

Additional headers for the message. Defaults to None.

TYPE: Optional[Dict[str, str]] DEFAULT: None

correlation_id

The correlation ID for the message. Defaults to None.

TYPE: Optional[str] DEFAULT: None

reply_to

The topic to which responses should be sent. Defaults to \"\".

TYPE: str DEFAULT: ''

rpc

If True, treat the message as an RPC request. Defaults to False.

TYPE: bool DEFAULT: False

rpc_timeout

Timeout for RPC requests. Defaults to None.

TYPE: Optional[float] DEFAULT: None

raise_timeout

If True, raise an exception on timeout. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION Optional[SendableMessage]

Optional[SendableMessage]: The response message, if this was an RPC request, otherwise None.

Source code in faststream/kafka/test.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\",\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False,\n) -> Optional[SendableMessage]:\n    \"\"\"\n    Publish a message to the Kafka broker.\n\n    Args:\n        message (SendableMessage): The message to be published.\n        topic (str): The Kafka topic to publish the message to.\n        key (Optional[bytes], optional): The message key. Defaults to None.\n        partition (Optional[int], optional): The Kafka partition to use. Defaults to None.\n        timestamp_ms (Optional[int], optional): The message timestamp in milliseconds. Defaults to None.\n        headers (Optional[Dict[str, str]], optional): Additional headers for the message. Defaults to None.\n        correlation_id (Optional[str], optional): The correlation ID for the message. Defaults to None.\n        reply_to (str, optional): The topic to which responses should be sent. Defaults to \"\".\n        rpc (bool, optional): If True, treat the message as an RPC request. Defaults to False.\n        rpc_timeout (Optional[float], optional): Timeout for RPC requests. Defaults to None.\n        raise_timeout (bool, optional): If True, raise an exception on timeout. Defaults to False.\n\n    Returns:\n        Optional[SendableMessage]: The response message, if this was an RPC request, otherwise None.\n    \"\"\"\n    incoming = build_message(\n        message=message,\n        topic=topic,\n        key=key,\n        partition=partition,\n        timestamp_ms=timestamp_ms,\n        headers=headers,\n        correlation_id=correlation_id,\n        reply_to=reply_to,\n    )\n\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        if topic in handler.topics:\n            return await call_handler(\n                handler=handler,\n                message=[incoming] if handler.batch else incoming,\n                rpc=rpc,\n                rpc_timeout=rpc_timeout,\n                raise_timeout=raise_timeout,\n            )\n\n    return None\n
","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/#faststream.kafka.test.FakeProducer.publish_batch","title":"publish_batch async","text":"
publish_batch(\n    *msgs: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None\n) -> None\n

Publish a batch of messages to the Kafka broker.

PARAMETER DESCRIPTION *msgs

Variable number of messages to be published.

TYPE: SendableMessage DEFAULT: ()

topic

The Kafka topic to publish the messages to.

TYPE: str

partition

The Kafka partition to use. Defaults to None.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

The message timestamp in milliseconds. Defaults to None.

TYPE: Optional[int] DEFAULT: None

headers

Additional headers for the messages. Defaults to None.

TYPE: Optional[Dict[str, str]] DEFAULT: None

RETURNS DESCRIPTION None

This method does not return a value.

TYPE: None

Source code in faststream/kafka/test.py
async def publish_batch(\n    self,\n    *msgs: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n) -> None:\n    \"\"\"\n    Publish a batch of messages to the Kafka broker.\n\n    Args:\n        *msgs (SendableMessage): Variable number of messages to be published.\n        topic (str): The Kafka topic to publish the messages to.\n        partition (Optional[int], optional): The Kafka partition to use. Defaults to None.\n        timestamp_ms (Optional[int], optional): The message timestamp in milliseconds. Defaults to None.\n        headers (Optional[Dict[str, str]], optional): Additional headers for the messages. Defaults to None.\n\n    Returns:\n        None: This method does not return a value.\n    \"\"\"\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        if topic in handler.topics:\n            await call_handler(\n                handler=handler,\n                message=[\n                    build_message(\n                        message=message,\n                        topic=topic,\n                        partition=partition,\n                        timestamp_ms=timestamp_ms,\n                        headers=headers,\n                    )\n                    for message in msgs\n                ],\n            )\n\n    return None\n
","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/#faststream.kafka.test.FakeProducer.stop","title":"stop async","text":"
stop() -> None\n
Source code in faststream/kafka/producer.py
async def stop(self) -> None:\n    if self._producer is not None:  # pragma: no branch\n        await self._producer.stop()\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/","title":"TestKafkaBroker","text":"","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker","title":"faststream.kafka.test.TestKafkaBroker","text":"
TestKafkaBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[KafkaBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/kafka/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: KafkaBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(  # type: ignore[call-overload,misc]\n        publisher.topic,\n        batch=publisher.batch,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f  # type: ignore[no-any-return]\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: KafkaBroker, publisher: Any\n) -> None\n
Source code in faststream/kafka/test.py
@staticmethod\ndef patch_publisher(broker: KafkaBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> None\n
Source code in faststream/kafka/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> None:\n    broker.handlers.pop(publisher.topic, None)\n
","boost":0.5},{"location":"api/faststream/kafka/test/build_message/","title":"build_message","text":"","boost":0.5},{"location":"api/faststream/kafka/test/build_message/#faststream.kafka.test.build_message","title":"faststream.kafka.test.build_message","text":"
build_message(\n    message: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    key: Optional[bytes] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\"\n) -> ConsumerRecord\n

Build a Kafka ConsumerRecord for a sendable message.

PARAMETER DESCRIPTION message

The sendable message to be encoded.

TYPE: SendableMessage

topic

The Kafka topic for the message.

TYPE: str

partition

The Kafka partition for the message. Defaults to None.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

The message timestamp in milliseconds. Defaults to None.

TYPE: Optional[int] DEFAULT: None

key

The message key. Defaults to None.

TYPE: Optional[bytes] DEFAULT: None

headers

Additional headers for the message. Defaults to None.

TYPE: Optional[Dict[str, str]] DEFAULT: None

correlation_id

The correlation ID for the message. Defaults to None.

TYPE: Optional[str] DEFAULT: None

reply_to

The topic to which responses should be sent. Defaults to \"\".

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION ConsumerRecord

A Kafka ConsumerRecord object.

TYPE: ConsumerRecord

Source code in faststream/kafka/test.py
def build_message(\n    message: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    key: Optional[bytes] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\",\n) -> ConsumerRecord:\n    \"\"\"\n    Build a Kafka ConsumerRecord for a sendable message.\n\n    Args:\n        message (SendableMessage): The sendable message to be encoded.\n        topic (str): The Kafka topic for the message.\n        partition (Optional[int], optional): The Kafka partition for the message. Defaults to None.\n        timestamp_ms (Optional[int], optional): The message timestamp in milliseconds. Defaults to None.\n        key (Optional[bytes], optional): The message key. Defaults to None.\n        headers (Optional[Dict[str, str]], optional): Additional headers for the message. Defaults to None.\n        correlation_id (Optional[str], optional): The correlation ID for the message. Defaults to None.\n        reply_to (str, optional): The topic to which responses should be sent. Defaults to \"\".\n\n    Returns:\n        ConsumerRecord: A Kafka ConsumerRecord object.\n    \"\"\"\n    msg, content_type = encode_message(message)\n    k = key or b\"\"\n    headers = {\n        \"content-type\": content_type or \"\",\n        \"correlation_id\": correlation_id or str(uuid4()),\n        \"reply_to\": reply_to,\n        **(headers or {}),\n    }\n\n    return ConsumerRecord(\n        value=msg,\n        topic=topic,\n        partition=partition or 0,\n        timestamp=timestamp_ms or int(datetime.now().timestamp()),\n        timestamp_type=0,\n        key=k,\n        serialized_key_size=len(k),\n        serialized_value_size=len(msg),\n        checksum=sum(msg),\n        offset=0,\n        headers=[(i, j.encode()) for i, j in headers.items()],\n    )\n
","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/","title":"ColourizedFormatter","text":"","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/#faststream.log.formatter.ColourizedFormatter","title":"faststream.log.formatter.ColourizedFormatter","text":"
ColourizedFormatter(\n    fmt: Optional[str] = None,\n    datefmt: Optional[str] = None,\n    style: Literal[\"%\", \"{\", \"$\"] = \"%\",\n    use_colors: Optional[bool] = None,\n)\n

Bases: Formatter

A class to format log messages with colorized level names.

METHOD DESCRIPTION __init__

Initialize the formatter with specified format strings.

color_level_name

Colorize the level name based on the log level.

formatMessage

Format the log record message with colorized level name.

Initialize the formatter with specified format strings.

Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.

Use a style parameter of '%', '{' or '$' to specify that you want to use one of %-formatting, :meth:str.format ({}) formatting or :class:string.Template formatting in your format string.

Source code in faststream/log/formatter.py
def __init__(\n    self,\n    fmt: Optional[str] = None,\n    datefmt: Optional[str] = None,\n    style: Literal[\"%\", \"{\", \"$\"] = \"%\",\n    use_colors: Optional[bool] = None,\n) -> None:\n    \"\"\"\n    Initialize the formatter with specified format strings.\n\n    Initialize the formatter either with the specified format string, or a\n    default as described above. Allow for specialized date formatting with\n    the optional datefmt argument. If datefmt is omitted, you get an\n    ISO8601-like (or RFC 3339-like) format.\n\n    Use a style parameter of '%', '{' or '$' to specify that you want to\n    use one of %-formatting, :meth:`str.format` (``{}``) formatting or\n    :class:`string.Template` formatting in your format string.\n    \"\"\"\n    if use_colors in (True, False):\n        self.use_colors = use_colors\n    else:\n        self.use_colors = sys.stdout.isatty()\n    super().__init__(fmt=fmt, datefmt=datefmt, style=style)\n
","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/#faststream.log.formatter.ColourizedFormatter.level_name_colors","title":"level_name_colors class-attribute instance-attribute","text":"
level_name_colors: DefaultDict[\n    str, Callable[[str], str]\n] = defaultdict(\n    lambda: str,\n    **{\n        str(logging.DEBUG): lambda: click.style(\n            str(level_name), fg=\"cyan\"\n        ),\n        str(logging.INFO): lambda: click.style(\n            str(level_name), fg=\"green\"\n        ),\n        str(logging.WARNING): lambda: click.style(\n            str(level_name), fg=\"yellow\"\n        ),\n        str(logging.ERROR): lambda: click.style(\n            str(level_name), fg=\"red\"\n        ),\n        str(logging.CRITICAL): lambda: click.style(\n            str(level_name), fg=\"bright_red\"\n        ),\n    }\n)\n
","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/#faststream.log.formatter.ColourizedFormatter.use_colors","title":"use_colors instance-attribute","text":"
use_colors = use_colors\n
","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/#faststream.log.formatter.ColourizedFormatter.color_level_name","title":"color_level_name","text":"
color_level_name(level_name: str, level_no: int) -> str\n

Returns the colored level name.

PARAMETER DESCRIPTION level_name

The name of the level.

TYPE: str

level_no

The number of the level.

TYPE: int

RETURNS DESCRIPTION str

The colored level name.

RAISES DESCRIPTION KeyError

If the level number is not found in the level name colors dictionary.

Source code in faststream/log/formatter.py
def color_level_name(self, level_name: str, level_no: int) -> str:\n    \"\"\"Returns the colored level name.\n\n    Args:\n        level_name: The name of the level.\n        level_no: The number of the level.\n\n    Returns:\n        The colored level name.\n\n    Raises:\n        KeyError: If the level number is not found in the level name colors dictionary.\n\n    \"\"\"\n    return self.level_name_colors[str(level_no)](level_name)\n
","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/#faststream.log.formatter.ColourizedFormatter.formatMessage","title":"formatMessage","text":"
formatMessage(record: logging.LogRecord) -> str\n

Formats the log message.

PARAMETER DESCRIPTION record

The log record to format.

TYPE: LogRecord

RETURNS DESCRIPTION str

The formatted log message.

TYPE: str

Source code in faststream/log/formatter.py
def formatMessage(self, record: logging.LogRecord) -> str:\n    \"\"\"Formats the log message.\n\n    Args:\n        record (logging.LogRecord): The log record to format.\n\n    Returns:\n        str: The formatted log message.\n\n    \"\"\"\n    levelname = expand_log_field(record.levelname, 8)\n    if self.use_colors is True:  # pragma: no cover\n        levelname = self.color_level_name(levelname, record.levelno)\n    record.__dict__[\"levelname\"] = levelname\n    return super().formatMessage(record)\n
","boost":0.5},{"location":"api/faststream/log/formatter/expand_log_field/","title":"expand_log_field","text":"","boost":0.5},{"location":"api/faststream/log/formatter/expand_log_field/#faststream.log.formatter.expand_log_field","title":"faststream.log.formatter.expand_log_field","text":"
expand_log_field(field: str, symbols: int) -> str\n

Expands a log field by adding spaces.

PARAMETER DESCRIPTION field

The log field to expand.

TYPE: str

symbols

The desired length of the expanded field.

TYPE: int

RETURNS DESCRIPTION str

The expanded log field.

Source code in faststream/log/formatter.py
def expand_log_field(field: str, symbols: int) -> str:\n    \"\"\"Expands a log field by adding spaces.\n\n    Args:\n        field: The log field to expand.\n        symbols: The desired length of the expanded field.\n\n    Returns:\n        The expanded log field.\n\n    \"\"\"\n    return field + (\" \" * (symbols - len(field)))\n
","boost":0.5},{"location":"api/faststream/log/formatter/make_record_with_extra/","title":"make_record_with_extra","text":"","boost":0.5},{"location":"api/faststream/log/formatter/make_record_with_extra/#faststream.log.formatter.make_record_with_extra","title":"faststream.log.formatter.make_record_with_extra","text":"
make_record_with_extra(\n    self: logging.Logger,\n    name: str,\n    level: int,\n    fn: str,\n    lno: int,\n    msg: str,\n    args: Tuple[str],\n    exc_info: Optional[\n        Union[\n            Tuple[\n                Type[BaseException],\n                BaseException,\n                Optional[TracebackType],\n            ],\n            Tuple[None, None, None],\n        ]\n    ],\n    func: Optional[str] = None,\n    extra: Optional[Mapping[str, object]] = None,\n    sinfo: Optional[str] = None,\n) -> logging.LogRecord\n

Creates a log record with additional information.

PARAMETER DESCRIPTION self

The logger object.

TYPE: Logger

name

The name of the logger.

TYPE: str

level

The logging level.

TYPE: int

fn

The filename where the log message originated.

TYPE: str

lno

The line number where the log message originated.

TYPE: int

msg

The log message.

TYPE: str

args

The arguments for the log message.

TYPE: Tuple[str]

exc_info

Information about an exception.

TYPE: Optional[Union[Tuple[Type[BaseException], BaseException, Optional[TracebackType]], Tuple[None, None, None]]]

func

The name of the function where the log message originated.

TYPE: Optional[str] DEFAULT: None

extra

Additional information to include in the log record.

TYPE: Optional[Mapping[str, object]] DEFAULT: None

sinfo

Stack information.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION LogRecord

The log record.

Note

If extra is None, it will be set to the value of context.get_local(\"log_context\").

Source code in faststream/log/formatter.py
def make_record_with_extra(\n    self: logging.Logger,\n    name: str,\n    level: int,\n    fn: str,\n    lno: int,\n    msg: str,\n    args: Tuple[str],\n    exc_info: Optional[\n        Union[\n            Tuple[Type[BaseException], BaseException, Optional[TracebackType]],\n            Tuple[None, None, None],\n        ]\n    ],\n    func: Optional[str] = None,\n    extra: Optional[Mapping[str, object]] = None,\n    sinfo: Optional[str] = None,\n) -> logging.LogRecord:\n    \"\"\"Creates a log record with additional information.\n\n    Args:\n        self: The logger object.\n        name: The name of the logger.\n        level: The logging level.\n        fn: The filename where the log message originated.\n        lno: The line number where the log message originated.\n        msg: The log message.\n        args: The arguments for the log message.\n        exc_info: Information about an exception.\n        func: The name of the function where the log message originated.\n        extra: Additional information to include in the log record.\n        sinfo: Stack information.\n\n    Returns:\n        The log record.\n\n    Note:\n        If `extra` is `None`, it will be set to the value of `context.get_local(\"log_context\")`.\n\n    \"\"\"\n    if extra is None:\n        extra = context.get_local(\n            \"log_context\", default=context.get(\"default_log_context\")\n        )\n\n    record = original_makeRecord(\n        self,\n        name,\n        level,\n        fn,\n        lno,\n        msg,\n        args,\n        exc_info,\n        func,\n        extra,\n        sinfo,\n    )\n\n    return record\n
","boost":0.5},{"location":"api/faststream/log/logging/configure_formatter/","title":"configure_formatter","text":"","boost":0.5},{"location":"api/faststream/log/logging/configure_formatter/#faststream.log.logging.configure_formatter","title":"faststream.log.logging.configure_formatter","text":"
configure_formatter(\n    formatter: Type[logging.Formatter],\n    *args: Any,\n    **kwargs: Any\n) -> logging.Formatter\n

Configures a logging formatter.

PARAMETER DESCRIPTION formatter

The type of logging formatter to configure.

TYPE: Type[Formatter]

*args

Additional positional arguments to pass to the formatter constructor.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments to pass to the formatter constructor.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Formatter

An instance of the configured logging formatter.

Source code in faststream/log/logging.py
def configure_formatter(\n    formatter: Type[logging.Formatter], *args: Any, **kwargs: Any\n) -> logging.Formatter:\n    \"\"\"Configures a logging formatter.\n\n    Args:\n        formatter: The type of logging formatter to configure.\n        *args: Additional positional arguments to pass to the formatter constructor.\n        **kwargs: Additional keyword arguments to pass to the formatter constructor.\n\n    Returns:\n        An instance of the configured logging formatter.\n\n    \"\"\"\n    return formatter(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/nats/AckPolicy/","title":"AckPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/AckPolicy/#nats.js.api.AckPolicy","title":"nats.js.api.AckPolicy","text":"

Bases: str, Enum

Policies defining how messages should be acknowledged.

If an ack is required but is not received within the AckWait window, the message will be redelivered.

References ","boost":0.5},{"location":"api/faststream/nats/AckPolicy/#nats.js.api.AckPolicy.ALL","title":"ALL class-attribute instance-attribute","text":"
ALL = 'all'\n
","boost":0.5},{"location":"api/faststream/nats/AckPolicy/#nats.js.api.AckPolicy.EXPLICIT","title":"EXPLICIT class-attribute instance-attribute","text":"
EXPLICIT = 'explicit'\n
","boost":0.5},{"location":"api/faststream/nats/AckPolicy/#nats.js.api.AckPolicy.NONE","title":"NONE class-attribute instance-attribute","text":"
NONE = 'none'\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/","title":"ConsumerConfig","text":"","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig","title":"nats.js.api.ConsumerConfig dataclass","text":"

Bases: Base

Consumer configuration.

References ","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.ack_policy","title":"ack_policy class-attribute instance-attribute","text":"
ack_policy: Optional[AckPolicy] = AckPolicy.EXPLICIT\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.ack_wait","title":"ack_wait class-attribute instance-attribute","text":"
ack_wait: Optional[float] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.deliver_group","title":"deliver_group class-attribute instance-attribute","text":"
deliver_group: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.deliver_policy","title":"deliver_policy class-attribute instance-attribute","text":"
deliver_policy: Optional[DeliverPolicy] = DeliverPolicy.ALL\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.deliver_subject","title":"deliver_subject class-attribute instance-attribute","text":"
deliver_subject: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.durable_name","title":"durable_name class-attribute instance-attribute","text":"
durable_name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.filter_subject","title":"filter_subject class-attribute instance-attribute","text":"
filter_subject: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.flow_control","title":"flow_control class-attribute instance-attribute","text":"
flow_control: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.headers_only","title":"headers_only class-attribute instance-attribute","text":"
headers_only: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.idle_heartbeat","title":"idle_heartbeat class-attribute instance-attribute","text":"
idle_heartbeat: Optional[float] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.inactive_threshold","title":"inactive_threshold class-attribute instance-attribute","text":"
inactive_threshold: Optional[float] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.max_ack_pending","title":"max_ack_pending class-attribute instance-attribute","text":"
max_ack_pending: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.max_deliver","title":"max_deliver class-attribute instance-attribute","text":"
max_deliver: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.max_waiting","title":"max_waiting class-attribute instance-attribute","text":"
max_waiting: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.mem_storage","title":"mem_storage class-attribute instance-attribute","text":"
mem_storage: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.num_replicas","title":"num_replicas class-attribute instance-attribute","text":"
num_replicas: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.opt_start_seq","title":"opt_start_seq class-attribute instance-attribute","text":"
opt_start_seq: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.opt_start_time","title":"opt_start_time class-attribute instance-attribute","text":"
opt_start_time: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.rate_limit_bps","title":"rate_limit_bps class-attribute instance-attribute","text":"
rate_limit_bps: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.replay_policy","title":"replay_policy class-attribute instance-attribute","text":"
replay_policy: Optional[ReplayPolicy] = ReplayPolicy.INSTANT\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.sample_freq","title":"sample_freq class-attribute instance-attribute","text":"
sample_freq: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n
Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    result = super().as_dict()\n    result['ack_wait'] = self._to_nanoseconds(self.ack_wait)\n    result['idle_heartbeat'] = self._to_nanoseconds(self.idle_heartbeat)\n    result['inactive_threshold'] = self._to_nanoseconds(\n        self.inactive_threshold\n    )\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any])\n
Source code in nats/js/api.py
@classmethod\ndef from_response(cls, resp: Dict[str, Any]):\n    cls._convert_nanoseconds(resp, 'ack_wait')\n    cls._convert_nanoseconds(resp, 'idle_heartbeat')\n    cls._convert_nanoseconds(resp, 'inactive_threshold')\n    return super().from_response(resp)\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/","title":"DeliverPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy","title":"nats.js.api.DeliverPolicy","text":"

Bases: str, Enum

When a consumer is first created, it can specify where in the stream it wants to start receiving messages.

This is the DeliverPolicy, and this enumeration defines allowed values.

References ","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.ALL","title":"ALL class-attribute instance-attribute","text":"
ALL = 'all'\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.BY_START_SEQUENCE","title":"BY_START_SEQUENCE class-attribute instance-attribute","text":"
BY_START_SEQUENCE = 'by_start_sequence'\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.BY_START_TIME","title":"BY_START_TIME class-attribute instance-attribute","text":"
BY_START_TIME = 'by_start_time'\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.LAST","title":"LAST class-attribute instance-attribute","text":"
LAST = 'last'\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.LAST_PER_SUBJECT","title":"LAST_PER_SUBJECT class-attribute instance-attribute","text":"
LAST_PER_SUBJECT = 'last_per_subject'\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.NEW","title":"NEW class-attribute instance-attribute","text":"
NEW = 'new'\n
","boost":0.5},{"location":"api/faststream/nats/DiscardPolicy/","title":"DiscardPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/DiscardPolicy/#nats.js.api.DiscardPolicy","title":"nats.js.api.DiscardPolicy","text":"

Bases: str, Enum

Discard policy when a stream reaches its limits

","boost":0.5},{"location":"api/faststream/nats/DiscardPolicy/#nats.js.api.DiscardPolicy.NEW","title":"NEW class-attribute instance-attribute","text":"
NEW = 'new'\n
","boost":0.5},{"location":"api/faststream/nats/DiscardPolicy/#nats.js.api.DiscardPolicy.OLD","title":"OLD class-attribute instance-attribute","text":"
OLD = 'old'\n
","boost":0.5},{"location":"api/faststream/nats/ExternalStream/","title":"ExternalStream","text":"","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream","title":"nats.js.api.ExternalStream dataclass","text":"

Bases: Base

","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream.api","title":"api instance-attribute","text":"
api: str\n
","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream.deliver","title":"deliver class-attribute instance-attribute","text":"
deliver: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/JStream/","title":"JStream","text":"","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream","title":"faststream.nats.JStream","text":"
JStream(\n    name: str,\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any\n)\n

Bases: NameRequired

Source code in faststream/nats/js_stream.py
def __init__(\n    self,\n    name: str,\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any,\n) -> None:\n    super().__init__(\n        name=name,\n        declare=declare,\n        subjects=[],\n        config=StreamConfig(\n            *args,\n            name=name,\n            **kwargs,  # type: ignore[misc]\n        ),\n    )\n
","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream.config","title":"config instance-attribute","text":"
config: StreamConfig\n
","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream.declare","title":"declare class-attribute instance-attribute","text":"
declare: bool = Field(default=True)\n
","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream.subjects","title":"subjects class-attribute instance-attribute","text":"
subjects: List[str] = Field(default_factory=list)\n
","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/","title":"NatsBroker","text":"","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker","title":"faststream.nats.NatsBroker","text":"
NatsBroker(\n    servers: Union[str, Sequence[str]] = (\n        \"nats://localhost:4222\"\n    ),\n    *,\n    security: Optional[BaseSecurity] = None,\n    protocol: str = \"nats\",\n    protocol_version: Optional[str] = \"custom\",\n    **kwargs: Any\n)\n

Bases: NatsLoggingMixin, BrokerAsyncUsecase[Msg, Client]

Source code in faststream/nats/broker.py
def __init__(\n    self,\n    servers: Union[str, Sequence[str]] = (\"nats://localhost:4222\",),  # noqa: B006\n    *,\n    security: Optional[BaseSecurity] = None,\n    protocol: str = \"nats\",\n    protocol_version: Optional[str] = \"custom\",\n    **kwargs: Any,\n) -> None:\n    kwargs.update(parse_security(security))\n\n    if kwargs.get(\"tls\"):  # pragma: no cover\n        warnings.warn(\n            (\n                \"\\nNATS `tls` option was deprecated and will be removed in 0.4.0\"\n                \"\\nPlease, use `security` with `BaseSecurity` or `SASLPlaintext` instead\"\n            ),\n            DeprecationWarning,\n            stacklevel=2,\n        )\n\n    super().__init__(\n        url=([servers] if isinstance(servers, str) else list(servers)),\n        protocol=protocol,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n    )\n\n    self.__is_connected = False\n    self._producer = None\n\n    # JS options\n    self.stream = None\n    self._js_producer = None\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[Subject, Handler]\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.stream","title":"stream instance-attribute","text":"
stream: Optional[JetStreamContext] = None\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.url","title":"url instance-attribute","text":"
url: List[str]\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.connect","title":"connect async","text":"
connect(*args: Any, **kwargs: Any) -> Client\n
Source code in faststream/nats/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Client:\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        self.__set_publisher_producer(p)\n    return connection\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, stream: Optional[str] = None, **kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    stream: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[DecodedMessage]:\n    if stream is None:\n        assert self._producer, NOT_CONNECTED_YET  # nosec B101\n        return await self._producer.publish(*args, **kwargs)\n    else:\n        assert self._js_producer, NOT_CONNECTED_YET  # nosec B101\n        return await self._js_producer.publish(\n            *args,\n            stream=stream,\n            **kwargs,  # type: ignore[misc]\n        )\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.publisher","title":"publisher","text":"
publisher(\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    stream: Union[str, JStream, None] = None,\n    timeout: Optional[float] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/nats/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    # Core\n    reply_to: str = \"\",\n    # JS\n    stream: Union[str, JStream, None] = None,\n    timeout: Optional[float] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    if (stream := stream_builder.stream(stream)) is not None:\n        stream.subjects.append(subject)\n\n    publisher = self._publishers.get(\n        subject,\n        Publisher(\n            subject=subject,\n            headers=headers,\n            # Core\n            reply_to=reply_to,\n            # JS\n            timeout=timeout,\n            stream=stream,\n            # AsyncAPI\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(subject, publisher)\n    self.__set_publisher_producer(publisher)\n    return publisher\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.start","title":"start async","text":"
start() -> None\n
Source code in faststream/nats/broker.py
async def start(self) -> None:\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n    assert (\n        self._connection and self.stream\n    ), \"Broker should be started already\"  # nosec B101\n\n    for handler in self.handlers.values():\n        stream = handler.stream\n\n        if (is_js := stream is not None) and stream.declare:\n            try:  # pragma: no branch\n                await self.stream.add_stream(\n                    config=stream.config,\n                    subjects=stream.subjects,\n                )\n\n            except nats.js.errors.BadRequestError as e:\n                old_config = (await self.stream.stream_info(stream.name)).config\n\n                c = self._get_log_context(None, \"\")\n                if (\n                    e.description\n                    == \"stream name already in use with a different configuration\"\n                ):\n                    self._log(str(e), logging.WARNING, c)\n                    await self.stream.update_stream(\n                        config=stream.config,\n                        subjects=tuple(\n                            set(old_config.subjects or ()).union(stream.subjects)\n                        ),\n                    )\n\n                else:  # pragma: no cover\n                    self._log(str(e), logging.ERROR, c, exc_info=e)\n\n            finally:\n                # prevent from double declaration\n                stream.declare = False\n\n        c = self._get_log_context(\n            None,\n            subject=handler.subject,\n            queue=handler.queue,\n            stream=stream.name if stream else \"\",\n        )\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self.stream if is_js else self._connection)\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/nats/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    # Core arguments\n    max_msgs: int = 0,\n    # JS arguments\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    # pull arguments\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    # custom\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[Sequence[Callable[[Msg], BaseMiddleware]]] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],\n]:\n    stream = stream_builder.stream(stream)\n\n    if pull_sub is not None and stream is None:\n        raise ValueError(\"Pull subscriber can be used only with a stream\")\n\n    self._setup_log_context(\n        queue=queue,\n        subject=subject,\n        stream=stream.name if stream else None,\n    )\n    super().subscriber()\n\n    extra_options: AnyDict = {\n        \"pending_msgs_limit\": pending_msgs_limit\n        or (\n            DEFAULT_JS_SUB_PENDING_MSGS_LIMIT\n            if stream\n            else DEFAULT_SUB_PENDING_MSGS_LIMIT\n        ),\n        \"pending_bytes_limit\": pending_bytes_limit\n        or (\n            DEFAULT_JS_SUB_PENDING_BYTES_LIMIT\n            if stream\n            else DEFAULT_SUB_PENDING_BYTES_LIMIT\n        ),\n    }\n\n    if stream:\n        extra_options.update(\n            {\n                \"durable\": durable,\n                \"stream\": stream.name,\n                \"config\": config,\n            }\n        )\n\n        if pull_sub is not None:\n            extra_options.update({\"inbox_prefix\": inbox_prefix})\n\n        else:\n            extra_options.update(\n                {\n                    \"ordered_consumer\": ordered_consumer,\n                    \"idle_heartbeat\": idle_heartbeat,\n                    \"flow_control\": flow_control,\n                    \"deliver_policy\": deliver_policy,\n                    \"headers_only\": headers_only,\n                    \"manual_ack\": not ack_first,\n                }\n            )\n\n    else:\n        extra_options.update(\n            {\n                \"max_msgs\": max_msgs,\n            }\n        )\n\n    key = Handler.get_routing_hash(subject)\n    handler = self.handlers[key] = self.handlers.get(\n        key,\n        Handler(\n            subject=subject,\n            queue=queue,\n            stream=stream,\n            pull_sub=pull_sub,\n            extra_options=extra_options,\n            title=title,\n            description=description,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n            log_context_builder=partial(\n                self._get_log_context,\n                stream=stream.name if stream else \"\",\n                subject=subject,\n                queue=queue,\n            ),\n        ),\n    )\n\n    if stream:\n        stream.subjects.append(handler.subject)\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn,]:\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/nats/NatsRoute/","title":"NatsRoute","text":"","boost":0.5},{"location":"api/faststream/nats/NatsRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/nats/NatsRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/nats/NatsRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/nats/NatsRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/","title":"NatsRouter","text":"","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter","title":"faststream.nats.NatsRouter","text":"
NatsRouter(\n    prefix: str = \"\",\n    handlers: Sequence[NatsRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: NatsRouter

Source code in faststream/nats/router.py
    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.publisher","title":"publisher","text":"
publisher(\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/nats/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            subject=subject,\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    retry: bool = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
","boost":0.5},{"location":"api/faststream/nats/Placement/","title":"Placement","text":"","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement","title":"nats.js.api.Placement dataclass","text":"

Bases: Base

Placement directives to consider when placing replicas of this stream

","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement.cluster","title":"cluster class-attribute instance-attribute","text":"
cluster: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/PullSub/","title":"PullSub","text":"","boost":0.5},{"location":"api/faststream/nats/PullSub/#faststream.nats.PullSub","title":"faststream.nats.PullSub","text":"
PullSub(\n    batch_size: int = 1,\n    timeout: Optional[float] = 5.0,\n    batch: bool = False,\n)\n

Bases: BaseModel

Source code in faststream/nats/pull_sub.py
def __init__(\n    self,\n    batch_size: int = 1,\n    timeout: Optional[float] = 5.0,\n    batch: bool = False,\n) -> None:\n    super().__init__(\n        batch_size=batch_size,\n        timeout=timeout,\n        batch=batch,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/PullSub/#faststream.nats.PullSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = Field(default=False)\n
","boost":0.5},{"location":"api/faststream/nats/PullSub/#faststream.nats.PullSub.batch_size","title":"batch_size class-attribute instance-attribute","text":"
batch_size: int = Field(default=1)\n
","boost":0.5},{"location":"api/faststream/nats/PullSub/#faststream.nats.PullSub.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: Optional[float] = Field(default=5.0)\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/","title":"RePublish","text":"","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish","title":"nats.js.api.RePublish dataclass","text":"

Bases: Base

RePublish is for republishing messages once committed to a stream. The original subject cis remapped from the subject pattern to the destination pattern.

","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.dest","title":"dest class-attribute instance-attribute","text":"
dest: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.headers_only","title":"headers_only class-attribute instance-attribute","text":"
headers_only: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.src","title":"src class-attribute instance-attribute","text":"
src: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/ReplayPolicy/","title":"ReplayPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/ReplayPolicy/#nats.js.api.ReplayPolicy","title":"nats.js.api.ReplayPolicy","text":"

Bases: str, Enum

The replay policy applies when the DeliverPolicy is one of

since those deliver policies begin reading the stream at a position other than the end.

References ","boost":0.5},{"location":"api/faststream/nats/ReplayPolicy/#nats.js.api.ReplayPolicy.INSTANT","title":"INSTANT class-attribute instance-attribute","text":"
INSTANT = 'instant'\n
","boost":0.5},{"location":"api/faststream/nats/ReplayPolicy/#nats.js.api.ReplayPolicy.ORIGINAL","title":"ORIGINAL class-attribute instance-attribute","text":"
ORIGINAL = 'original'\n
","boost":0.5},{"location":"api/faststream/nats/RetentionPolicy/","title":"RetentionPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/RetentionPolicy/#nats.js.api.RetentionPolicy","title":"nats.js.api.RetentionPolicy","text":"

Bases: str, Enum

How message retention is considered

","boost":0.5},{"location":"api/faststream/nats/RetentionPolicy/#nats.js.api.RetentionPolicy.INTEREST","title":"INTEREST class-attribute instance-attribute","text":"
INTEREST = 'interest'\n
","boost":0.5},{"location":"api/faststream/nats/RetentionPolicy/#nats.js.api.RetentionPolicy.LIMITS","title":"LIMITS class-attribute instance-attribute","text":"
LIMITS = 'limits'\n
","boost":0.5},{"location":"api/faststream/nats/RetentionPolicy/#nats.js.api.RetentionPolicy.WORK_QUEUE","title":"WORK_QUEUE class-attribute instance-attribute","text":"
WORK_QUEUE = 'workqueue'\n
","boost":0.5},{"location":"api/faststream/nats/StorageType/","title":"StorageType","text":"","boost":0.5},{"location":"api/faststream/nats/StorageType/#nats.js.api.StorageType","title":"nats.js.api.StorageType","text":"

Bases: str, Enum

The type of storage backend

","boost":0.5},{"location":"api/faststream/nats/StorageType/#nats.js.api.StorageType.FILE","title":"FILE class-attribute instance-attribute","text":"
FILE = 'file'\n
","boost":0.5},{"location":"api/faststream/nats/StorageType/#nats.js.api.StorageType.MEMORY","title":"MEMORY class-attribute instance-attribute","text":"
MEMORY = 'memory'\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/","title":"StreamConfig","text":"","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig","title":"nats.js.api.StreamConfig dataclass","text":"

Bases: Base

StreamConfig represents the configuration of a stream.

","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.allow_direct","title":"allow_direct class-attribute instance-attribute","text":"
allow_direct: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.allow_rollup_hdrs","title":"allow_rollup_hdrs class-attribute instance-attribute","text":"
allow_rollup_hdrs: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.deny_delete","title":"deny_delete class-attribute instance-attribute","text":"
deny_delete: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.deny_purge","title":"deny_purge class-attribute instance-attribute","text":"
deny_purge: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.discard","title":"discard class-attribute instance-attribute","text":"
discard: Optional[DiscardPolicy] = DiscardPolicy.OLD\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.duplicate_window","title":"duplicate_window class-attribute instance-attribute","text":"
duplicate_window: float = 0\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_age","title":"max_age class-attribute instance-attribute","text":"
max_age: Optional[float] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_bytes","title":"max_bytes class-attribute instance-attribute","text":"
max_bytes: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_consumers","title":"max_consumers class-attribute instance-attribute","text":"
max_consumers: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_msg_size","title":"max_msg_size class-attribute instance-attribute","text":"
max_msg_size: Optional[int] = -1\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_msgs","title":"max_msgs class-attribute instance-attribute","text":"
max_msgs: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_msgs_per_subject","title":"max_msgs_per_subject class-attribute instance-attribute","text":"
max_msgs_per_subject: int = -1\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.mirror","title":"mirror class-attribute instance-attribute","text":"
mirror: Optional[StreamSource] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.mirror_direct","title":"mirror_direct class-attribute instance-attribute","text":"
mirror_direct: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.no_ack","title":"no_ack class-attribute instance-attribute","text":"
no_ack: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.num_replicas","title":"num_replicas class-attribute instance-attribute","text":"
num_replicas: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.placement","title":"placement class-attribute instance-attribute","text":"
placement: Optional[Placement] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.republish","title":"republish class-attribute instance-attribute","text":"
republish: Optional[RePublish] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.retention","title":"retention class-attribute instance-attribute","text":"
retention: Optional[RetentionPolicy] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.sealed","title":"sealed class-attribute instance-attribute","text":"
sealed: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.sources","title":"sources class-attribute instance-attribute","text":"
sources: Optional[List[StreamSource]] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.storage","title":"storage class-attribute instance-attribute","text":"
storage: Optional[StorageType] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.subjects","title":"subjects class-attribute instance-attribute","text":"
subjects: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.template_owner","title":"template_owner class-attribute instance-attribute","text":"
template_owner: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n
Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    result = super().as_dict()\n    result['duplicate_window'] = self._to_nanoseconds(\n        self.duplicate_window\n    )\n    result['max_age'] = self._to_nanoseconds(self.max_age)\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any])\n
Source code in nats/js/api.py
@classmethod\ndef from_response(cls, resp: Dict[str, Any]):\n    cls._convert_nanoseconds(resp, 'max_age')\n    cls._convert_nanoseconds(resp, 'duplicate_window')\n    cls._convert(resp, 'placement', Placement)\n    cls._convert(resp, 'mirror', StreamSource)\n    cls._convert(resp, 'sources', StreamSource)\n    cls._convert(resp, 'republish', RePublish)\n    return super().from_response(resp)\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/","title":"StreamSource","text":"","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource","title":"nats.js.api.StreamSource dataclass","text":"

Bases: Base

","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.external","title":"external class-attribute instance-attribute","text":"
external: Optional[ExternalStream] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.filter_subject","title":"filter_subject class-attribute instance-attribute","text":"
filter_subject: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.opt_start_seq","title":"opt_start_seq class-attribute instance-attribute","text":"
opt_start_seq: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any])\n
Source code in nats/js/api.py
@classmethod\ndef from_response(cls, resp: Dict[str, Any]):\n    cls._convert(resp, 'external', ExternalStream)\n    return super().from_response(resp)\n
","boost":0.5},{"location":"api/faststream/nats/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/nats/TestApp/#faststream.broker.test.TestApp","title":"faststream.broker.test.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/nats/TestApp/#faststream.broker.test.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/","title":"TestNatsBroker","text":"","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker","title":"faststream.nats.TestNatsBroker","text":"
TestNatsBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[NatsBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/nats/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: NatsBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(publisher.subject, _raw=True)\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(broker: NatsBroker, publisher: Any) -> None\n
Source code in faststream/nats/test.py
@staticmethod\ndef patch_publisher(broker: NatsBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> None\n
Source code in faststream/nats/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> None:\n    broker.handlers.pop(Handler.get_routing_hash(publisher.subject), None)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/","title":"Handler","text":"","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler","title":"faststream.nats.asyncapi.Handler","text":"
Handler(\n    subject: str,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    queue: str = \"\",\n    stream: Optional[JStream] = None,\n    pull_sub: Optional[PullSub] = None,\n    extra_options: Optional[AnyDict] = None,\n    graceful_timeout: Optional[float] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n)\n

Bases: LogicNatsHandler

Source code in faststream/nats/handler.py
def __init__(\n    self,\n    subject: str,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    queue: str = \"\",\n    stream: Optional[JStream] = None,\n    pull_sub: Optional[PullSub] = None,\n    extra_options: Optional[AnyDict] = None,\n    graceful_timeout: Optional[float] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    reg, path = compile_path(subject, replace_symbol=\"*\")\n    self.subject = path\n    self.path_regex = reg\n\n    self.queue = queue\n\n    self.stream = stream\n    self.pull_sub = pull_sub\n    self.extra_options = extra_options or {}\n\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        include_in_schema=include_in_schema,\n        title=title,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.task = None\n    self.subscription = None\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.extra_options","title":"extra_options instance-attribute","text":"
extra_options = extra_options or {}\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.path_regex","title":"path_regex instance-attribute","text":"
path_regex = reg\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.pull_sub","title":"pull_sub instance-attribute","text":"
pull_sub = pull_sub\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.queue","title":"queue instance-attribute","text":"
queue = queue\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.stream","title":"stream instance-attribute","text":"
stream = stream\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.subject","title":"subject instance-attribute","text":"
subject = path\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.subscription","title":"subscription instance-attribute","text":"
subscription: Union[\n    None,\n    Subscription,\n    JetStreamContext.PushSubscription,\n    JetStreamContext.PullSubscription,\n] = None\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.task","title":"task class-attribute instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[Msg, NatsMessage]],\n    decoder: Optional[CustomDecoder[NatsMessage]],\n    filter: Filter[NatsMessage],\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ]\n) -> None\n
Source code in faststream/nats/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[Msg, NatsMessage]],\n    decoder: Optional[CustomDecoder[NatsMessage]],\n    filter: Filter[NatsMessage],\n    middlewares: Optional[Sequence[Callable[[Msg], BaseMiddleware]]],\n) -> None:\n    parser_ = Parser if self.stream is None else JsParser\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, parser_.parse_message),\n        decoder=resolve_custom_func(decoder, parser_.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/nats/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.subscription is not None:\n        await self.subscription.unsubscribe()\n        self.subscription = None\n\n    if self.task is not None:\n        self.task.cancel()\n        self.task = None\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(subject: str) -> str\n
Source code in faststream/nats/handler.py
@staticmethod\ndef get_routing_hash(subject: str) -> str:\n    return subject\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/nats/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n    handler_name = self._title or f\"{self.subject}:{self.call_name}\"\n    return {\n        handler_name: Channel(\n            description=self.description,\n            subscribe=Operation(\n                message=Message(\n                    title=f\"{handler_name}:Message\",\n                    payload=resolve_payloads(payloads),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                nats=nats.ChannelBinding(\n                    subject=self.subject,\n                    queue=self.queue or None,\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.start","title":"start async","text":"
start(connection: Union[Client, JetStreamContext]) -> None\n
Source code in faststream/nats/handler.py
@override\nasync def start(self, connection: Union[Client, JetStreamContext]) -> None:  # type: ignore[override]\n    if self.pull_sub is not None:\n        connection = cast(JetStreamContext, connection)\n\n        if self.stream is None:\n            raise ValueError(\"Pull subscriber can be used only with a stream\")\n\n        self.subscription = await connection.pull_subscribe(\n            subject=self.subject,\n            **self.extra_options,\n        )\n        self.task = asyncio.create_task(self._consume())\n\n    else:\n        self.subscription = await connection.subscribe(\n            subject=self.subject,\n            queue=self.queue,\n            cb=self.consume,  # type: ignore[arg-type]\n            **self.extra_options,\n        )\n\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/","title":"Publisher","text":"","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher","title":"faststream.nats.asyncapi.Publisher","text":"

Bases: LogicPublisher

","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.name","title":"name property","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.stream","title":"stream class-attribute instance-attribute","text":"
stream: Optional[JStream] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.subject","title":"subject class-attribute instance-attribute","text":"
subject: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: Optional[float] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.publish","title":"publish async","text":"
publish(\n    message: SendableMessage = \"\",\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[Dict[str, str]] = None,\n    **producer_kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage = \"\",\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[Dict[str, str]] = None,\n    **producer_kwargs: Any,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    assert self.subject, \"You have to specify outgoing subject\"  # nosec B101\n\n    extra: AnyDict = {\n        \"reply_to\": reply_to or self.reply_to,\n    }\n    if self.stream is not None:\n        extra.update(\n            {\n                \"stream\": self.stream.name,\n                \"timeout\": self.timeout,\n            }\n        )\n\n    return await self._producer.publish(\n        message=message,\n        subject=self.subject,\n        headers=headers or self.headers,\n        correlation_id=correlation_id,\n        **extra,\n        **producer_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/nats/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    return {\n        self.name: Channel(\n            description=self.description,\n            publish=Operation(\n                message=Message(\n                    title=f\"{self.name}:Message\",\n                    payload=resolve_payloads(payloads, \"Publisher\"),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                nats=nats.ChannelBinding(\n                    subject=self.subject,\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/","title":"NatsBroker","text":"","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker","title":"faststream.nats.broker.NatsBroker","text":"
NatsBroker(\n    servers: Union[str, Sequence[str]] = (\n        \"nats://localhost:4222\"\n    ),\n    *,\n    security: Optional[BaseSecurity] = None,\n    protocol: str = \"nats\",\n    protocol_version: Optional[str] = \"custom\",\n    **kwargs: Any\n)\n

Bases: NatsLoggingMixin, BrokerAsyncUsecase[Msg, Client]

Source code in faststream/nats/broker.py
def __init__(\n    self,\n    servers: Union[str, Sequence[str]] = (\"nats://localhost:4222\",),  # noqa: B006\n    *,\n    security: Optional[BaseSecurity] = None,\n    protocol: str = \"nats\",\n    protocol_version: Optional[str] = \"custom\",\n    **kwargs: Any,\n) -> None:\n    kwargs.update(parse_security(security))\n\n    if kwargs.get(\"tls\"):  # pragma: no cover\n        warnings.warn(\n            (\n                \"\\nNATS `tls` option was deprecated and will be removed in 0.4.0\"\n                \"\\nPlease, use `security` with `BaseSecurity` or `SASLPlaintext` instead\"\n            ),\n            DeprecationWarning,\n            stacklevel=2,\n        )\n\n    super().__init__(\n        url=([servers] if isinstance(servers, str) else list(servers)),\n        protocol=protocol,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n    )\n\n    self.__is_connected = False\n    self._producer = None\n\n    # JS options\n    self.stream = None\n    self._js_producer = None\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[Subject, Handler]\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.stream","title":"stream instance-attribute","text":"
stream: Optional[JetStreamContext] = None\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.url","title":"url instance-attribute","text":"
url: List[str]\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.connect","title":"connect async","text":"
connect(*args: Any, **kwargs: Any) -> Client\n
Source code in faststream/nats/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Client:\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        self.__set_publisher_producer(p)\n    return connection\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, stream: Optional[str] = None, **kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    stream: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[DecodedMessage]:\n    if stream is None:\n        assert self._producer, NOT_CONNECTED_YET  # nosec B101\n        return await self._producer.publish(*args, **kwargs)\n    else:\n        assert self._js_producer, NOT_CONNECTED_YET  # nosec B101\n        return await self._js_producer.publish(\n            *args,\n            stream=stream,\n            **kwargs,  # type: ignore[misc]\n        )\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.publisher","title":"publisher","text":"
publisher(\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    stream: Union[str, JStream, None] = None,\n    timeout: Optional[float] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/nats/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    # Core\n    reply_to: str = \"\",\n    # JS\n    stream: Union[str, JStream, None] = None,\n    timeout: Optional[float] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    if (stream := stream_builder.stream(stream)) is not None:\n        stream.subjects.append(subject)\n\n    publisher = self._publishers.get(\n        subject,\n        Publisher(\n            subject=subject,\n            headers=headers,\n            # Core\n            reply_to=reply_to,\n            # JS\n            timeout=timeout,\n            stream=stream,\n            # AsyncAPI\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(subject, publisher)\n    self.__set_publisher_producer(publisher)\n    return publisher\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.start","title":"start async","text":"
start() -> None\n
Source code in faststream/nats/broker.py
async def start(self) -> None:\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n    assert (\n        self._connection and self.stream\n    ), \"Broker should be started already\"  # nosec B101\n\n    for handler in self.handlers.values():\n        stream = handler.stream\n\n        if (is_js := stream is not None) and stream.declare:\n            try:  # pragma: no branch\n                await self.stream.add_stream(\n                    config=stream.config,\n                    subjects=stream.subjects,\n                )\n\n            except nats.js.errors.BadRequestError as e:\n                old_config = (await self.stream.stream_info(stream.name)).config\n\n                c = self._get_log_context(None, \"\")\n                if (\n                    e.description\n                    == \"stream name already in use with a different configuration\"\n                ):\n                    self._log(str(e), logging.WARNING, c)\n                    await self.stream.update_stream(\n                        config=stream.config,\n                        subjects=tuple(\n                            set(old_config.subjects or ()).union(stream.subjects)\n                        ),\n                    )\n\n                else:  # pragma: no cover\n                    self._log(str(e), logging.ERROR, c, exc_info=e)\n\n            finally:\n                # prevent from double declaration\n                stream.declare = False\n\n        c = self._get_log_context(\n            None,\n            subject=handler.subject,\n            queue=handler.queue,\n            stream=stream.name if stream else \"\",\n        )\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self.stream if is_js else self._connection)\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/nats/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    # Core arguments\n    max_msgs: int = 0,\n    # JS arguments\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    # pull arguments\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    # custom\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[Sequence[Callable[[Msg], BaseMiddleware]]] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],\n]:\n    stream = stream_builder.stream(stream)\n\n    if pull_sub is not None and stream is None:\n        raise ValueError(\"Pull subscriber can be used only with a stream\")\n\n    self._setup_log_context(\n        queue=queue,\n        subject=subject,\n        stream=stream.name if stream else None,\n    )\n    super().subscriber()\n\n    extra_options: AnyDict = {\n        \"pending_msgs_limit\": pending_msgs_limit\n        or (\n            DEFAULT_JS_SUB_PENDING_MSGS_LIMIT\n            if stream\n            else DEFAULT_SUB_PENDING_MSGS_LIMIT\n        ),\n        \"pending_bytes_limit\": pending_bytes_limit\n        or (\n            DEFAULT_JS_SUB_PENDING_BYTES_LIMIT\n            if stream\n            else DEFAULT_SUB_PENDING_BYTES_LIMIT\n        ),\n    }\n\n    if stream:\n        extra_options.update(\n            {\n                \"durable\": durable,\n                \"stream\": stream.name,\n                \"config\": config,\n            }\n        )\n\n        if pull_sub is not None:\n            extra_options.update({\"inbox_prefix\": inbox_prefix})\n\n        else:\n            extra_options.update(\n                {\n                    \"ordered_consumer\": ordered_consumer,\n                    \"idle_heartbeat\": idle_heartbeat,\n                    \"flow_control\": flow_control,\n                    \"deliver_policy\": deliver_policy,\n                    \"headers_only\": headers_only,\n                    \"manual_ack\": not ack_first,\n                }\n            )\n\n    else:\n        extra_options.update(\n            {\n                \"max_msgs\": max_msgs,\n            }\n        )\n\n    key = Handler.get_routing_hash(subject)\n    handler = self.handlers[key] = self.handlers.get(\n        key,\n        Handler(\n            subject=subject,\n            queue=queue,\n            stream=stream,\n            pull_sub=pull_sub,\n            extra_options=extra_options,\n            title=title,\n            description=description,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n            log_context_builder=partial(\n                self._get_log_context,\n                stream=stream.name if stream else \"\",\n                subject=subject,\n                queue=queue,\n            ),\n        ),\n    )\n\n    if stream:\n        stream.subjects.append(handler.subject)\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn,]:\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/nats/fastapi/Context/#faststream.broker.fastapi.context.Context","title":"faststream.broker.fastapi.context.Context","text":"
Context(name: str) -> Any\n
Source code in faststream/broker/fastapi/context.py
def Context(name: str) -> Any:\n    return params.Depends(\n        lambda: context.resolve(name),\n        use_cache=True,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/","title":"NatsRouter","text":"","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter","title":"faststream.nats.fastapi.NatsRouter","text":"
NatsRouter(\n    servers: Union[str, Sequence[str]] = (\n        \"nats://localhost:4222\"\n    ),\n    *,\n    error_cb: Optional[ErrorCallback] = None,\n    disconnected_cb: Optional[Callback] = None,\n    closed_cb: Optional[Callback] = None,\n    discovered_server_cb: Optional[Callback] = None,\n    reconnected_cb: Optional[Callback] = None,\n    name: Optional[str] = None,\n    pedantic: bool = False,\n    verbose: bool = False,\n    allow_reconnect: bool = True,\n    connect_timeout: int = DEFAULT_CONNECT_TIMEOUT,\n    reconnect_time_wait: int = DEFAULT_RECONNECT_TIME_WAIT,\n    max_reconnect_attempts: int = DEFAULT_MAX_RECONNECT_ATTEMPTS,\n    ping_interval: int = DEFAULT_PING_INTERVAL,\n    max_outstanding_pings: int = DEFAULT_MAX_OUTSTANDING_PINGS,\n    dont_randomize: bool = False,\n    flusher_queue_size: int = DEFAULT_MAX_FLUSHER_QUEUE_SIZE,\n    no_echo: bool = False,\n    tls: Optional[ssl.SSLContext] = None,\n    tls_hostname: Optional[str] = None,\n    user: Optional[str] = None,\n    password: Optional[str] = None,\n    token: Optional[str] = None,\n    drain_timeout: int = DEFAULT_DRAIN_TIMEOUT,\n    signature_cb: Optional[SignatureCallback] = None,\n    user_jwt_cb: Optional[JWTCallback] = None,\n    user_credentials: Optional[Credentials] = None,\n    nkeys_seed: Optional[str] = None,\n    inbox_prefix: Union[str, bytes] = DEFAULT_INBOX_PREFIX,\n    pending_size: int = DEFAULT_PENDING_SIZE,\n    flush_timeout: Optional[float] = None,\n    graceful_timeout: Optional[float] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    asyncapi_url: Union[str, List[str], None] = None,\n    protocol: str = \"nats\",\n    protocol_version: Optional[str] = \"0.9.1\",\n    description: Optional[str] = None,\n    asyncapi_tags: Optional[Sequence[asyncapi.Tag]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    setup_state: bool = True,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n)\n

Bases: StreamRouter[Msg]

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.broker","title":"broker instance-attribute","text":"
broker: NatsBroker\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.broker_class","title":"broker_class class-attribute instance-attribute","text":"
broker_class = NB\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    subject: str,\n    *,\n    endpoint: Callable[..., T_HandlerReturn],\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    retry: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    **__service_kwargs: Any\n) -> Callable[[Msg, bool], Awaitable[T_HandlerReturn]]\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.publisher","title":"publisher","text":"
publisher(\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    stream: Union[str, JStream, None] = None,\n    timeout: Optional[float] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    retry: bool = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/","title":"LogicNatsHandler","text":"","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler","title":"faststream.nats.handler.LogicNatsHandler","text":"
LogicNatsHandler(\n    subject: str,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    queue: str = \"\",\n    stream: Optional[JStream] = None,\n    pull_sub: Optional[PullSub] = None,\n    extra_options: Optional[AnyDict] = None,\n    graceful_timeout: Optional[float] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n)\n

Bases: AsyncHandler[Msg]

Source code in faststream/nats/handler.py
def __init__(\n    self,\n    subject: str,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    queue: str = \"\",\n    stream: Optional[JStream] = None,\n    pull_sub: Optional[PullSub] = None,\n    extra_options: Optional[AnyDict] = None,\n    graceful_timeout: Optional[float] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    reg, path = compile_path(subject, replace_symbol=\"*\")\n    self.subject = path\n    self.path_regex = reg\n\n    self.queue = queue\n\n    self.stream = stream\n    self.pull_sub = pull_sub\n    self.extra_options = extra_options or {}\n\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        include_in_schema=include_in_schema,\n        title=title,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.task = None\n    self.subscription = None\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.extra_options","title":"extra_options instance-attribute","text":"
extra_options = extra_options or {}\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.path_regex","title":"path_regex instance-attribute","text":"
path_regex = reg\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.pull_sub","title":"pull_sub instance-attribute","text":"
pull_sub = pull_sub\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.queue","title":"queue instance-attribute","text":"
queue = queue\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.stream","title":"stream instance-attribute","text":"
stream = stream\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.subject","title":"subject instance-attribute","text":"
subject = path\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.subscription","title":"subscription instance-attribute","text":"
subscription: Union[\n    None,\n    Subscription,\n    JetStreamContext.PushSubscription,\n    JetStreamContext.PullSubscription,\n] = None\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.task","title":"task class-attribute instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[Msg, NatsMessage]],\n    decoder: Optional[CustomDecoder[NatsMessage]],\n    filter: Filter[NatsMessage],\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ]\n) -> None\n
Source code in faststream/nats/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[Msg, NatsMessage]],\n    decoder: Optional[CustomDecoder[NatsMessage]],\n    filter: Filter[NatsMessage],\n    middlewares: Optional[Sequence[Callable[[Msg], BaseMiddleware]]],\n) -> None:\n    parser_ = Parser if self.stream is None else JsParser\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, parser_.parse_message),\n        decoder=resolve_custom_func(decoder, parser_.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/nats/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.subscription is not None:\n        await self.subscription.unsubscribe()\n        self.subscription = None\n\n    if self.task is not None:\n        self.task.cancel()\n        self.task = None\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(subject: str) -> str\n
Source code in faststream/nats/handler.py
@staticmethod\ndef get_routing_hash(subject: str) -> str:\n    return subject\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.start","title":"start async","text":"
start(connection: Union[Client, JetStreamContext]) -> None\n
Source code in faststream/nats/handler.py
@override\nasync def start(self, connection: Union[Client, JetStreamContext]) -> None:  # type: ignore[override]\n    if self.pull_sub is not None:\n        connection = cast(JetStreamContext, connection)\n\n        if self.stream is None:\n            raise ValueError(\"Pull subscriber can be used only with a stream\")\n\n        self.subscription = await connection.pull_subscribe(\n            subject=self.subject,\n            **self.extra_options,\n        )\n        self.task = asyncio.create_task(self._consume())\n\n    else:\n        self.subscription = await connection.subscribe(\n            subject=self.subject,\n            queue=self.queue,\n            cb=self.consume,  # type: ignore[arg-type]\n            **self.extra_options,\n        )\n\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/nats/helpers/StreamBuilder/","title":"StreamBuilder","text":"","boost":0.5},{"location":"api/faststream/nats/helpers/StreamBuilder/#faststream.nats.helpers.StreamBuilder","title":"faststream.nats.helpers.StreamBuilder","text":"
StreamBuilder()\n
Source code in faststream/nats/helpers.py
def __init__(self) -> None:\n    self.streams = {}\n
","boost":0.5},{"location":"api/faststream/nats/helpers/StreamBuilder/#faststream.nats.helpers.StreamBuilder.streams","title":"streams instance-attribute","text":"
streams: Dict[str, JStream] = {}\n
","boost":0.5},{"location":"api/faststream/nats/helpers/StreamBuilder/#faststream.nats.helpers.StreamBuilder.stream","title":"stream","text":"
stream(\n    name: Union[str, JStream, None],\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any\n) -> Optional[JStream]\n
Source code in faststream/nats/helpers.py
def stream(\n    self,\n    name: Union[str, JStream, None],\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any,\n) -> Optional[JStream]:\n    stream = JStream.validate(name)\n\n    if stream is not None:\n        stream = self.streams[stream.name] = self.streams.get(stream.name, stream)\n\n    return stream\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/DiscardPolicy/","title":"DiscardPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/DiscardPolicy/#nats.js.api.DiscardPolicy","title":"nats.js.api.DiscardPolicy","text":"

Bases: str, Enum

Discard policy when a stream reaches its limits

","boost":0.5},{"location":"api/faststream/nats/js_stream/DiscardPolicy/#nats.js.api.DiscardPolicy.NEW","title":"NEW class-attribute instance-attribute","text":"
NEW = 'new'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/DiscardPolicy/#nats.js.api.DiscardPolicy.OLD","title":"OLD class-attribute instance-attribute","text":"
OLD = 'old'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/","title":"ExternalStream","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream","title":"nats.js.api.ExternalStream dataclass","text":"

Bases: Base

","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream.api","title":"api instance-attribute","text":"
api: str\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream.deliver","title":"deliver class-attribute instance-attribute","text":"
deliver: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/","title":"JStream","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream","title":"faststream.nats.js_stream.JStream","text":"
JStream(\n    name: str,\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any\n)\n

Bases: NameRequired

Source code in faststream/nats/js_stream.py
def __init__(\n    self,\n    name: str,\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any,\n) -> None:\n    super().__init__(\n        name=name,\n        declare=declare,\n        subjects=[],\n        config=StreamConfig(\n            *args,\n            name=name,\n            **kwargs,  # type: ignore[misc]\n        ),\n    )\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream.config","title":"config instance-attribute","text":"
config: StreamConfig\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream.declare","title":"declare class-attribute instance-attribute","text":"
declare: bool = Field(default=True)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream.subjects","title":"subjects class-attribute instance-attribute","text":"
subjects: List[str] = Field(default_factory=list)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/","title":"Placement","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement","title":"nats.js.api.Placement dataclass","text":"

Bases: Base

Placement directives to consider when placing replicas of this stream

","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement.cluster","title":"cluster class-attribute instance-attribute","text":"
cluster: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/","title":"RePublish","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish","title":"nats.js.api.RePublish dataclass","text":"

Bases: Base

RePublish is for republishing messages once committed to a stream. The original subject cis remapped from the subject pattern to the destination pattern.

","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.dest","title":"dest class-attribute instance-attribute","text":"
dest: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.headers_only","title":"headers_only class-attribute instance-attribute","text":"
headers_only: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.src","title":"src class-attribute instance-attribute","text":"
src: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RetentionPolicy/","title":"RetentionPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/RetentionPolicy/#nats.js.api.RetentionPolicy","title":"nats.js.api.RetentionPolicy","text":"

Bases: str, Enum

How message retention is considered

","boost":0.5},{"location":"api/faststream/nats/js_stream/RetentionPolicy/#nats.js.api.RetentionPolicy.INTEREST","title":"INTEREST class-attribute instance-attribute","text":"
INTEREST = 'interest'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RetentionPolicy/#nats.js.api.RetentionPolicy.LIMITS","title":"LIMITS class-attribute instance-attribute","text":"
LIMITS = 'limits'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RetentionPolicy/#nats.js.api.RetentionPolicy.WORK_QUEUE","title":"WORK_QUEUE class-attribute instance-attribute","text":"
WORK_QUEUE = 'workqueue'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StorageType/","title":"StorageType","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/StorageType/#nats.js.api.StorageType","title":"nats.js.api.StorageType","text":"

Bases: str, Enum

The type of storage backend

","boost":0.5},{"location":"api/faststream/nats/js_stream/StorageType/#nats.js.api.StorageType.FILE","title":"FILE class-attribute instance-attribute","text":"
FILE = 'file'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StorageType/#nats.js.api.StorageType.MEMORY","title":"MEMORY class-attribute instance-attribute","text":"
MEMORY = 'memory'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/","title":"StreamSource","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource","title":"nats.js.api.StreamSource dataclass","text":"

Bases: Base

","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.external","title":"external class-attribute instance-attribute","text":"
external: Optional[ExternalStream] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.filter_subject","title":"filter_subject class-attribute instance-attribute","text":"
filter_subject: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.opt_start_seq","title":"opt_start_seq class-attribute instance-attribute","text":"
opt_start_seq: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any])\n
Source code in nats/js/api.py
@classmethod\ndef from_response(cls, resp: Dict[str, Any]):\n    cls._convert(resp, 'external', ExternalStream)\n    return super().from_response(resp)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/","title":"NatsMessage","text":"","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage","title":"faststream.nats.message.NatsMessage dataclass","text":"

Bases: StreamMessage[Msg]

","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.is_js","title":"is_js class-attribute instance-attribute","text":"
is_js: bool = True\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.ack","title":"ack async","text":"
ack(**kwargs: Any) -> None\n
Source code in faststream/nats/message.py
async def ack(self, **kwargs: Any) -> None:\n    await super().ack()\n    if self.is_js:\n        if not isinstance(self.raw_message, list):\n            if not self.raw_message._ackd:\n                await self.raw_message.ack()\n\n        else:\n            for m in filter(\n                lambda m: not m._ackd,\n                self.raw_message,\n            ):\n                await m.ack()\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.in_progress","title":"in_progress async","text":"
in_progress(**kwargs: Any) -> None\n
Source code in faststream/nats/message.py
async def in_progress(self, **kwargs: Any) -> None:\n    if self.is_js:\n        if not isinstance(self.raw_message, list):\n            if not self.raw_message._ackd:\n                await self.raw_message.in_progress()\n\n        else:\n            for m in filter(\n                lambda m: not m._ackd,\n                self.raw_message,\n            ):\n                await m.in_progress()\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.nack","title":"nack async","text":"
nack(**kwargs: Any) -> None\n
Source code in faststream/nats/message.py
async def nack(self, **kwargs: Any) -> None:\n    await super().nack()\n    if self.is_js:\n        if not isinstance(self.raw_message, list):\n            if not self.raw_message._ackd:\n                await self.raw_message.nak(**kwargs)\n\n        else:\n            for m in filter(\n                lambda m: not m._ackd,\n                self.raw_message,\n            ):\n                await m.nak(**kwargs)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.reject","title":"reject async","text":"
reject(**kwargs: Any) -> None\n
Source code in faststream/nats/message.py
async def reject(self, **kwargs: Any) -> None:\n    await super().reject()\n    if self.is_js:\n        if not isinstance(self.raw_message, list):\n            if not self.raw_message._ackd:\n                await self.raw_message.term()\n\n        else:\n            for m in filter(\n                lambda m: not m._ackd,\n                self.raw_message,\n            ):\n                await m.term()\n
","boost":0.5},{"location":"api/faststream/nats/parser/NatsParser/","title":"NatsParser","text":"","boost":0.5},{"location":"api/faststream/nats/parser/NatsParser/#faststream.nats.parser.NatsParser","title":"faststream.nats.parser.NatsParser","text":"
NatsParser(is_js: bool)\n
Source code in faststream/nats/parser.py
def __init__(self, is_js: bool) -> None:\n    self.is_js = is_js\n
","boost":0.5},{"location":"api/faststream/nats/parser/NatsParser/#faststream.nats.parser.NatsParser.is_js","title":"is_js instance-attribute","text":"
is_js = is_js\n
","boost":0.5},{"location":"api/faststream/nats/parser/NatsParser/#faststream.nats.parser.NatsParser.decode_message","title":"decode_message async","text":"
decode_message(\n    msg: Union[StreamMessage[Msg], StreamMessage[List[Msg]]]\n) -> DecodedMessage\n
Source code in faststream/nats/parser.py
async def decode_message(\n    self,\n    msg: Union[\n        StreamMessage[Msg],\n        StreamMessage[List[Msg]],\n    ],\n) -> DecodedMessage:\n    if isinstance(msg.raw_message, list):\n        data = []\n\n        path: Optional[AnyDict] = None\n        for m in msg.raw_message:\n            msg = await self.parse_message(m, path=path)\n            path = msg.path\n\n            data.append(decode_message(msg))\n\n        return data\n\n    else:\n        return decode_message(msg)\n
","boost":0.5},{"location":"api/faststream/nats/parser/NatsParser/#faststream.nats.parser.NatsParser.parse_message","title":"parse_message async","text":"
parse_message(\n    message: Union[Msg, List[Msg]],\n    *,\n    path: Optional[AnyDict] = None\n) -> Union[StreamMessage[Msg], StreamMessage[List[Msg]]]\n
Source code in faststream/nats/parser.py
async def parse_message(\n    self, message: Union[Msg, List[Msg]], *, path: Optional[AnyDict] = None\n) -> Union[StreamMessage[Msg], StreamMessage[List[Msg]],]:\n    if isinstance(message, list):\n        return NatsMessage(\n            is_js=self.is_js,\n            raw_message=message,  # type: ignore[arg-type]\n            body=[m.data for m in message],\n        )\n\n    else:\n        path_re: Optional[Pattern[str]]\n        if (\n            path is None\n            and (handler := context.get_local(\"handler_\"))\n            and (path_re := handler.path_regex) is not None\n            and (match := path_re.match(message.subject)) is not None\n        ):\n            path = match.groupdict()\n\n        headers = message.header or {}\n\n        return NatsMessage(\n            is_js=self.is_js,\n            raw_message=message,\n            body=message.data,\n            path=path or {},\n            reply_to=headers.get(\"reply_to\", \"\") if self.is_js else message.reply,\n            headers=headers,\n            content_type=headers.get(\"content-type\", \"\"),\n            message_id=headers.get(\"message_id\", str(uuid4())),\n            correlation_id=headers.get(\"correlation_id\", str(uuid4())),\n        )\n
","boost":0.5},{"location":"api/faststream/nats/producer/NatsFastProducer/","title":"NatsFastProducer","text":"","boost":0.5},{"location":"api/faststream/nats/producer/NatsFastProducer/#faststream.nats.producer.NatsFastProducer","title":"faststream.nats.producer.NatsFastProducer","text":"
NatsFastProducer(\n    connection: Client,\n    parser: Optional[AsyncCustomParser[Msg, NatsMessage]],\n    decoder: Optional[AsyncCustomDecoder[NatsMessage]],\n)\n
Source code in faststream/nats/producer.py
def __init__(\n    self,\n    connection: Client,\n    parser: Optional[AsyncCustomParser[Msg, NatsMessage]],\n    decoder: Optional[AsyncCustomDecoder[NatsMessage]],\n) -> None:\n    self._connection = connection\n    self._parser = resolve_custom_func(parser, Parser.parse_message)\n    self._decoder = resolve_custom_func(decoder, Parser.decode_message)\n
","boost":0.5},{"location":"api/faststream/nats/producer/NatsFastProducer/#faststream.nats.producer.NatsFastProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    subject: str,\n    reply_to: str = \"\",\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/producer.py
async def publish(\n    self,\n    message: SendableMessage,\n    subject: str,\n    reply_to: str = \"\",\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    payload, content_type = encode_message(message)\n\n    headers_to_send = {\n        \"content-type\": content_type or \"\",\n        \"correlation_id\": correlation_id or str(uuid4()),\n        **(headers or {}),\n    }\n\n    client = self._connection\n\n    if rpc:\n        if reply_to:\n            raise WRONG_PUBLISH_ARGS\n\n        token = client._nuid.next()\n        token.extend(token_hex(2).encode())\n        reply_to = token.decode()\n\n        future: asyncio.Future[Msg] = asyncio.Future()\n        sub = await client.subscribe(reply_to, future=future, max_msgs=1)\n        await sub.unsubscribe(limit=1)\n\n    await client.publish(\n        subject=subject,\n        payload=payload,\n        reply=reply_to,\n        headers=headers_to_send,\n    )\n\n    if rpc:\n        msg: Any = None\n        with timeout_scope(rpc_timeout, raise_timeout):\n            msg = await future\n\n        if msg:  # pragma: no branch\n            if msg.headers:  # pragma: no cover\n                if (\n                    msg.headers.get(nats.js.api.Header.STATUS)\n                    == nats.aio.client.NO_RESPONDERS_STATUS\n                ):\n                    raise nats.errors.NoRespondersError\n            return await self._decoder(await self._parser(msg))\n\n    return None\n
","boost":0.5},{"location":"api/faststream/nats/producer/NatsJSFastProducer/","title":"NatsJSFastProducer","text":"","boost":0.5},{"location":"api/faststream/nats/producer/NatsJSFastProducer/#faststream.nats.producer.NatsJSFastProducer","title":"faststream.nats.producer.NatsJSFastProducer","text":"
NatsJSFastProducer(\n    connection: JetStreamContext,\n    parser: Optional[AsyncCustomParser[Msg, NatsMessage]],\n    decoder: Optional[AsyncCustomDecoder[NatsMessage]],\n)\n
Source code in faststream/nats/producer.py
def __init__(\n    self,\n    connection: JetStreamContext,\n    parser: Optional[AsyncCustomParser[Msg, NatsMessage]],\n    decoder: Optional[AsyncCustomDecoder[NatsMessage]],\n) -> None:\n    self._connection = connection\n    self._parser = resolve_custom_func(parser, Parser.parse_message)\n    self._decoder = resolve_custom_func(decoder, Parser.decode_message)\n
","boost":0.5},{"location":"api/faststream/nats/producer/NatsJSFastProducer/#faststream.nats.producer.NatsJSFastProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    stream: Optional[str] = None,\n    timeout: Optional[float] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/producer.py
async def publish(\n    self,\n    message: SendableMessage,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    stream: Optional[str] = None,\n    timeout: Optional[float] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    payload, content_type = encode_message(message)\n\n    headers_to_send = {\n        \"content-type\": content_type or \"\",\n        \"correlation_id\": correlation_id or str(uuid4()),\n        **(headers or {}),\n    }\n\n    if rpc:\n        if reply_to:\n            raise WRONG_PUBLISH_ARGS\n\n        reply_to = str(uuid4())\n        future: asyncio.Future[Msg] = asyncio.Future()\n        sub = await self._connection._nc.subscribe(\n            reply_to, future=future, max_msgs=1\n        )\n        await sub.unsubscribe(limit=1)\n\n    if reply_to:\n        headers_to_send.update({\"reply_to\": reply_to})\n\n    await self._connection.publish(\n        subject=subject,\n        payload=payload,\n        headers=headers_to_send,\n        stream=stream,\n        timeout=timeout,\n    )\n\n    if rpc:\n        msg: Any = None\n        with timeout_scope(rpc_timeout, raise_timeout):\n            msg = await future\n\n        if msg:  # pragma: no branch\n            if msg.headers:  # pragma: no cover\n                if (\n                    msg.headers.get(nats.js.api.Header.STATUS)\n                    == nats.aio.client.NO_RESPONDERS_STATUS\n                ):\n                    raise nats.errors.NoRespondersError\n            return await self._decoder(await self._parser(msg))\n\n    return None\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/","title":"LogicPublisher","text":"","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher","title":"faststream.nats.publisher.LogicPublisher dataclass","text":"

Bases: BasePublisher[Msg]

","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.stream","title":"stream class-attribute instance-attribute","text":"
stream: Optional[JStream] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.subject","title":"subject class-attribute instance-attribute","text":"
subject: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: Optional[float] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.publish","title":"publish async","text":"
publish(\n    message: SendableMessage = \"\",\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[Dict[str, str]] = None,\n    **producer_kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage = \"\",\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[Dict[str, str]] = None,\n    **producer_kwargs: Any,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    assert self.subject, \"You have to specify outgoing subject\"  # nosec B101\n\n    extra: AnyDict = {\n        \"reply_to\": reply_to or self.reply_to,\n    }\n    if self.stream is not None:\n        extra.update(\n            {\n                \"stream\": self.stream.name,\n                \"timeout\": self.timeout,\n            }\n        )\n\n    return await self._producer.publish(\n        message=message,\n        subject=self.subject,\n        headers=headers or self.headers,\n        correlation_id=correlation_id,\n        **extra,\n        **producer_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/nats/pull_sub/PullSub/","title":"PullSub","text":"","boost":0.5},{"location":"api/faststream/nats/pull_sub/PullSub/#faststream.nats.pull_sub.PullSub","title":"faststream.nats.pull_sub.PullSub","text":"
PullSub(\n    batch_size: int = 1,\n    timeout: Optional[float] = 5.0,\n    batch: bool = False,\n)\n

Bases: BaseModel

Source code in faststream/nats/pull_sub.py
def __init__(\n    self,\n    batch_size: int = 1,\n    timeout: Optional[float] = 5.0,\n    batch: bool = False,\n) -> None:\n    super().__init__(\n        batch_size=batch_size,\n        timeout=timeout,\n        batch=batch,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/pull_sub/PullSub/#faststream.nats.pull_sub.PullSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = Field(default=False)\n
","boost":0.5},{"location":"api/faststream/nats/pull_sub/PullSub/#faststream.nats.pull_sub.PullSub.batch_size","title":"batch_size class-attribute instance-attribute","text":"
batch_size: int = Field(default=1)\n
","boost":0.5},{"location":"api/faststream/nats/pull_sub/PullSub/#faststream.nats.pull_sub.PullSub.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: Optional[float] = Field(default=5.0)\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/","title":"NatsRouter","text":"","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter","title":"faststream.nats.router.NatsRouter","text":"
NatsRouter(\n    prefix: str = \"\",\n    handlers: Sequence[NatsRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: NatsRouter

Source code in faststream/nats/router.py
    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.publisher","title":"publisher","text":"
publisher(\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/nats/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            subject=subject,\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    retry: bool = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
","boost":0.5},{"location":"api/faststream/nats/security/parse_security/","title":"parse_security","text":"","boost":0.5},{"location":"api/faststream/nats/security/parse_security/#faststream.nats.security.parse_security","title":"faststream.nats.security.parse_security","text":"
parse_security(security: Optional[BaseSecurity]) -> AnyDict\n
Source code in faststream/nats/security.py
def parse_security(security: Optional[BaseSecurity]) -> AnyDict:\n    if security is None:\n        return {}\n    elif isinstance(security, SASLPlaintext):\n        return _parse_sasl_plaintext(security)\n    elif isinstance(security, BaseSecurity):\n        return _parse_base_security(security)\n    else:\n        raise NotImplementedError(f\"NatsBroker does not support {type(security)}\")\n
","boost":0.5},{"location":"api/faststream/nats/shared/logging/NatsLoggingMixin/","title":"NatsLoggingMixin","text":"","boost":0.5},{"location":"api/faststream/nats/shared/logging/NatsLoggingMixin/#faststream.nats.shared.logging.NatsLoggingMixin","title":"faststream.nats.shared.logging.NatsLoggingMixin","text":"
NatsLoggingMixin(\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any\n)\n

Bases: LoggingMixin

Source code in faststream/nats/shared/logging.py
def __init__(\n    self,\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any,\n) -> None:\n    super().__init__(\n        *args,\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n        **kwargs,\n    )\n    self._max_queue_len = 0\n    self._max_stream_len = 0\n    self._max_subject_len = 4\n
","boost":0.5},{"location":"api/faststream/nats/shared/logging/NatsLoggingMixin/#faststream.nats.shared.logging.NatsLoggingMixin.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/nats/shared/logging/NatsLoggingMixin/#faststream.nats.shared.logging.NatsLoggingMixin.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/nats/shared/logging/NatsLoggingMixin/#faststream.nats.shared.logging.NatsLoggingMixin.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRoute/","title":"NatsRoute","text":"","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/","title":"NatsRouter","text":"","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter","title":"faststream.nats.shared.router.NatsRouter","text":"
NatsRouter(\n    prefix: str = \"\",\n    handlers: Sequence[NatsRoute] = (),\n    **kwargs: Any\n)\n

Bases: BrokerRouter[str, Msg]

Source code in faststream/nats/shared/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[NatsRoute[Msg, SendableMessage]] = (),\n    **kwargs: Any,\n) -> None:\n    for h in handlers:\n        if not (subj := h.kwargs.pop(\"subject\", None)):\n            subj, h.args = h.args[0], h.args[1:]\n        h.args = (prefix + subj, *h.args)\n    super().__init__(prefix, handlers, **kwargs)\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str, **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/nats/shared/router.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    subject: str,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],\n]:\n    return self._wrap_subscriber(\n        self.prefix + subject,\n        **broker_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/test/FakeProducer/","title":"FakeProducer","text":"","boost":0.5},{"location":"api/faststream/nats/test/FakeProducer/#faststream.nats.test.FakeProducer","title":"faststream.nats.test.FakeProducer","text":"
FakeProducer(broker: NatsBroker)\n

Bases: NatsFastProducer

Source code in faststream/nats/test.py
def __init__(self, broker: NatsBroker) -> None:\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/nats/test/FakeProducer/#faststream.nats.test.FakeProducer.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/nats/test/FakeProducer/#faststream.nats.test.FakeProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    subject: str,\n    reply_to: str = \"\",\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    timeout: Optional[float] = None,\n    stream: Optional[str] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False\n) -> Optional[SendableMessage]\n
Source code in faststream/nats/test.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage,\n    subject: str,\n    reply_to: str = \"\",\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    # NatsJSFastProducer compatibility\n    timeout: Optional[float] = None,\n    stream: Optional[str] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False,\n) -> Optional[SendableMessage]:\n    incoming = build_message(\n        message=message,\n        subject=subject,\n        headers=headers,\n        correlation_id=correlation_id,\n        reply_to=reply_to,\n    )\n\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        call = False\n\n        if stream and getattr(handler.stream, \"name\", None) != stream:\n            continue\n\n        if subject == handler.subject:\n            call = True\n\n        else:\n            call = True\n\n            for current, base in zip_longest(\n                subject.split(\".\"),\n                handler.subject.split(\".\"),\n                fillvalue=None,\n            ):\n                if base == \">\":\n                    break\n\n                if base != \"*\" and current != base:\n                    call = False\n                    break\n\n        if call:\n            r = await call_handler(\n                handler=handler,\n                message=[incoming]\n                if getattr(handler.pull_sub, \"batch\", False)\n                else incoming,\n                rpc=rpc,\n                rpc_timeout=rpc_timeout,\n                raise_timeout=raise_timeout,\n            )\n\n            if rpc:\n                return r\n\n    return None\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/","title":"PatchedMessage","text":"","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage","title":"faststream.nats.test.PatchedMessage","text":"

Bases: Msg

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.data","title":"data class-attribute instance-attribute","text":"
data: bytes = b''\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.header","title":"header property","text":"
header: Optional[Dict[str, str]]\n

header returns the headers from a message.

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = None\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.metadata","title":"metadata property","text":"
metadata: Metadata\n

metadata returns the Metadata of a JetStream message.

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.reply","title":"reply class-attribute instance-attribute","text":"
reply: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.sid","title":"sid property","text":"
sid: int\n

sid returns the subscription ID from a message.

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.subject","title":"subject class-attribute instance-attribute","text":"
subject: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack","title":"Ack","text":"","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.AccHash","title":"AccHash class-attribute instance-attribute","text":"
AccHash = 3\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Ack","title":"Ack class-attribute instance-attribute","text":"
Ack = b'+ACK'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Consumer","title":"Consumer class-attribute instance-attribute","text":"
Consumer = 5\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.ConsumerSeq","title":"ConsumerSeq class-attribute instance-attribute","text":"
ConsumerSeq = 8\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Domain","title":"Domain class-attribute instance-attribute","text":"
Domain = 2\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Nak","title":"Nak class-attribute instance-attribute","text":"
Nak = b'-NAK'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.NumDelivered","title":"NumDelivered class-attribute instance-attribute","text":"
NumDelivered = 6\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.NumPending","title":"NumPending class-attribute instance-attribute","text":"
NumPending = 10\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Prefix0","title":"Prefix0 class-attribute instance-attribute","text":"
Prefix0 = '$JS'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Prefix1","title":"Prefix1 class-attribute instance-attribute","text":"
Prefix1 = 'ACK'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Progress","title":"Progress class-attribute instance-attribute","text":"
Progress = b'+WPI'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Stream","title":"Stream class-attribute instance-attribute","text":"
Stream = 4\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.StreamSeq","title":"StreamSeq class-attribute instance-attribute","text":"
StreamSeq = 7\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Term","title":"Term class-attribute instance-attribute","text":"
Term = b'+TERM'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Timestamp","title":"Timestamp class-attribute instance-attribute","text":"
Timestamp = 9\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata","title":"Metadata dataclass","text":"

Metadata is the metadata from a JetStream message.

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.consumer","title":"consumer instance-attribute","text":"
consumer: str\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.domain","title":"domain class-attribute instance-attribute","text":"
domain: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.num_delivered","title":"num_delivered instance-attribute","text":"
num_delivered: int\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.num_pending","title":"num_pending instance-attribute","text":"
num_pending: int\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.sequence","title":"sequence instance-attribute","text":"
sequence: SequencePair\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.stream","title":"stream instance-attribute","text":"
stream: str\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.timestamp","title":"timestamp instance-attribute","text":"
timestamp: datetime.datetime\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.SequencePair","title":"SequencePair dataclass","text":"

SequencePair represents a pair of consumer and stream sequence.

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.SequencePair.consumer","title":"consumer instance-attribute","text":"
consumer: int\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.SequencePair.stream","title":"stream instance-attribute","text":"
stream: int\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.ack","title":"ack async","text":"
ack() -> None\n
Source code in faststream/nats/test.py
async def ack(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.ack_sync","title":"ack_sync async","text":"
ack_sync(timeout: float = 1) -> PatchedMessage\n
Source code in faststream/nats/test.py
async def ack_sync(\n    self, timeout: float = 1\n) -> \"PatchedMessage\":  # pragma: no cover\n    return self\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.in_progress","title":"in_progress async","text":"
in_progress() -> None\n
Source code in faststream/nats/test.py
async def in_progress(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.nak","title":"nak async","text":"
nak(delay: Union[int, float, None] = None) -> None\n
Source code in faststream/nats/test.py
async def nak(self, delay: Union[int, float, None] = None) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.respond","title":"respond async","text":"
respond(data: bytes) -> None\n

respond replies to the inbox of the message if there is one.

Source code in nats/aio/msg.py
async def respond(self, data: bytes) -> None:\n    \"\"\"\n    respond replies to the inbox of the message if there is one.\n    \"\"\"\n    if not self.reply:\n        raise Error('no reply subject available')\n    if not self._client:\n        raise Error('client not set')\n\n    await self._client.publish(self.reply, data, headers=self.headers)\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.term","title":"term async","text":"
term() -> None\n
Source code in faststream/nats/test.py
async def term(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/","title":"TestNatsBroker","text":"","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker","title":"faststream.nats.test.TestNatsBroker","text":"
TestNatsBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[NatsBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/nats/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: NatsBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(publisher.subject, _raw=True)\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(broker: NatsBroker, publisher: Any) -> None\n
Source code in faststream/nats/test.py
@staticmethod\ndef patch_publisher(broker: NatsBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> None\n
Source code in faststream/nats/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> None:\n    broker.handlers.pop(Handler.get_routing_hash(publisher.subject), None)\n
","boost":0.5},{"location":"api/faststream/nats/test/build_message/","title":"build_message","text":"","boost":0.5},{"location":"api/faststream/nats/test/build_message/#faststream.nats.test.build_message","title":"faststream.nats.test.build_message","text":"
build_message(\n    message: SendableMessage,\n    subject: str,\n    *,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[AnyDict] = None\n) -> PatchedMessage\n
Source code in faststream/nats/test.py
def build_message(\n    message: SendableMessage,\n    subject: str,\n    *,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[AnyDict] = None,\n) -> \"PatchedMessage\":\n    msg, content_type = encode_message(message)\n    return PatchedMessage(\n        _client=None,  # type: ignore\n        subject=subject,\n        reply=reply_to,\n        data=msg,\n        headers={\n            \"content-type\": content_type or \"\",\n            \"correlation_id\": correlation_id or str(uuid4()),\n            **(headers or {}),\n        },\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/","title":"ExchangeType","text":"","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType","title":"faststream.rabbit.ExchangeType","text":"

Bases: str, Enum

A class to represent the exchange type.

","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.DIRECT","title":"DIRECT class-attribute instance-attribute","text":"
DIRECT = 'direct'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.FANOUT","title":"FANOUT class-attribute instance-attribute","text":"
FANOUT = 'fanout'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.HEADERS","title":"HEADERS class-attribute instance-attribute","text":"
HEADERS = 'headers'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.TOPIC","title":"TOPIC class-attribute instance-attribute","text":"
TOPIC = 'topic'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.X_CONSISTENT_HASH","title":"X_CONSISTENT_HASH class-attribute instance-attribute","text":"
X_CONSISTENT_HASH = 'x-consistent-hash'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.X_DELAYED_MESSAGE","title":"X_DELAYED_MESSAGE class-attribute instance-attribute","text":"
X_DELAYED_MESSAGE = 'x-delayed-message'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.X_MODULUS_HASH","title":"X_MODULUS_HASH class-attribute instance-attribute","text":"
X_MODULUS_HASH = 'x-modulus-hash'\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/","title":"RabbitBroker","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker","title":"faststream.rabbit.RabbitBroker","text":"
RabbitBroker(\n    url: Union[\n        str, URL, None\n    ] = \"amqp://guest:guest@localhost:5672/\",\n    *,\n    host: str = None,\n    port: int = None,\n    login: str = None,\n    password: str = None,\n    virtualhost: str = None,\n    ssl_options: Optional[aio_pika.abc.SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    max_consumers: Optional[int] = None,\n    protocol: str = None,\n    protocol_version: Optional[str] = \"0.9.1\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: RabbitLoggingMixin, BrokerAsyncUsecase[IncomingMessage, RobustConnection]

A RabbitMQ broker for FastAPI applications.

This class extends the base BrokerAsyncUsecase and provides asynchronous support for RabbitMQ as a message broker.

PARAMETER DESCRIPTION url

The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".

TYPE: Union[str, URL, None] DEFAULT: 'amqp://guest:guest@localhost:5672/'

max_consumers

Maximum number of consumers to limit message consumption. Defaults to None.

TYPE: Optional[int] DEFAULT: None

protocol

The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".

TYPE: str DEFAULT: None

protocol_version

The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".

TYPE: Optional[str] DEFAULT: '0.9.1'

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Initialize the RabbitBroker.

PARAMETER DESCRIPTION url

The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".

TYPE: Union[str, URL, None] DEFAULT: 'amqp://guest:guest@localhost:5672/'

max_consumers

Maximum number of consumers to limit message consumption. Defaults to None.

TYPE: Optional[int] DEFAULT: None

protocol

The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".

TYPE: str DEFAULT: None

protocol_version

The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".

TYPE: Optional[str] DEFAULT: '0.9.1'

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/rabbit/broker.py
def __init__(\n    self,\n    url: Union[str, URL, None] = \"amqp://guest:guest@localhost:5672/\",\n    *,\n    # connection args\n    host: Optional[str] = None,\n    port: Optional[int] = None,\n    login: Optional[str] = None,\n    password: Optional[str] = None,\n    virtualhost: Optional[str] = None,\n    ssl_options: Optional[SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    # broker args\n    max_consumers: Optional[int] = None,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"0.9.1\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Initialize the RabbitBroker.\n\n    Args:\n        url (Union[str, URL, None], optional): The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".\n        max_consumers (Optional[int], optional): Maximum number of consumers to limit message consumption. Defaults to None.\n        protocol (str, optional): The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".\n        protocol_version (Optional[str], optional): The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".\n        **kwargs: Additional keyword arguments.\n    \"\"\"\n    security_args = parse_security(security)\n\n    if (ssl := kwargs.get(\"ssl\")) or kwargs.get(\"ssl_context\"):  # pragma: no cover\n        warnings.warn(\n            (\n                f\"\\nRabbitMQ {'`ssl`' if ssl else '`ssl_context`'} option was deprecated and will be removed in 0.4.0\"\n                \"\\nPlease, use `security` with `BaseSecurity` or `SASLPlaintext` instead\"\n            ),\n            DeprecationWarning,\n            stacklevel=2,\n        )\n\n    amqp_url = build_url(\n        url,\n        host=host,\n        port=port,\n        login=security_args.get(\"login\", login),\n        password=security_args.get(\"password\", password),\n        virtualhost=virtualhost,\n        ssl=security_args.get(\"ssl\", kwargs.pop(\"ssl\", False)),\n        ssl_options=ssl_options,\n        client_properties=client_properties,\n    )\n\n    super().__init__(\n        url=str(amqp_url),\n        protocol_version=protocol_version,\n        security=security,\n        ssl_context=security_args.get(\n            \"ssl_context\",\n            kwargs.pop(\"ssl_context\", None),\n        ),\n        **kwargs,\n    )\n\n    # respect ascynapi_url argument scheme\n    asyncapi_url = build_url(self.url)\n    self.protocol = protocol or asyncapi_url.scheme\n    self.virtual_host = asyncapi_url.path\n\n    self._max_consumers = max_consumers\n\n    self._channel = None\n    self.declarer = None\n    self._producer = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.declarer","title":"declarer instance-attribute","text":"
declarer: Optional[RabbitDeclarer] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[int, Handler]\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol or asyncapi_url.scheme\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.virtual_host","title":"virtual_host instance-attribute","text":"
virtual_host = asyncapi_url.path\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.connect","title":"connect async","text":"
connect(\n    *args: Any, **kwargs: Any\n) -> aio_pika.RobustConnection\n

Connect to the RabbitMQ server.

PARAMETER DESCRIPTION *args

Additional positional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION RobustConnection

aio_pika.RobustConnection: The RabbitMQ connection instance.

Source code in faststream/rabbit/broker.py
async def connect(self, *args: Any, **kwargs: Any) -> aio_pika.RobustConnection:\n    \"\"\"\n    Connect to the RabbitMQ server.\n\n    Args:\n        *args: Additional positional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        aio_pika.RobustConnection: The RabbitMQ connection instance.\n    \"\"\"\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.declare_exchange","title":"declare_exchange async","text":"
declare_exchange(\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange\n

Declare a RabbitMQ exchange.

PARAMETER DESCRIPTION exchange

The RabbitMQ exchange to declare.

TYPE: RabbitExchange

RETURNS DESCRIPTION RobustExchange

aio_pika.RobustExchange: The declared RabbitMQ exchange.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def declare_exchange(\n    self,\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange:\n    \"\"\"\n    Declare a RabbitMQ exchange.\n\n    Args:\n        exchange (RabbitExchange): The RabbitMQ exchange to declare.\n\n    Returns:\n        aio_pika.RobustExchange: The declared RabbitMQ exchange.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n    return await self.declarer.declare_exchange(exchange)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.declare_queue","title":"declare_queue async","text":"
declare_queue(queue: RabbitQueue) -> aio_pika.RobustQueue\n

Declare a RabbitMQ queue.

PARAMETER DESCRIPTION queue

The RabbitMQ queue to declare.

TYPE: RabbitQueue

RETURNS DESCRIPTION RobustQueue

aio_pika.RobustQueue: The declared RabbitMQ queue.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def declare_queue(\n    self,\n    queue: RabbitQueue,\n) -> aio_pika.RobustQueue:\n    \"\"\"\n    Declare a RabbitMQ queue.\n\n    Args:\n        queue (RabbitQueue): The RabbitMQ queue to declare.\n\n    Returns:\n        aio_pika.RobustQueue: The declared RabbitMQ queue.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n    return await self.declarer.declare_queue(queue)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, **kwargs: Any\n) -> Union[\n    aiormq.abc.ConfirmationFrameType, SendableMessage\n]\n

Publish a message to the RabbitMQ broker.

PARAMETER DESCRIPTION *args

Additional positional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Union[ConfirmationFrameType, SendableMessage]

Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The confirmation frame or the response message.

Source code in faststream/rabbit/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Union[aiormq.abc.ConfirmationFrameType, SendableMessage]:\n    \"\"\"\n    Publish a message to the RabbitMQ broker.\n\n    Args:\n        *args: Additional positional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The confirmation frame or the response message.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.publisher","title":"publisher","text":"
publisher(\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Publisher\n

Define a message publisher.

PARAMETER DESCRIPTION queue

The name of the RabbitMQ queue. Defaults to \"\".

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The name of the RabbitMQ exchange. Defaults to None.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key for messages. Defaults to \"\".

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory. Defaults to True.

TYPE: bool DEFAULT: True

immediate

Whether the message should be sent immediately. Defaults to False.

TYPE: bool DEFAULT: False

timeout

Timeout for message publishing. Defaults to None.

TYPE: TimeoutType DEFAULT: None

persist

Whether to persist messages. Defaults to False.

TYPE: bool DEFAULT: False

reply_to

The reply-to queue name. Defaults to None.

TYPE: Optional[str] DEFAULT: None

title

Title for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

description

Description for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional message properties and content.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Publisher

A message publisher instance.

TYPE: Publisher

Source code in faststream/rabbit/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Publisher:\n    \"\"\"\n    Define a message publisher.\n\n    Args:\n        queue (Union[RabbitQueue, str], optional): The name of the RabbitMQ queue. Defaults to \"\".\n        exchange (Union[RabbitExchange, str, None], optional): The name of the RabbitMQ exchange. Defaults to None.\n        routing_key (str, optional): The routing key for messages. Defaults to \"\".\n        mandatory (bool, optional): Whether the message is mandatory. Defaults to True.\n        immediate (bool, optional): Whether the message should be sent immediately. Defaults to False.\n        timeout (TimeoutType, optional): Timeout for message publishing. Defaults to None.\n        persist (bool, optional): Whether to persist messages. Defaults to False.\n        reply_to (Optional[str], optional): The reply-to queue name. Defaults to None.\n        title (Optional[str]): Title for AsyncAPI docs.\n        description (Optional[str]): Description for AsyncAPI docs.\n        **message_kwargs (Any): Additional message properties and content.\n\n    Returns:\n        Publisher: A message publisher instance.\n    \"\"\"\n    q, ex = RabbitQueue.validate(queue), RabbitExchange.validate(exchange)\n\n    publisher = Publisher(\n        title=title,\n        queue=q,\n        exchange=ex,\n        routing_key=routing_key,\n        mandatory=mandatory,\n        immediate=immediate,\n        timeout=timeout,\n        persist=persist,\n        reply_to=reply_to,\n        priority=priority,\n        message_kwargs=message_kwargs,\n        _description=description,\n        _schema=schema,\n        virtual_host=self.virtual_host,\n        include_in_schema=include_in_schema,\n    )\n\n    key = publisher._get_routing_hash()\n    publisher = self._publishers.get(key, publisher)\n    super().publisher(key, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.start","title":"start async","text":"
start() -> None\n

Start the RabbitMQ broker.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def start(self) -> None:\n    \"\"\"\n    Start the RabbitMQ broker.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, RabbitQueue(\"\"), RabbitExchange(\"\")),\n    )\n\n    await super().start()\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n\n    for publisher in self._publishers.values():\n        if publisher.exchange is not None:\n            await self.declare_exchange(publisher.exchange)\n\n    for handler in self.handlers.values():\n        c = self._get_log_context(None, handler.queue, handler.exchange)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self.declarer)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Filter[RabbitMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n

Decorator to define a message subscriber.

PARAMETER DESCRIPTION queue

The name of the RabbitMQ queue.

TYPE: Union[str, RabbitQueue]

exchange

The name of the RabbitMQ exchange. Defaults to None.

TYPE: Union[str, RabbitExchange, None] DEFAULT: None

consume_args

Additional arguments for message consumption.

TYPE: Optional[AnyDict] DEFAULT: None

no_ack

Whether not to ack/nack/reject messages.

TYPE: bool DEFAULT: False

title

Title for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

description

Description for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION Callable

A decorator function for defining message subscribers.

TYPE: Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn]]

Source code in faststream/rabbit/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[aio_pika.IncomingMessage, RabbitMessage]] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[aio_pika.IncomingMessage], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RabbitMessage] = default_filter,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"\n    Decorator to define a message subscriber.\n\n    Args:\n        queue (Union[str, RabbitQueue]): The name of the RabbitMQ queue.\n        exchange (Union[str, RabbitExchange, None], optional): The name of the RabbitMQ exchange. Defaults to None.\n        consume_args (Optional[AnyDict], optional): Additional arguments for message consumption.\n        no_ack (bool): Whether not to ack/nack/reject messages.\n        title (Optional[str]): Title for AsyncAPI docs.\n        description (Optional[str]): Description for AsyncAPI docs.\n\n    Returns:\n        Callable: A decorator function for defining message subscribers.\n    \"\"\"\n    super().subscriber()\n\n    r_queue = RabbitQueue.validate(queue)\n    r_exchange = RabbitExchange.validate(exchange)\n\n    self._setup_log_context(r_queue, r_exchange)\n\n    key = get_routing_hash(r_queue, r_exchange)\n    handler = self.handlers.get(\n        key,\n        Handler(\n            log_context_builder=partial(\n                self._get_log_context, queue=r_queue, exchange=r_exchange\n            ),\n            queue=r_queue,\n            exchange=r_exchange,\n            consume_args=consume_args,\n            description=description,\n            title=title,\n            virtual_host=self.virtual_host,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n        ),\n    )\n\n    self.handlers[key] = handler\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[\n        aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn\n    ]:\n        \"\"\"Wraps a consumer function with additional functionality.\n\n        Args:\n            func: The consumer function to be wrapped.\n\n        Returns:\n            The wrapped consumer function.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            _process_kwargs={\n                \"reply_config\": reply_config,\n            },\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/","title":"RabbitExchange","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange","title":"faststream.rabbit.RabbitExchange","text":"
RabbitExchange(\n    name: str,\n    type: ExchangeType = ExchangeType.DIRECT,\n    durable: bool = False,\n    auto_delete: bool = False,\n    internal: bool = False,\n    passive: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_to: Optional[RabbitExchange] = None,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n)\n

Bases: NameRequired

A class to represent a RabbitMQ exchange.

METHOD DESCRIPTION __hash__

returns the hash value of the exchange

__init__

initializes the RabbitExchange object

Initialize a RabbitExchange object.

PARAMETER DESCRIPTION name

Name of the exchange.

TYPE: str

type

Type of the exchange. Defaults to ExchangeType.DIRECT.

TYPE: ExchangeType DEFAULT: DIRECT

durable

Whether the exchange should survive broker restarts. Defaults to False.

TYPE: bool DEFAULT: False

auto_delete

Whether the exchange should be deleted when no longer in use. Defaults to False.

TYPE: bool DEFAULT: False

internal

Whether the exchange is used for internal purposes and should not be published to directly. Defaults to False.

TYPE: bool DEFAULT: False

passive

Whether to check if the exchange exists before creating it. Defaults to False.

TYPE: bool DEFAULT: False

arguments

Additional arguments for the exchange. Defaults to None.

TYPE: Optional[AnyDict] DEFAULT: None

timeout

Timeout for the operation. Defaults to None.

TYPE: TimeoutType DEFAULT: None

robust

Whether to use robust mode for the exchange. Defaults to True.

TYPE: bool DEFAULT: True

bind_to

Exchange to bind to. Defaults to None.

TYPE: Optional[RabbitExchange] DEFAULT: None

bind_arguments

Arguments for the binding. Defaults to None.

TYPE: Optional[AnyDict] DEFAULT: None

routing_key

Routing key for the exchange. Defaults to \"\".

TYPE: str DEFAULT: ''

RAISES DESCRIPTION NotImplementedError Source code in faststream/rabbit/shared/schemas.py
def __init__(\n    self,\n    name: str,\n    type: ExchangeType = ExchangeType.DIRECT,\n    durable: bool = False,\n    auto_delete: bool = False,\n    internal: bool = False,\n    passive: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_to: Optional[\"RabbitExchange\"] = None,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n) -> None:\n    \"\"\"Initialize a RabbitExchange object.\n\n    Args:\n        name (str): Name of the exchange.\n        type (ExchangeType, optional): Type of the exchange. Defaults to ExchangeType.DIRECT.\n        durable (bool, optional): Whether the exchange should survive broker restarts. Defaults to False.\n        auto_delete (bool, optional): Whether the exchange should be deleted when no longer in use. Defaults to False.\n        internal (bool, optional): Whether the exchange is used for internal purposes and should not be published to directly. Defaults to False.\n        passive (bool, optional): Whether to check if the exchange exists before creating it. Defaults to False.\n        arguments (Optional[AnyDict], optional): Additional arguments for the exchange. Defaults to None.\n        timeout (TimeoutType, optional): Timeout for the operation. Defaults to None.\n        robust (bool, optional): Whether to use robust mode for the exchange. Defaults to True.\n        bind_to (Optional[\"RabbitExchange\"], optional): Exchange to bind to. Defaults to None.\n        bind_arguments (Optional[AnyDict], optional): Arguments for the binding. Defaults to None.\n        routing_key (str, optional): Routing key for the exchange. Defaults to \"\".\n\n    Raises:\n        NotImplementedError:\n\n    \"\"\"\n    if routing_key and bind_to is None:  # pragma: no cover\n        warnings.warn(\n            (\n                \"\\nRabbitExchange `routing_key` is using to bind exchange to another one\"\n                \"\\nIt can be used only with the `bind_to` argument, please setup it too\"\n            ),\n            category=RuntimeWarning,\n            stacklevel=1,\n        )\n\n    super().__init__(\n        name=name,\n        type=type.value,\n        durable=durable,\n        auto_delete=auto_delete,\n        routing_key=routing_key,\n        bind_to=bind_to,\n        bind_arguments=bind_arguments,\n        robust=robust,\n        internal=internal,\n        passive=passive,\n        timeout=timeout,\n        arguments=arguments,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.arguments","title":"arguments class-attribute instance-attribute","text":"
arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.auto_delete","title":"auto_delete class-attribute instance-attribute","text":"
auto_delete: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.bind_arguments","title":"bind_arguments class-attribute instance-attribute","text":"
bind_arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.bind_to","title":"bind_to class-attribute instance-attribute","text":"
bind_to: Optional[RabbitExchange] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.durable","title":"durable class-attribute instance-attribute","text":"
durable: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.internal","title":"internal class-attribute instance-attribute","text":"
internal: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.passive","title":"passive class-attribute instance-attribute","text":"
passive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.robust","title":"robust class-attribute instance-attribute","text":"
robust: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.type","title":"type class-attribute instance-attribute","text":"
type: str = ExchangeType.DIRECT.value\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/","title":"RabbitQueue","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue","title":"faststream.rabbit.RabbitQueue","text":"
RabbitQueue(\n    name: str,\n    durable: bool = False,\n    exclusive: bool = False,\n    passive: bool = False,\n    auto_delete: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n)\n

Bases: NameRequired

A class to represent a RabbitMQ queue.

METHOD DESCRIPTION __hash__

returns the hash value of the queue

routing

returns the routing key of the queue

__init__

initializes the RabbitQueue object with the given parameters

Initialize a class object.

PARAMETER DESCRIPTION name

The name of the object.

TYPE: str

durable

Whether the object is durable. Defaults to False.

TYPE: bool DEFAULT: False

exclusive

Whether the object is exclusive. Defaults to False.

TYPE: bool DEFAULT: False

passive

Whether the object is passive. Defaults to False.

TYPE: bool DEFAULT: False

auto_delete

Whether the object is auto delete. Defaults to False.

TYPE: bool DEFAULT: False

arguments

Additional arguments for the object. Defaults to None.

TYPE: dict DEFAULT: None

timeout

Timeout for the object. Defaults to None.

TYPE: TimeoutType DEFAULT: None

robust

Whether the object is robust. Defaults to True.

TYPE: bool DEFAULT: True

bind_arguments

Bind arguments for the object. Defaults to None.

TYPE: dict DEFAULT: None

routing_key

Routing key for the object. Defaults to \"\".

TYPE: str DEFAULT: ''

Source code in faststream/rabbit/shared/schemas.py
def __init__(\n    self,\n    name: str,\n    durable: bool = False,\n    exclusive: bool = False,\n    passive: bool = False,\n    auto_delete: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n) -> None:\n    \"\"\"Initialize a class object.\n\n    Args:\n        name (str): The name of the object.\n        durable (bool, optional): Whether the object is durable. Defaults to False.\n        exclusive (bool, optional): Whether the object is exclusive. Defaults to False.\n        passive (bool, optional): Whether the object is passive. Defaults to False.\n        auto_delete (bool, optional): Whether the object is auto delete. Defaults to False.\n        arguments (dict, optional): Additional arguments for the object. Defaults to None.\n        timeout (TimeoutType, optional): Timeout for the object. Defaults to None.\n        robust (bool, optional): Whether the object is robust. Defaults to True.\n        bind_arguments (dict, optional): Bind arguments for the object. Defaults to None.\n        routing_key (str, optional): Routing key for the object. Defaults to \"\".\n\n    \"\"\"\n    re, routing_key = compile_path(routing_key, replace_symbol=\"*\")\n    super().__init__(\n        name=name,\n        path_regex=re,\n        durable=durable,\n        exclusive=exclusive,\n        bind_arguments=bind_arguments,\n        routing_key=routing_key,\n        robust=robust,\n        passive=passive,\n        auto_delete=auto_delete,\n        arguments=arguments,\n        timeout=timeout,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.arguments","title":"arguments class-attribute instance-attribute","text":"
arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.auto_delete","title":"auto_delete class-attribute instance-attribute","text":"
auto_delete: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.bind_arguments","title":"bind_arguments class-attribute instance-attribute","text":"
bind_arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.durable","title":"durable class-attribute instance-attribute","text":"
durable: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.exclusive","title":"exclusive class-attribute instance-attribute","text":"
exclusive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'arbitrary_types_allowed': True}\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.name","title":"name class-attribute instance-attribute","text":"
name: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.passive","title":"passive class-attribute instance-attribute","text":"
passive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.path_regex","title":"path_regex class-attribute instance-attribute","text":"
path_regex: Optional[Pattern[str]] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.robust","title":"robust class-attribute instance-attribute","text":"
robust: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.routing","title":"routing property","text":"
routing: str\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.Config.arbitrary_types_allowed","title":"arbitrary_types_allowed class-attribute instance-attribute","text":"
arbitrary_types_allowed = True\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRoute/","title":"RabbitRoute","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/","title":"RabbitRouter","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter","title":"faststream.rabbit.RabbitRouter","text":"
RabbitRouter(\n    prefix: str = \"\",\n    handlers: Sequence[RabbitRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: RabbitRouter

A class representing a RabbitMQ router for publishing messages.

METHOD DESCRIPTION _get_publisher_key

Returns the key for a given Publisher object

_update_publisher_prefix

Updates the prefix of a given Publisher object

publisher

Publishes a message to RabbitMQ

Source code in faststream/rabbit/router.py
_publishers: Dict[int, Publisher]\n\n@staticmethod\ndef _get_publisher_key(publisher: Publisher) -> int:\n    \"\"\"Get the publisher key.\n\n    Args:\n        publisher: The publisher object.\n\n    Returns:\n        The publisher key as an integer.\n\n    \"\"\"\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.publisher","title":"publisher","text":"
publisher(\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Publisher\n

Publishes a message to a RabbitMQ queue or exchange.

PARAMETER DESCRIPTION queue

The RabbitMQ queue to publish the message to. Can be either a RabbitQueue object or a string representing the queue name.

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The RabbitMQ exchange to publish the message to. Can be either a RabbitExchange object, a string representing the exchange name, or None.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key to use when publishing the message.

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory or not.

TYPE: bool DEFAULT: True

immediate

Whether the message should be delivered immediately or not.

TYPE: bool DEFAULT: False

timeout

The timeout for the publish operation.

TYPE: TimeoutType DEFAULT: None

persist

Whether the message should be persisted or not.

TYPE: bool DEFAULT: False

reply_to

The reply-to address for the message.

TYPE: Optional[str] DEFAULT: None

title

The title of the message (AsyncAPI information).

TYPE: Optional[str] DEFAULT: None

description

The description of the message (AsyncAPI information).

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional keyword arguments to include in the message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Publisher

The Publisher object used to publish the message.

Source code in faststream/rabbit/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Publisher:\n    \"\"\"Publishes a message to a RabbitMQ queue or exchange.\n\n    Args:\n        queue: The RabbitMQ queue to publish the message to. Can be either a RabbitQueue object or a string representing the queue name.\n        exchange: The RabbitMQ exchange to publish the message to. Can be either a RabbitExchange object, a string representing the exchange name, or None.\n        routing_key: The routing key to use when publishing the message.\n        mandatory: Whether the message is mandatory or not.\n        immediate: Whether the message should be delivered immediately or not.\n        timeout: The timeout for the publish operation.\n        persist: Whether the message should be persisted or not.\n        reply_to: The reply-to address for the message.\n        title: The title of the message (AsyncAPI information).\n        description: The description of the message (AsyncAPI information).\n        **message_kwargs: Additional keyword arguments to include in the message.\n\n    Returns:\n        The Publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            queue=RabbitQueue.validate(queue),\n            exchange=RabbitExchange.validate(exchange),\n            routing_key=routing_key,\n            mandatory=mandatory,\n            immediate=immediate,\n            timeout=timeout,\n            persist=persist,\n            reply_to=reply_to,\n            priority=priority,\n            message_kwargs=message_kwargs,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[key] = self._publishers.get(key, new_publisher)\n    return publisher\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    dependencies: Sequence[Depends] = (),\n    filter: Filter[RabbitMessage] = default_filter,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    retry: Union[bool, int] = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n
Source code in faststream/rabbit/router.py
    Returns:\n        Publisher: The updated publisher object.\n\n    Note:\n        This function is intended to be used as a decorator.\n\n    \"\"\"\n    publisher.queue = model_copy(\n        publisher.queue, update={\"name\": prefix + publisher.queue.name}\n    )\n    return publisher\n\n@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n
","boost":0.5},{"location":"api/faststream/rabbit/ReplyConfig/","title":"ReplyConfig","text":"","boost":0.5},{"location":"api/faststream/rabbit/ReplyConfig/#faststream.rabbit.ReplyConfig","title":"faststream.rabbit.ReplyConfig","text":"

Bases: BaseModel

","boost":0.5},{"location":"api/faststream/rabbit/ReplyConfig/#faststream.rabbit.ReplyConfig.immediate","title":"immediate class-attribute instance-attribute","text":"
immediate: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/ReplyConfig/#faststream.rabbit.ReplyConfig.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/ReplyConfig/#faststream.rabbit.ReplyConfig.persist","title":"persist class-attribute instance-attribute","text":"
persist: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/rabbit/TestApp/#faststream.broker.test.TestApp","title":"faststream.broker.test.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/rabbit/TestApp/#faststream.broker.test.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/","title":"TestRabbitBroker","text":"","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker","title":"faststream.rabbit.TestRabbitBroker","text":"
TestRabbitBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[RabbitBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: RabbitBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: RabbitBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(\n        queue=publisher.queue,\n        exchange=publisher.exchange,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: RabbitBroker, publisher: Any\n) -> None\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef patch_publisher(broker: RabbitBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: RabbitBroker, publisher: Publisher\n) -> None\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: RabbitBroker,\n    publisher: Publisher,\n) -> None:\n    broker.handlers.pop(\n        publisher._get_routing_hash(),\n        None,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/","title":"Handler","text":"","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler","title":"faststream.rabbit.asyncapi.Handler","text":"
Handler(\n    queue: RabbitQueue,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    exchange: Optional[RabbitExchange] = None,\n    consume_args: Optional[AnyDict] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    virtual_host: str = \"/\",\n)\n

Bases: LogicHandler

A class that serves as a handler for RMQAsyncAPIChannel and LogicHandler.

METHOD DESCRIPTION - name

Returns the name of the handler.

- get_payloads

Returns a list of payloads.

Initialize a RabbitMQ consumer.

PARAMETER DESCRIPTION queue

RabbitQueue object representing the queue to consume from

TYPE: RabbitQueue

exchange

RabbitExchange object representing the exchange to bind the queue to (optional)

TYPE: Optional[RabbitExchange] DEFAULT: None

consume_args

Additional arguments for consuming from the queue (optional)

TYPE: Optional[AnyDict] DEFAULT: None

description

Description of the consumer (optional)

TYPE: Optional[str] DEFAULT: None

title

Title of the consumer (optional)

TYPE: Optional[str] DEFAULT: None

Source code in faststream/rabbit/handler.py
def __init__(\n    self,\n    queue: RabbitQueue,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # RMQ information\n    exchange: Optional[RabbitExchange] = None,\n    consume_args: Optional[AnyDict] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    virtual_host: str = \"/\",\n) -> None:\n    \"\"\"Initialize a RabbitMQ consumer.\n\n    Args:\n        queue: RabbitQueue object representing the queue to consume from\n        exchange: RabbitExchange object representing the exchange to bind the queue to (optional)\n        consume_args: Additional arguments for consuming from the queue (optional)\n        description: Description of the consumer (optional)\n        title: Title of the consumer (optional)\n\n    \"\"\"\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.queue = queue\n    self.exchange = exchange\n    self.virtual_host = virtual_host\n    self.consume_args = consume_args or {}\n\n    self._consumer_tag = None\n    self._queue_obj = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.consume_args","title":"consume_args instance-attribute","text":"
consume_args: AnyDict = consume_args or {}\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.exchange","title":"exchange instance-attribute","text":"
exchange: Optional[RabbitExchange] = exchange\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.queue","title":"queue instance-attribute","text":"
queue: RabbitQueue = queue\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.virtual_host","title":"virtual_host instance-attribute","text":"
virtual_host = virtual_host\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ],\n    decoder: Optional[CustomDecoder[RabbitMessage]],\n    filter: Filter[RabbitMessage],\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ]\n) -> None\n

Add a call to the handler.

PARAMETER DESCRIPTION handler

The handler for the call.

TYPE: HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn]

dependant

The dependant for the call.

TYPE: CallModel[P_HandlerParams, T_HandlerReturn]

parser

Optional custom parser for the call.

TYPE: Optional[CustomParser[IncomingMessage, RabbitMessage]]

decoder

Optional custom decoder for the call.

TYPE: Optional[CustomDecoder[RabbitMessage]]

filter

The filter for the call.

TYPE: Filter[RabbitMessage]

middlewares

Optional sequence of middlewares for the call.

TYPE: Optional[Sequence[Callable[[IncomingMessage], BaseMiddleware]]]

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[\n        aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[aio_pika.IncomingMessage, RabbitMessage]],\n    decoder: Optional[CustomDecoder[RabbitMessage]],\n    filter: Filter[RabbitMessage],\n    middlewares: Optional[\n        Sequence[Callable[[aio_pika.IncomingMessage], BaseMiddleware]]\n    ],\n) -> None:\n    \"\"\"Add a call to the handler.\n\n    Args:\n        handler: The handler for the call.\n        dependant: The dependant for the call.\n        parser: Optional custom parser for the call.\n        decoder: Optional custom decoder for the call.\n        filter: The filter for the call.\n        middlewares: Optional sequence of middlewares for the call.\n\n    Returns:\n        None\n\n    \"\"\"\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, AioPikaParser.parse_message),\n        decoder=resolve_custom_func(decoder, AioPikaParser.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/rabbit/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self._queue_obj is not None:\n        if self._consumer_tag is not None:  # pragma: no branch\n            await self._queue_obj.cancel(self._consumer_tag)\n            self._consumer_tag = None\n        self._queue_obj = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/rabbit/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    handler_name = (\n        self._title\n        or f\"{self.queue.name}:{getattr(self.exchange, 'name', '_')}:{self.call_name}\"\n    )\n\n    return {\n        handler_name: Channel(\n            description=self.description,  # type: ignore[attr-defined]\n            subscribe=Operation(\n                bindings=OperationBinding(\n                    amqp=amqp.OperationBinding(\n                        cc=self.queue.routing,\n                    ),\n                )\n                if _is_exchange(self.exchange)\n                else None,\n                message=Message(\n                    title=f\"{handler_name}:Message\",\n                    payload=resolve_payloads(payloads),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                amqp=amqp.ChannelBinding(\n                    **{\n                        \"is\": \"routingKey\",  # type: ignore\n                        \"queue\": amqp.Queue(\n                            name=self.queue.name,\n                            durable=self.queue.durable,\n                            exclusive=self.queue.exclusive,\n                            autoDelete=self.queue.auto_delete,\n                            vhost=self.virtual_host,\n                        )\n                        if _is_exchange(self.exchange)\n                        else None,\n                        \"exchange\": (\n                            amqp.Exchange(type=\"default\", vhost=self.virtual_host)\n                            if self.exchange is None\n                            else amqp.Exchange(\n                                type=self.exchange.type,  # type: ignore\n                                name=self.exchange.name,\n                                durable=self.exchange.durable,\n                                autoDelete=self.exchange.auto_delete,\n                                vhost=self.virtual_host,\n                            )\n                        ),\n                    }\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.start","title":"start async","text":"
start(declarer: RabbitDeclarer) -> None\n

Starts the consumer for the RabbitMQ queue.

PARAMETER DESCRIPTION declarer

RabbitDeclarer object used to declare the queue and exchange

TYPE: RabbitDeclarer

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/handler.py
@override\nasync def start(self, declarer: RabbitDeclarer) -> None:  # type: ignore[override]\n    \"\"\"Starts the consumer for the RabbitMQ queue.\n\n    Args:\n        declarer: RabbitDeclarer object used to declare the queue and exchange\n\n    Returns:\n        None\n\n    \"\"\"\n    self._queue_obj = queue = await declarer.declare_queue(self.queue)\n\n    if self.exchange is not None:\n        exchange = await declarer.declare_exchange(self.exchange)\n        await queue.bind(\n            exchange,\n            routing_key=self.queue.routing,\n            arguments=self.queue.bind_arguments,\n        )\n\n    self._consumer_tag = await queue.consume(\n        # NOTE: aio-pika expects AbstractIncomingMessage, not IncomingMessage\n        self.consume,  # type: ignore[arg-type]\n        arguments=self.consume_args,\n    )\n\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/","title":"Publisher","text":"","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher","title":"faststream.rabbit.asyncapi.Publisher","text":"

Bases: LogicPublisher

A class representing a publisher.

METHOD DESCRIPTION get_payloads

Get the payloads for the publisher

","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.exchange","title":"exchange class-attribute instance-attribute","text":"
exchange: Optional[RabbitExchange] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.immediate","title":"immediate class-attribute instance-attribute","text":"
immediate: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.message_kwargs","title":"message_kwargs class-attribute instance-attribute","text":"
message_kwargs: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.name","title":"name property","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.persist","title":"persist class-attribute instance-attribute","text":"
persist: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.priority","title":"priority class-attribute instance-attribute","text":"
priority: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.queue","title":"queue class-attribute instance-attribute","text":"
queue: RabbitQueue = field(default=RabbitQueue(''))\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.routing","title":"routing property","text":"
routing: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.virtual_host","title":"virtual_host class-attribute instance-attribute","text":"
virtual_host: str = '/'\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.publish","title":"publish async","text":"
publish(\n    message: AioPikaSendableMessage = \"\",\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    correlation_id: Optional[str] = None,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Union[\n    aiormq.abc.ConfirmationFrameType, SendableMessage\n]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: AioPikaSendableMessage DEFAULT: ''

rpc

Whether the message is for RPC (Remote Procedure Call).

TYPE: bool DEFAULT: False

rpc_timeout

Timeout for RPC.

TYPE: Optional[float] DEFAULT: 30.0

raise_timeout

Whether to raise an exception if timeout occurs.

TYPE: bool DEFAULT: False

correlation_id

Correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional keyword arguments for the message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Union[ConfirmationFrameType, SendableMessage]

ConfirmationFrameType or SendableMessage: The result of the publish operation.

RAISES DESCRIPTION AssertionError

If _producer is not set up.

Source code in faststream/rabbit/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: AioPikaSendableMessage = \"\",\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    correlation_id: Optional[str] = None,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Union[aiormq.abc.ConfirmationFrameType, SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        rpc: Whether the message is for RPC (Remote Procedure Call).\n        rpc_timeout: Timeout for RPC.\n        raise_timeout: Whether to raise an exception if timeout occurs.\n        correlation_id: Correlation ID for the message.\n        **message_kwargs: Additional keyword arguments for the message.\n\n    Returns:\n        ConfirmationFrameType or SendableMessage: The result of the publish operation.\n\n    Raises:\n        AssertionError: If `_producer` is not set up.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(\n        message=message,\n        exchange=self.exchange,\n        routing_key=self.routing,\n        mandatory=self.mandatory,\n        immediate=self.immediate,\n        timeout=self.timeout,\n        rpc=rpc,\n        rpc_timeout=rpc_timeout,\n        raise_timeout=raise_timeout,\n        persist=self.persist,\n        reply_to=self.reply_to,\n        correlation_id=correlation_id,\n        priority=priority or self.priority,\n        **self.message_kwargs,\n        **message_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/rabbit/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    return {\n        self.name: Channel(\n            description=self.description,  # type: ignore[attr-defined]\n            publish=Operation(\n                bindings=OperationBinding(\n                    amqp=amqp.OperationBinding(\n                        cc=self.routing or None,\n                        deliveryMode=2 if self.persist else 1,\n                        mandatory=self.mandatory,\n                        replyTo=self.reply_to,\n                        priority=self.priority,\n                    ),\n                )\n                if _is_exchange(self.exchange)\n                else None,\n                message=Message(\n                    title=f\"{self.name}:Message\",\n                    payload=resolve_payloads(\n                        payloads,\n                        \"Publisher\",\n                        served_words=2 if self.title is None else 1,\n                    ),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                amqp=amqp.ChannelBinding(\n                    **{\n                        \"is\": \"routingKey\",  # type: ignore\n                        \"queue\": amqp.Queue(\n                            name=self.queue.name,\n                            durable=self.queue.durable,\n                            exclusive=self.queue.exclusive,\n                            autoDelete=self.queue.auto_delete,\n                            vhost=self.virtual_host,\n                        )\n                        if _is_exchange(self.exchange) and self.queue.name\n                        else None,\n                        \"exchange\": (\n                            amqp.Exchange(type=\"default\", vhost=self.virtual_host)\n                            if self.exchange is None\n                            else amqp.Exchange(\n                                type=self.exchange.type,  # type: ignore\n                                name=self.exchange.name,\n                                durable=self.exchange.durable,\n                                autoDelete=self.exchange.auto_delete,\n                                vhost=self.virtual_host,\n                            )\n                        ),\n                    }\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/","title":"RabbitBroker","text":"","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker","title":"faststream.rabbit.broker.RabbitBroker","text":"
RabbitBroker(\n    url: Union[\n        str, URL, None\n    ] = \"amqp://guest:guest@localhost:5672/\",\n    *,\n    host: str = None,\n    port: int = None,\n    login: str = None,\n    password: str = None,\n    virtualhost: str = None,\n    ssl_options: Optional[aio_pika.abc.SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    max_consumers: Optional[int] = None,\n    protocol: str = None,\n    protocol_version: Optional[str] = \"0.9.1\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: RabbitLoggingMixin, BrokerAsyncUsecase[IncomingMessage, RobustConnection]

A RabbitMQ broker for FastAPI applications.

This class extends the base BrokerAsyncUsecase and provides asynchronous support for RabbitMQ as a message broker.

PARAMETER DESCRIPTION url

The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".

TYPE: Union[str, URL, None] DEFAULT: 'amqp://guest:guest@localhost:5672/'

max_consumers

Maximum number of consumers to limit message consumption. Defaults to None.

TYPE: Optional[int] DEFAULT: None

protocol

The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".

TYPE: str DEFAULT: None

protocol_version

The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".

TYPE: Optional[str] DEFAULT: '0.9.1'

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Initialize the RabbitBroker.

PARAMETER DESCRIPTION url

The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".

TYPE: Union[str, URL, None] DEFAULT: 'amqp://guest:guest@localhost:5672/'

max_consumers

Maximum number of consumers to limit message consumption. Defaults to None.

TYPE: Optional[int] DEFAULT: None

protocol

The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".

TYPE: str DEFAULT: None

protocol_version

The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".

TYPE: Optional[str] DEFAULT: '0.9.1'

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/rabbit/broker.py
def __init__(\n    self,\n    url: Union[str, URL, None] = \"amqp://guest:guest@localhost:5672/\",\n    *,\n    # connection args\n    host: Optional[str] = None,\n    port: Optional[int] = None,\n    login: Optional[str] = None,\n    password: Optional[str] = None,\n    virtualhost: Optional[str] = None,\n    ssl_options: Optional[SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    # broker args\n    max_consumers: Optional[int] = None,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"0.9.1\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Initialize the RabbitBroker.\n\n    Args:\n        url (Union[str, URL, None], optional): The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".\n        max_consumers (Optional[int], optional): Maximum number of consumers to limit message consumption. Defaults to None.\n        protocol (str, optional): The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".\n        protocol_version (Optional[str], optional): The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".\n        **kwargs: Additional keyword arguments.\n    \"\"\"\n    security_args = parse_security(security)\n\n    if (ssl := kwargs.get(\"ssl\")) or kwargs.get(\"ssl_context\"):  # pragma: no cover\n        warnings.warn(\n            (\n                f\"\\nRabbitMQ {'`ssl`' if ssl else '`ssl_context`'} option was deprecated and will be removed in 0.4.0\"\n                \"\\nPlease, use `security` with `BaseSecurity` or `SASLPlaintext` instead\"\n            ),\n            DeprecationWarning,\n            stacklevel=2,\n        )\n\n    amqp_url = build_url(\n        url,\n        host=host,\n        port=port,\n        login=security_args.get(\"login\", login),\n        password=security_args.get(\"password\", password),\n        virtualhost=virtualhost,\n        ssl=security_args.get(\"ssl\", kwargs.pop(\"ssl\", False)),\n        ssl_options=ssl_options,\n        client_properties=client_properties,\n    )\n\n    super().__init__(\n        url=str(amqp_url),\n        protocol_version=protocol_version,\n        security=security,\n        ssl_context=security_args.get(\n            \"ssl_context\",\n            kwargs.pop(\"ssl_context\", None),\n        ),\n        **kwargs,\n    )\n\n    # respect ascynapi_url argument scheme\n    asyncapi_url = build_url(self.url)\n    self.protocol = protocol or asyncapi_url.scheme\n    self.virtual_host = asyncapi_url.path\n\n    self._max_consumers = max_consumers\n\n    self._channel = None\n    self.declarer = None\n    self._producer = None\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.declarer","title":"declarer instance-attribute","text":"
declarer: Optional[RabbitDeclarer] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[int, Handler]\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol or asyncapi_url.scheme\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.virtual_host","title":"virtual_host instance-attribute","text":"
virtual_host = asyncapi_url.path\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.connect","title":"connect async","text":"
connect(\n    *args: Any, **kwargs: Any\n) -> aio_pika.RobustConnection\n

Connect to the RabbitMQ server.

PARAMETER DESCRIPTION *args

Additional positional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION RobustConnection

aio_pika.RobustConnection: The RabbitMQ connection instance.

Source code in faststream/rabbit/broker.py
async def connect(self, *args: Any, **kwargs: Any) -> aio_pika.RobustConnection:\n    \"\"\"\n    Connect to the RabbitMQ server.\n\n    Args:\n        *args: Additional positional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        aio_pika.RobustConnection: The RabbitMQ connection instance.\n    \"\"\"\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.declare_exchange","title":"declare_exchange async","text":"
declare_exchange(\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange\n

Declare a RabbitMQ exchange.

PARAMETER DESCRIPTION exchange

The RabbitMQ exchange to declare.

TYPE: RabbitExchange

RETURNS DESCRIPTION RobustExchange

aio_pika.RobustExchange: The declared RabbitMQ exchange.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def declare_exchange(\n    self,\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange:\n    \"\"\"\n    Declare a RabbitMQ exchange.\n\n    Args:\n        exchange (RabbitExchange): The RabbitMQ exchange to declare.\n\n    Returns:\n        aio_pika.RobustExchange: The declared RabbitMQ exchange.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n    return await self.declarer.declare_exchange(exchange)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.declare_queue","title":"declare_queue async","text":"
declare_queue(queue: RabbitQueue) -> aio_pika.RobustQueue\n

Declare a RabbitMQ queue.

PARAMETER DESCRIPTION queue

The RabbitMQ queue to declare.

TYPE: RabbitQueue

RETURNS DESCRIPTION RobustQueue

aio_pika.RobustQueue: The declared RabbitMQ queue.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def declare_queue(\n    self,\n    queue: RabbitQueue,\n) -> aio_pika.RobustQueue:\n    \"\"\"\n    Declare a RabbitMQ queue.\n\n    Args:\n        queue (RabbitQueue): The RabbitMQ queue to declare.\n\n    Returns:\n        aio_pika.RobustQueue: The declared RabbitMQ queue.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n    return await self.declarer.declare_queue(queue)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, **kwargs: Any\n) -> Union[\n    aiormq.abc.ConfirmationFrameType, SendableMessage\n]\n

Publish a message to the RabbitMQ broker.

PARAMETER DESCRIPTION *args

Additional positional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Union[ConfirmationFrameType, SendableMessage]

Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The confirmation frame or the response message.

Source code in faststream/rabbit/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Union[aiormq.abc.ConfirmationFrameType, SendableMessage]:\n    \"\"\"\n    Publish a message to the RabbitMQ broker.\n\n    Args:\n        *args: Additional positional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The confirmation frame or the response message.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.publisher","title":"publisher","text":"
publisher(\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Publisher\n

Define a message publisher.

PARAMETER DESCRIPTION queue

The name of the RabbitMQ queue. Defaults to \"\".

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The name of the RabbitMQ exchange. Defaults to None.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key for messages. Defaults to \"\".

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory. Defaults to True.

TYPE: bool DEFAULT: True

immediate

Whether the message should be sent immediately. Defaults to False.

TYPE: bool DEFAULT: False

timeout

Timeout for message publishing. Defaults to None.

TYPE: TimeoutType DEFAULT: None

persist

Whether to persist messages. Defaults to False.

TYPE: bool DEFAULT: False

reply_to

The reply-to queue name. Defaults to None.

TYPE: Optional[str] DEFAULT: None

title

Title for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

description

Description for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional message properties and content.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Publisher

A message publisher instance.

TYPE: Publisher

Source code in faststream/rabbit/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Publisher:\n    \"\"\"\n    Define a message publisher.\n\n    Args:\n        queue (Union[RabbitQueue, str], optional): The name of the RabbitMQ queue. Defaults to \"\".\n        exchange (Union[RabbitExchange, str, None], optional): The name of the RabbitMQ exchange. Defaults to None.\n        routing_key (str, optional): The routing key for messages. Defaults to \"\".\n        mandatory (bool, optional): Whether the message is mandatory. Defaults to True.\n        immediate (bool, optional): Whether the message should be sent immediately. Defaults to False.\n        timeout (TimeoutType, optional): Timeout for message publishing. Defaults to None.\n        persist (bool, optional): Whether to persist messages. Defaults to False.\n        reply_to (Optional[str], optional): The reply-to queue name. Defaults to None.\n        title (Optional[str]): Title for AsyncAPI docs.\n        description (Optional[str]): Description for AsyncAPI docs.\n        **message_kwargs (Any): Additional message properties and content.\n\n    Returns:\n        Publisher: A message publisher instance.\n    \"\"\"\n    q, ex = RabbitQueue.validate(queue), RabbitExchange.validate(exchange)\n\n    publisher = Publisher(\n        title=title,\n        queue=q,\n        exchange=ex,\n        routing_key=routing_key,\n        mandatory=mandatory,\n        immediate=immediate,\n        timeout=timeout,\n        persist=persist,\n        reply_to=reply_to,\n        priority=priority,\n        message_kwargs=message_kwargs,\n        _description=description,\n        _schema=schema,\n        virtual_host=self.virtual_host,\n        include_in_schema=include_in_schema,\n    )\n\n    key = publisher._get_routing_hash()\n    publisher = self._publishers.get(key, publisher)\n    super().publisher(key, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.start","title":"start async","text":"
start() -> None\n

Start the RabbitMQ broker.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def start(self) -> None:\n    \"\"\"\n    Start the RabbitMQ broker.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, RabbitQueue(\"\"), RabbitExchange(\"\")),\n    )\n\n    await super().start()\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n\n    for publisher in self._publishers.values():\n        if publisher.exchange is not None:\n            await self.declare_exchange(publisher.exchange)\n\n    for handler in self.handlers.values():\n        c = self._get_log_context(None, handler.queue, handler.exchange)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self.declarer)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Filter[RabbitMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n

Decorator to define a message subscriber.

PARAMETER DESCRIPTION queue

The name of the RabbitMQ queue.

TYPE: Union[str, RabbitQueue]

exchange

The name of the RabbitMQ exchange. Defaults to None.

TYPE: Union[str, RabbitExchange, None] DEFAULT: None

consume_args

Additional arguments for message consumption.

TYPE: Optional[AnyDict] DEFAULT: None

no_ack

Whether not to ack/nack/reject messages.

TYPE: bool DEFAULT: False

title

Title for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

description

Description for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION Callable

A decorator function for defining message subscribers.

TYPE: Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn]]

Source code in faststream/rabbit/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[aio_pika.IncomingMessage, RabbitMessage]] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[aio_pika.IncomingMessage], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RabbitMessage] = default_filter,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"\n    Decorator to define a message subscriber.\n\n    Args:\n        queue (Union[str, RabbitQueue]): The name of the RabbitMQ queue.\n        exchange (Union[str, RabbitExchange, None], optional): The name of the RabbitMQ exchange. Defaults to None.\n        consume_args (Optional[AnyDict], optional): Additional arguments for message consumption.\n        no_ack (bool): Whether not to ack/nack/reject messages.\n        title (Optional[str]): Title for AsyncAPI docs.\n        description (Optional[str]): Description for AsyncAPI docs.\n\n    Returns:\n        Callable: A decorator function for defining message subscribers.\n    \"\"\"\n    super().subscriber()\n\n    r_queue = RabbitQueue.validate(queue)\n    r_exchange = RabbitExchange.validate(exchange)\n\n    self._setup_log_context(r_queue, r_exchange)\n\n    key = get_routing_hash(r_queue, r_exchange)\n    handler = self.handlers.get(\n        key,\n        Handler(\n            log_context_builder=partial(\n                self._get_log_context, queue=r_queue, exchange=r_exchange\n            ),\n            queue=r_queue,\n            exchange=r_exchange,\n            consume_args=consume_args,\n            description=description,\n            title=title,\n            virtual_host=self.virtual_host,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n        ),\n    )\n\n    self.handlers[key] = handler\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[\n        aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn\n    ]:\n        \"\"\"Wraps a consumer function with additional functionality.\n\n        Args:\n            func: The consumer function to be wrapped.\n\n        Returns:\n            The wrapped consumer function.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            _process_kwargs={\n                \"reply_config\": reply_config,\n            },\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/rabbit/fastapi/Context/#faststream.broker.fastapi.context.Context","title":"faststream.broker.fastapi.context.Context","text":"
Context(name: str) -> Any\n
Source code in faststream/broker/fastapi/context.py
def Context(name: str) -> Any:\n    return params.Depends(\n        lambda: context.resolve(name),\n        use_cache=True,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/","title":"RabbitRouter","text":"","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter","title":"faststream.rabbit.fastapi.RabbitRouter","text":"
RabbitRouter(\n    url: Union[\n        str, URL, None\n    ] = \"amqp://guest:guest@localhost:5672/\",\n    *,\n    host: str = \"localhost\",\n    port: int = 5672,\n    login: str = \"guest\",\n    password: str = \"guest\",\n    virtualhost: str = \"/\",\n    ssl_options: Optional[aio_pika.abc.SSLOptions] = None,\n    timeout: aio_pika.abc.TimeoutType = None,\n    client_properties: Optional[FieldTable] = None,\n    security: Optional[BaseSecurity] = None,\n    max_consumers: Optional[int] = None,\n    graceful_timeout: Optional[float] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    asyncapi_url: Optional[str] = None,\n    protocol: str = \"amqp\",\n    protocol_version: Optional[str] = \"0.9.1\",\n    description: Optional[str] = None,\n    asyncapi_tags: Optional[Sequence[asyncapi.Tag]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    setup_state: bool = True,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n)\n

Bases: StreamRouter[IncomingMessage]

A class to represent a RabbitMQ router for incoming messages.

METHOD DESCRIPTION _setup_log_context

sets up the log context for the main broker and the including broker

Source code in faststream/rabbit/fastapi.py
main_broker._setup_log_context(h.queue, h.exchange)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.broker","title":"broker instance-attribute","text":"
broker: RabbitBroker\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.broker_class","title":"broker_class class-attribute instance-attribute","text":"
broker_class: Type[RabbitBroker] = RB\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    queue: Union[str, RabbitQueue],\n    *,\n    endpoint: Callable[..., T_HandlerReturn],\n    exchange: Union[str, RabbitExchange, None] = None,\n    consume_args: Optional[AnyDict] = None,\n    dependencies: Sequence[params.Depends] = (),\n    filter: Filter[RabbitMessage] = default_filter,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    retry: Union[bool, int] = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    **__service_kwargs: Any\n) -> Callable[\n    [IncomingMessage, bool], Awaitable[T_HandlerReturn]\n]\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.publisher","title":"publisher","text":"
publisher(\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    headers: Optional[aio_pika.abc.HeadersType] = None,\n    content_type: Optional[str] = None,\n    content_encoding: Optional[str] = None,\n    priority: Optional[int] = None,\n    correlation_id: Optional[str] = None,\n    expiration: Optional[aio_pika.abc.DateType] = None,\n    message_id: Optional[str] = None,\n    timestamp: Optional[aio_pika.abc.DateType] = None,\n    type: Optional[str] = None,\n    user_id: Optional[str] = None,\n    app_id: Optional[str] = None\n) -> Publisher\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    dependencies: Sequence[params.Depends] = (),\n    filter: Filter[RabbitMessage] = default_filter,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    retry: Union[bool, int] = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/","title":"LogicHandler","text":"","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler","title":"faststream.rabbit.handler.LogicHandler","text":"
LogicHandler(\n    queue: RabbitQueue,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    exchange: Optional[RabbitExchange] = None,\n    consume_args: Optional[AnyDict] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    virtual_host: str = \"/\",\n)\n

Bases: AsyncHandler[IncomingMessage], BaseRMQInformation

A class to handle logic for RabbitMQ message consumption.

METHOD DESCRIPTION __init__

Initializes the LogicHandler object

add_call

Adds a call to be handled by the LogicHandler

start

Starts consuming messages from the queue

close

Closes the consumer and cancels message consumption

Initialize a RabbitMQ consumer.

PARAMETER DESCRIPTION queue

RabbitQueue object representing the queue to consume from

TYPE: RabbitQueue

exchange

RabbitExchange object representing the exchange to bind the queue to (optional)

TYPE: Optional[RabbitExchange] DEFAULT: None

consume_args

Additional arguments for consuming from the queue (optional)

TYPE: Optional[AnyDict] DEFAULT: None

description

Description of the consumer (optional)

TYPE: Optional[str] DEFAULT: None

title

Title of the consumer (optional)

TYPE: Optional[str] DEFAULT: None

Source code in faststream/rabbit/handler.py
def __init__(\n    self,\n    queue: RabbitQueue,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # RMQ information\n    exchange: Optional[RabbitExchange] = None,\n    consume_args: Optional[AnyDict] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    virtual_host: str = \"/\",\n) -> None:\n    \"\"\"Initialize a RabbitMQ consumer.\n\n    Args:\n        queue: RabbitQueue object representing the queue to consume from\n        exchange: RabbitExchange object representing the exchange to bind the queue to (optional)\n        consume_args: Additional arguments for consuming from the queue (optional)\n        description: Description of the consumer (optional)\n        title: Title of the consumer (optional)\n\n    \"\"\"\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.queue = queue\n    self.exchange = exchange\n    self.virtual_host = virtual_host\n    self.consume_args = consume_args or {}\n\n    self._consumer_tag = None\n    self._queue_obj = None\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.consume_args","title":"consume_args instance-attribute","text":"
consume_args: AnyDict = consume_args or {}\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.exchange","title":"exchange instance-attribute","text":"
exchange: Optional[RabbitExchange] = exchange\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.queue","title":"queue instance-attribute","text":"
queue: RabbitQueue = queue\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.virtual_host","title":"virtual_host instance-attribute","text":"
virtual_host = virtual_host\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ],\n    decoder: Optional[CustomDecoder[RabbitMessage]],\n    filter: Filter[RabbitMessage],\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ]\n) -> None\n

Add a call to the handler.

PARAMETER DESCRIPTION handler

The handler for the call.

TYPE: HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn]

dependant

The dependant for the call.

TYPE: CallModel[P_HandlerParams, T_HandlerReturn]

parser

Optional custom parser for the call.

TYPE: Optional[CustomParser[IncomingMessage, RabbitMessage]]

decoder

Optional custom decoder for the call.

TYPE: Optional[CustomDecoder[RabbitMessage]]

filter

The filter for the call.

TYPE: Filter[RabbitMessage]

middlewares

Optional sequence of middlewares for the call.

TYPE: Optional[Sequence[Callable[[IncomingMessage], BaseMiddleware]]]

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[\n        aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[aio_pika.IncomingMessage, RabbitMessage]],\n    decoder: Optional[CustomDecoder[RabbitMessage]],\n    filter: Filter[RabbitMessage],\n    middlewares: Optional[\n        Sequence[Callable[[aio_pika.IncomingMessage], BaseMiddleware]]\n    ],\n) -> None:\n    \"\"\"Add a call to the handler.\n\n    Args:\n        handler: The handler for the call.\n        dependant: The dependant for the call.\n        parser: Optional custom parser for the call.\n        decoder: Optional custom decoder for the call.\n        filter: The filter for the call.\n        middlewares: Optional sequence of middlewares for the call.\n\n    Returns:\n        None\n\n    \"\"\"\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, AioPikaParser.parse_message),\n        decoder=resolve_custom_func(decoder, AioPikaParser.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/rabbit/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self._queue_obj is not None:\n        if self._consumer_tag is not None:  # pragma: no branch\n            await self._queue_obj.cancel(self._consumer_tag)\n            self._consumer_tag = None\n        self._queue_obj = None\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.start","title":"start async","text":"
start(declarer: RabbitDeclarer) -> None\n

Starts the consumer for the RabbitMQ queue.

PARAMETER DESCRIPTION declarer

RabbitDeclarer object used to declare the queue and exchange

TYPE: RabbitDeclarer

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/handler.py
@override\nasync def start(self, declarer: RabbitDeclarer) -> None:  # type: ignore[override]\n    \"\"\"Starts the consumer for the RabbitMQ queue.\n\n    Args:\n        declarer: RabbitDeclarer object used to declare the queue and exchange\n\n    Returns:\n        None\n\n    \"\"\"\n    self._queue_obj = queue = await declarer.declare_queue(self.queue)\n\n    if self.exchange is not None:\n        exchange = await declarer.declare_exchange(self.exchange)\n        await queue.bind(\n            exchange,\n            routing_key=self.queue.routing,\n            arguments=self.queue.bind_arguments,\n        )\n\n    self._consumer_tag = await queue.consume(\n        # NOTE: aio-pika expects AbstractIncomingMessage, not IncomingMessage\n        self.consume,  # type: ignore[arg-type]\n        arguments=self.consume_args,\n    )\n\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/","title":"RabbitDeclarer","text":"","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer","title":"faststream.rabbit.helpers.RabbitDeclarer","text":"
RabbitDeclarer(channel: aio_pika.RobustChannel)\n

Bases: Singleton

A class to declare RabbitMQ queues and exchanges.

METHOD DESCRIPTION declare_queue

RabbitQueue) -> aio_pika.RobustQueue Declares a queue and returns the declared queue object.

declare_exchange

RabbitExchange) -> aio_pika.RobustExchange Declares an exchange and returns the declared exchange object.

Initialize the class.

PARAMETER DESCRIPTION channel

Aio_pika RobustChannel object

TYPE: RobustChannel

Source code in faststream/rabbit/helpers.py
def __init__(self, channel: aio_pika.RobustChannel) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        channel: Aio_pika RobustChannel object\n\n    Attributes:\n        channel: Aio_pika RobustChannel object\n        queues: A dictionary to store queues\n        exchanges: A dictionary to store exchanges\n\n    \"\"\"\n    self.channel = channel\n    self.queues = {}\n    self.exchanges = {}\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer.channel","title":"channel instance-attribute","text":"
channel: aio_pika.RobustChannel = channel\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer.exchanges","title":"exchanges instance-attribute","text":"
exchanges: Dict[\n    Union[RabbitExchange, str], aio_pika.RobustExchange\n] = {}\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer.queues","title":"queues instance-attribute","text":"
queues: Dict[\n    Union[RabbitQueue, str], aio_pika.RobustQueue\n] = {}\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer.declare_exchange","title":"declare_exchange async","text":"
declare_exchange(\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange\n

Declare an exchange.

PARAMETER DESCRIPTION exchange

RabbitExchange object representing the exchange to be declared.

TYPE: RabbitExchange

RETURNS DESCRIPTION RobustExchange

aio_pika.RobustExchange: The declared exchange.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/rabbit/helpers.py
async def declare_exchange(\n    self,\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange:\n    \"\"\"Declare an exchange.\n\n    Args:\n        exchange: RabbitExchange object representing the exchange to be declared.\n\n    Returns:\n        aio_pika.RobustExchange: The declared exchange.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    exch = self.exchanges.get(exchange)\n\n    if exch is None:\n        exch = cast(\n            aio_pika.RobustExchange,\n            await self.channel.declare_exchange(\n                **model_to_dict(\n                    exchange,\n                    exclude={\n                        \"routing_key\",\n                        \"bind_arguments\",\n                        \"bind_to\",\n                    },\n                )\n            ),\n        )\n        self.exchanges[exchange] = exch\n\n    if exchange.bind_to is not None:\n        parent = await self.declare_exchange(exchange.bind_to)\n        await exch.bind(\n            exchange=parent,\n            routing_key=exchange.routing_key,\n            arguments=exchange.arguments,\n        )\n\n    return exch\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer.declare_queue","title":"declare_queue async","text":"
declare_queue(queue: RabbitQueue) -> aio_pika.RobustQueue\n

Declare a queue.

PARAMETER DESCRIPTION queue

RabbitQueue object representing the queue to be declared.

TYPE: RabbitQueue

RETURNS DESCRIPTION RobustQueue

aio_pika.RobustQueue: The declared queue.

Source code in faststream/rabbit/helpers.py
async def declare_queue(\n    self,\n    queue: RabbitQueue,\n) -> aio_pika.RobustQueue:\n    \"\"\"Declare a queue.\n\n    Args:\n        queue: RabbitQueue object representing the queue to be declared.\n\n    Returns:\n        aio_pika.RobustQueue: The declared queue.\n\n    \"\"\"\n    q = self.queues.get(queue)\n    if q is None:\n        q = cast(\n            aio_pika.RobustQueue,\n            await self.channel.declare_queue(\n                **model_to_dict(\n                    queue,\n                    exclude={\n                        \"routing_key\",\n                        \"path_regex\",\n                        \"bind_arguments\",\n                    },\n                )\n            ),\n        )\n        self.queues[queue] = q\n    return q\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/","title":"RabbitMessage","text":"","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage","title":"faststream.rabbit.message.RabbitMessage","text":"

Bases: StreamMessage[IncomingMessage]

A message class for working with RabbitMQ messages.

This class extends StreamMessage to provide additional functionality for acknowledging, rejecting, or nack-ing RabbitMQ messages.

METHOD DESCRIPTION ack

Acknowledge the RabbitMQ message.

nack

Negative Acknowledgment of the RabbitMQ message.

reject

Reject the RabbitMQ message.

","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.ack","title":"ack async","text":"
ack(**kwargs: Any) -> None\n

Acknowledge the RabbitMQ message.

Acknowledgment indicates that the message has been successfully processed.

PARAMETER DESCRIPTION **kwargs

Additional keyword arguments (not used).

TYPE: Any DEFAULT: {}

Source code in faststream/rabbit/message.py
async def ack(self, **kwargs: Any) -> None:\n    \"\"\"\n    Acknowledge the RabbitMQ message.\n\n    Acknowledgment indicates that the message has been successfully processed.\n\n    Args:\n        **kwargs (Any): Additional keyword arguments (not used).\n\n    \"\"\"\n    pika_message = self.raw_message\n    await super().ack()\n    if (\n        pika_message._IncomingMessage__processed  # type: ignore[attr-defined]\n        or pika_message._IncomingMessage__no_ack  # type: ignore[attr-defined]\n    ):\n        return\n    await pika_message.ack()\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.nack","title":"nack async","text":"
nack(**kwargs: Any) -> None\n

Negative Acknowledgment of the RabbitMQ message.

Nack-ing a message indicates that the message processing has failed and should be requeued.

PARAMETER DESCRIPTION **kwargs

Additional keyword arguments (not used).

TYPE: Any DEFAULT: {}

Source code in faststream/rabbit/message.py
async def nack(self, **kwargs: Any) -> None:\n    \"\"\"\n    Negative Acknowledgment of the RabbitMQ message.\n\n    Nack-ing a message indicates that the message processing has failed and should be requeued.\n\n    Args:\n        **kwargs (Any): Additional keyword arguments (not used).\n\n    \"\"\"\n    pika_message = self.raw_message\n    await super().nack()\n    if (\n        pika_message._IncomingMessage__processed  # type: ignore[attr-defined]\n        or pika_message._IncomingMessage__no_ack  # type: ignore[attr-defined]\n    ):\n        return\n    await pika_message.nack()\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.reject","title":"reject async","text":"
reject(**kwargs: Any) -> None\n

Reject the RabbitMQ message.

Rejecting a message indicates that the message processing has failed, and it should not be requeued.

PARAMETER DESCRIPTION **kwargs

Additional keyword arguments (not used).

TYPE: Any DEFAULT: {}

Source code in faststream/rabbit/message.py
async def reject(self, **kwargs: Any) -> None:\n    \"\"\"\n    Reject the RabbitMQ message.\n\n    Rejecting a message indicates that the message processing has failed, and it should not be requeued.\n\n    Args:\n        **kwargs (Any): Additional keyword arguments (not used).\n\n    \"\"\"\n    pika_message = self.raw_message\n    await super().reject()\n    if (\n        pika_message._IncomingMessage__processed  # type: ignore[attr-defined]\n        or pika_message._IncomingMessage__no_ack  # type: ignore[attr-defined]\n    ):\n        return\n    await pika_message.reject()\n
","boost":0.5},{"location":"api/faststream/rabbit/parser/AioPikaParser/","title":"AioPikaParser","text":"","boost":0.5},{"location":"api/faststream/rabbit/parser/AioPikaParser/#faststream.rabbit.parser.AioPikaParser","title":"faststream.rabbit.parser.AioPikaParser","text":"

A class for parsing, encoding, and decoding messages using aio-pika.

METHOD DESCRIPTION parse_message

aio_pika.IncomingMessage) -> StreamMessage[aio_pika.IncomingMessage]: Parses an incoming message and returns a StreamMessage object.

decode_message

StreamMessage[aio_pika.IncomingMessage]) -> DecodedMessage: Decodes a StreamMessage object and returns a DecodedMessage object.

encode_message

AioPikaSendableMessage, persist: bool = False, callback_queue: Optional[aio_pika.abc.AbstractRobustQueue] = None, reply_to: Optional[str] = None, **message_kwargs: Any) -> aio_pika.Message: Encodes a message into an aio_pika.Message object.

","boost":0.5},{"location":"api/faststream/rabbit/parser/AioPikaParser/#faststream.rabbit.parser.AioPikaParser.decode_message","title":"decode_message async staticmethod","text":"
decode_message(\n    msg: StreamMessage[aio_pika.IncomingMessage],\n) -> DecodedMessage\n

Decode a message.

PARAMETER DESCRIPTION msg

The message to decode.

TYPE: StreamMessage[IncomingMessage]

RETURNS DESCRIPTION DecodedMessage

The decoded message.

Source code in faststream/rabbit/parser.py
@staticmethod\nasync def decode_message(\n    msg: StreamMessage[aio_pika.IncomingMessage],\n) -> DecodedMessage:\n    \"\"\"Decode a message.\n\n    Args:\n        msg: The message to decode.\n\n    Returns:\n        The decoded message.\n\n    \"\"\"\n    return decode_message(msg)\n
","boost":0.5},{"location":"api/faststream/rabbit/parser/AioPikaParser/#faststream.rabbit.parser.AioPikaParser.encode_message","title":"encode_message staticmethod","text":"
encode_message(\n    message: AioPikaSendableMessage,\n    persist: bool = False,\n    callback_queue: Optional[\n        aio_pika.abc.AbstractRobustQueue\n    ] = None,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any\n) -> aio_pika.Message\n

Encodes a message for sending using AioPika.

PARAMETER DESCRIPTION message

The message to encode.

TYPE: AioPikaSendableMessage

persist

Whether to persist the message. Defaults to False.

TYPE: bool DEFAULT: False

callback_queue

The callback queue to use for replies. Defaults to None.

TYPE: AbstractRobustQueue DEFAULT: None

reply_to

The reply-to queue to use for replies. Defaults to None.

TYPE: str DEFAULT: None

**message_kwargs

Additional keyword arguments to include in the encoded message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Message

aio_pika.Message: The encoded message.

RAISES DESCRIPTION NotImplementedError

If the message is not an instance of aio_pika.Message.

Source code in faststream/rabbit/parser.py
@staticmethod\ndef encode_message(\n    message: AioPikaSendableMessage,\n    persist: bool = False,\n    callback_queue: Optional[aio_pika.abc.AbstractRobustQueue] = None,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any,\n) -> aio_pika.Message:\n    \"\"\"Encodes a message for sending using AioPika.\n\n    Args:\n        message (AioPikaSendableMessage): The message to encode.\n        persist (bool, optional): Whether to persist the message. Defaults to False.\n        callback_queue (aio_pika.abc.AbstractRobustQueue, optional): The callback queue to use for replies. Defaults to None.\n        reply_to (str, optional): The reply-to queue to use for replies. Defaults to None.\n        **message_kwargs (Any): Additional keyword arguments to include in the encoded message.\n\n    Returns:\n        aio_pika.Message: The encoded message.\n\n    Raises:\n        NotImplementedError: If the message is not an instance of aio_pika.Message.\n\n    \"\"\"\n    if isinstance(message, aio_pika.Message):\n        return message\n\n    else:\n        message, content_type = encode_message(message)\n\n        delivery_mode = (\n            DeliveryMode.PERSISTENT if persist else DeliveryMode.NOT_PERSISTENT\n        )\n\n        return aio_pika.Message(\n            message,\n            **{\n                \"delivery_mode\": delivery_mode,\n                \"content_type\": content_type,\n                \"reply_to\": callback_queue or reply_to,\n                \"correlation_id\": str(uuid4()),\n                **message_kwargs,\n            },\n        )\n
","boost":0.5},{"location":"api/faststream/rabbit/parser/AioPikaParser/#faststream.rabbit.parser.AioPikaParser.parse_message","title":"parse_message async staticmethod","text":"
parse_message(\n    message: aio_pika.IncomingMessage,\n) -> StreamMessage[aio_pika.IncomingMessage]\n

Parses an incoming message and returns a RabbitMessage object.

PARAMETER DESCRIPTION message

The incoming message to parse.

TYPE: IncomingMessage

RETURNS DESCRIPTION StreamMessage[IncomingMessage]

A StreamMessage object representing the parsed message.

Source code in faststream/rabbit/parser.py
@staticmethod\nasync def parse_message(\n    message: aio_pika.IncomingMessage,\n) -> StreamMessage[aio_pika.IncomingMessage]:\n    \"\"\"Parses an incoming message and returns a RabbitMessage object.\n\n    Args:\n        message: The incoming message to parse.\n\n    Returns:\n        A StreamMessage object representing the parsed message.\n\n    \"\"\"\n    handler = context.get_local(\"handler_\")\n    path: AnyDict = {}\n    path_re: Optional[Pattern[str]]\n    if (\n        handler\n        and (path_re := handler.queue.path_regex) is not None\n        and (match := path_re.match(message.routing_key or \"\")) is not None\n    ):\n        path = match.groupdict()\n\n    return RabbitMessage(\n        body=message.body,\n        headers=message.headers,\n        reply_to=message.reply_to or \"\",\n        content_type=message.content_type,\n        message_id=message.message_id or str(uuid4()),\n        correlation_id=message.correlation_id or str(uuid4()),\n        path=path,\n        raw_message=message,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/producer/AioPikaFastProducer/","title":"AioPikaFastProducer","text":"","boost":0.5},{"location":"api/faststream/rabbit/producer/AioPikaFastProducer/#faststream.rabbit.producer.AioPikaFastProducer","title":"faststream.rabbit.producer.AioPikaFastProducer","text":"
AioPikaFastProducer(\n    channel: aio_pika.RobustChannel,\n    declarer: RabbitDeclarer,\n    parser: Optional[\n        AsyncCustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ],\n    decoder: Optional[AsyncCustomDecoder[RabbitMessage]],\n)\n

A class for fast producing messages using aio-pika.

METHOD DESCRIPTION publish

Publishes a message to a queue or exchange.

_publish

Publishes a message to an exchange.

Note: This docstring is incomplete as it is difficult to understand the purpose and functionality of the class and its methods without more context.

Initialize a class instance.

PARAMETER DESCRIPTION channel

The aio_pika.RobustChannel object.

TYPE: RobustChannel

declarer

The RabbitDeclarer object.

TYPE: RabbitDeclarer

parser

An optional AsyncCustomParser object for parsing incoming messages.

TYPE: Optional[AsyncCustomParser[IncomingMessage, RabbitMessage]]

decoder

An optional AsyncCustomDecoder object for decoding incoming messages.

TYPE: Optional[AsyncCustomDecoder[RabbitMessage]]

Source code in faststream/rabbit/producer.py
def __init__(\n    self,\n    channel: aio_pika.RobustChannel,\n    declarer: RabbitDeclarer,\n    parser: Optional[AsyncCustomParser[aio_pika.IncomingMessage, RabbitMessage]],\n    decoder: Optional[AsyncCustomDecoder[RabbitMessage]],\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        channel: The aio_pika.RobustChannel object.\n        declarer: The RabbitDeclarer object.\n        parser: An optional AsyncCustomParser object for parsing incoming messages.\n        decoder: An optional AsyncCustomDecoder object for decoding incoming messages.\n\n    \"\"\"\n    self._channel = channel\n    self.declarer = declarer\n    self._parser = resolve_custom_func(parser, AioPikaParser.parse_message)\n    self._decoder = resolve_custom_func(decoder, AioPikaParser.decode_message)\n    self._rpc_lock = anyio.Lock()\n
","boost":0.5},{"location":"api/faststream/rabbit/producer/AioPikaFastProducer/#faststream.rabbit.producer.AioPikaFastProducer.declarer","title":"declarer instance-attribute","text":"
declarer: RabbitDeclarer = declarer\n
","boost":0.5},{"location":"api/faststream/rabbit/producer/AioPikaFastProducer/#faststream.rabbit.producer.AioPikaFastProducer.publish","title":"publish async","text":"
publish(\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any\n) -> Union[\n    aiormq.abc.ConfirmationFrameType, SendableMessage\n]\n

Publish a message to a RabbitMQ queue.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: AioPikaSendableMessage DEFAULT: ''

queue

The queue to publish the message to.

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The exchange to publish the message to.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key for the message.

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory.

TYPE: bool DEFAULT: True

immediate

Whether the message should be delivered immediately.

TYPE: bool DEFAULT: False

timeout

The timeout for the operation.

TYPE: TimeoutType DEFAULT: None

rpc

Whether the message is for RPC.

TYPE: bool DEFAULT: False

rpc_timeout

The timeout for RPC.

TYPE: Optional[float] DEFAULT: 30.0

raise_timeout

Whether to raise an exception on timeout.

TYPE: bool DEFAULT: False

persist

Whether the message should be persisted.

TYPE: bool DEFAULT: False

reply_to

The reply-to queue for RPC.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional keyword arguments for the message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Union[ConfirmationFrameType, SendableMessage]

Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The result of the publish operation.

RAISES DESCRIPTION WRONG_PUBLISH_ARGS

If reply_to is not None when rpc is True.

Source code in faststream/rabbit/producer.py
async def publish(\n    self,\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any,\n) -> Union[aiormq.abc.ConfirmationFrameType, SendableMessage]:\n    \"\"\"Publish a message to a RabbitMQ queue.\n\n    Args:\n        message (AioPikaSendableMessage): The message to be published.\n        queue (Union[RabbitQueue, str]): The queue to publish the message to.\n        exchange (Union[RabbitExchange, str, None]): The exchange to publish the message to.\n        routing_key (str): The routing key for the message.\n        mandatory (bool): Whether the message is mandatory.\n        immediate (bool): Whether the message should be delivered immediately.\n        timeout (TimeoutType): The timeout for the operation.\n        rpc (bool): Whether the message is for RPC.\n        rpc_timeout (Optional[float]): The timeout for RPC.\n        raise_timeout (bool): Whether to raise an exception on timeout.\n        persist (bool): Whether the message should be persisted.\n        reply_to (Optional[str]): The reply-to queue for RPC.\n        **message_kwargs (Any): Additional keyword arguments for the message.\n\n    Returns:\n        Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The result of the publish operation.\n\n    Raises:\n        WRONG_PUBLISH_ARGS: If reply_to is not None when rpc is True.\n\n    \"\"\"\n    p_queue = RabbitQueue.validate(queue)\n\n    context: AsyncContextManager[\n        Optional[MemoryObjectReceiveStream[aio_pika.IncomingMessage]]\n    ]\n    if rpc is True:\n        if reply_to is not None:\n            raise WRONG_PUBLISH_ARGS\n        else:\n            context = _RPCCallback(\n                self._rpc_lock,\n                self.declarer.queues[RABBIT_REPLY],\n            )\n    else:\n        context = fake_context()\n\n    async with context as response_queue:\n        r = await self._publish(\n            message=message,\n            exchange=exchange,\n            routing_key=routing_key or p_queue.routing or \"\",\n            mandatory=mandatory,\n            immediate=immediate,\n            timeout=timeout,\n            persist=persist,\n            reply_to=RABBIT_REPLY if response_queue else reply_to,\n            **message_kwargs,\n        )\n\n        if response_queue is None:\n            return r\n\n        else:\n            msg: Optional[aio_pika.IncomingMessage] = None\n            with timeout_scope(rpc_timeout, raise_timeout):\n                msg = await response_queue.receive()\n\n            if msg:  # pragma: no branch\n                return await self._decoder(await self._parser(msg))\n\n    return None\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/","title":"LogicPublisher","text":"","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher","title":"faststream.rabbit.publisher.LogicPublisher dataclass","text":"

Bases: ABCPublisher[IncomingMessage]

A class to publish messages for logic processing.

METHOD DESCRIPTION publish

Publishes a message for logic processing.

","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.exchange","title":"exchange class-attribute instance-attribute","text":"
exchange: Optional[RabbitExchange] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.immediate","title":"immediate class-attribute instance-attribute","text":"
immediate: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.message_kwargs","title":"message_kwargs class-attribute instance-attribute","text":"
message_kwargs: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.persist","title":"persist class-attribute instance-attribute","text":"
persist: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.priority","title":"priority class-attribute instance-attribute","text":"
priority: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.queue","title":"queue class-attribute instance-attribute","text":"
queue: RabbitQueue = field(default=RabbitQueue(''))\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.routing","title":"routing property","text":"
routing: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.virtual_host","title":"virtual_host class-attribute instance-attribute","text":"
virtual_host: str = '/'\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/rabbit/publisher.py
Methods:\n    publish : Publishes a message for logic processing.\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.publish","title":"publish async","text":"
publish(\n    message: AioPikaSendableMessage = \"\",\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    correlation_id: Optional[str] = None,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Union[\n    aiormq.abc.ConfirmationFrameType, SendableMessage\n]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: AioPikaSendableMessage DEFAULT: ''

rpc

Whether the message is for RPC (Remote Procedure Call).

TYPE: bool DEFAULT: False

rpc_timeout

Timeout for RPC.

TYPE: Optional[float] DEFAULT: 30.0

raise_timeout

Whether to raise an exception if timeout occurs.

TYPE: bool DEFAULT: False

correlation_id

Correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional keyword arguments for the message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Union[ConfirmationFrameType, SendableMessage]

ConfirmationFrameType or SendableMessage: The result of the publish operation.

RAISES DESCRIPTION AssertionError

If _producer is not set up.

Source code in faststream/rabbit/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: AioPikaSendableMessage = \"\",\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    correlation_id: Optional[str] = None,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Union[aiormq.abc.ConfirmationFrameType, SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        rpc: Whether the message is for RPC (Remote Procedure Call).\n        rpc_timeout: Timeout for RPC.\n        raise_timeout: Whether to raise an exception if timeout occurs.\n        correlation_id: Correlation ID for the message.\n        **message_kwargs: Additional keyword arguments for the message.\n\n    Returns:\n        ConfirmationFrameType or SendableMessage: The result of the publish operation.\n\n    Raises:\n        AssertionError: If `_producer` is not set up.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(\n        message=message,\n        exchange=self.exchange,\n        routing_key=self.routing,\n        mandatory=self.mandatory,\n        immediate=self.immediate,\n        timeout=self.timeout,\n        rpc=rpc,\n        rpc_timeout=rpc_timeout,\n        raise_timeout=raise_timeout,\n        persist=self.persist,\n        reply_to=self.reply_to,\n        correlation_id=correlation_id,\n        priority=priority or self.priority,\n        **self.message_kwargs,\n        **message_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/","title":"RabbitRouter","text":"","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter","title":"faststream.rabbit.router.RabbitRouter","text":"
RabbitRouter(\n    prefix: str = \"\",\n    handlers: Sequence[RabbitRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: RabbitRouter

A class representing a RabbitMQ router for publishing messages.

METHOD DESCRIPTION _get_publisher_key

Returns the key for a given Publisher object

_update_publisher_prefix

Updates the prefix of a given Publisher object

publisher

Publishes a message to RabbitMQ

Source code in faststream/rabbit/router.py
_publishers: Dict[int, Publisher]\n\n@staticmethod\ndef _get_publisher_key(publisher: Publisher) -> int:\n    \"\"\"Get the publisher key.\n\n    Args:\n        publisher: The publisher object.\n\n    Returns:\n        The publisher key as an integer.\n\n    \"\"\"\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.publisher","title":"publisher","text":"
publisher(\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Publisher\n

Publishes a message to a RabbitMQ queue or exchange.

PARAMETER DESCRIPTION queue

The RabbitMQ queue to publish the message to. Can be either a RabbitQueue object or a string representing the queue name.

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The RabbitMQ exchange to publish the message to. Can be either a RabbitExchange object, a string representing the exchange name, or None.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key to use when publishing the message.

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory or not.

TYPE: bool DEFAULT: True

immediate

Whether the message should be delivered immediately or not.

TYPE: bool DEFAULT: False

timeout

The timeout for the publish operation.

TYPE: TimeoutType DEFAULT: None

persist

Whether the message should be persisted or not.

TYPE: bool DEFAULT: False

reply_to

The reply-to address for the message.

TYPE: Optional[str] DEFAULT: None

title

The title of the message (AsyncAPI information).

TYPE: Optional[str] DEFAULT: None

description

The description of the message (AsyncAPI information).

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional keyword arguments to include in the message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Publisher

The Publisher object used to publish the message.

Source code in faststream/rabbit/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Publisher:\n    \"\"\"Publishes a message to a RabbitMQ queue or exchange.\n\n    Args:\n        queue: The RabbitMQ queue to publish the message to. Can be either a RabbitQueue object or a string representing the queue name.\n        exchange: The RabbitMQ exchange to publish the message to. Can be either a RabbitExchange object, a string representing the exchange name, or None.\n        routing_key: The routing key to use when publishing the message.\n        mandatory: Whether the message is mandatory or not.\n        immediate: Whether the message should be delivered immediately or not.\n        timeout: The timeout for the publish operation.\n        persist: Whether the message should be persisted or not.\n        reply_to: The reply-to address for the message.\n        title: The title of the message (AsyncAPI information).\n        description: The description of the message (AsyncAPI information).\n        **message_kwargs: Additional keyword arguments to include in the message.\n\n    Returns:\n        The Publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            queue=RabbitQueue.validate(queue),\n            exchange=RabbitExchange.validate(exchange),\n            routing_key=routing_key,\n            mandatory=mandatory,\n            immediate=immediate,\n            timeout=timeout,\n            persist=persist,\n            reply_to=reply_to,\n            priority=priority,\n            message_kwargs=message_kwargs,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[key] = self._publishers.get(key, new_publisher)\n    return publisher\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    dependencies: Sequence[Depends] = (),\n    filter: Filter[RabbitMessage] = default_filter,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    retry: Union[bool, int] = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n
Source code in faststream/rabbit/router.py
    Returns:\n        Publisher: The updated publisher object.\n\n    Note:\n        This function is intended to be used as a decorator.\n\n    \"\"\"\n    publisher.queue = model_copy(\n        publisher.queue, update={\"name\": prefix + publisher.queue.name}\n    )\n    return publisher\n\n@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n
","boost":0.5},{"location":"api/faststream/rabbit/security/parse_security/","title":"parse_security","text":"","boost":0.5},{"location":"api/faststream/rabbit/security/parse_security/#faststream.rabbit.security.parse_security","title":"faststream.rabbit.security.parse_security","text":"
parse_security(security: Optional[BaseSecurity]) -> AnyDict\n
Source code in faststream/rabbit/security.py
def parse_security(security: Optional[BaseSecurity]) -> AnyDict:\n    if security is None:\n        return {}\n    elif isinstance(security, SASLPlaintext):\n        return _parse_sasl_plaintext(security)\n    elif isinstance(security, BaseSecurity):\n        return _parse_base_security(security)\n    else:\n        raise NotImplementedError(f\"RabbitBroker does not support {type(security)}\")\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/","title":"ExchangeType","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType","title":"faststream.rabbit.shared.constants.ExchangeType","text":"

Bases: str, Enum

A class to represent the exchange type.

","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.DIRECT","title":"DIRECT class-attribute instance-attribute","text":"
DIRECT = 'direct'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.FANOUT","title":"FANOUT class-attribute instance-attribute","text":"
FANOUT = 'fanout'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.HEADERS","title":"HEADERS class-attribute instance-attribute","text":"
HEADERS = 'headers'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.TOPIC","title":"TOPIC class-attribute instance-attribute","text":"
TOPIC = 'topic'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.X_CONSISTENT_HASH","title":"X_CONSISTENT_HASH class-attribute instance-attribute","text":"
X_CONSISTENT_HASH = 'x-consistent-hash'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.X_DELAYED_MESSAGE","title":"X_DELAYED_MESSAGE class-attribute instance-attribute","text":"
X_DELAYED_MESSAGE = 'x-delayed-message'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.X_MODULUS_HASH","title":"X_MODULUS_HASH class-attribute instance-attribute","text":"
X_MODULUS_HASH = 'x-modulus-hash'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/logging/RabbitLoggingMixin/","title":"RabbitLoggingMixin","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/logging/RabbitLoggingMixin/#faststream.rabbit.shared.logging.RabbitLoggingMixin","title":"faststream.rabbit.shared.logging.RabbitLoggingMixin","text":"
RabbitLoggingMixin(\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any\n)\n

Bases: LoggingMixin

A class that extends the LoggingMixin class and adds additional functionality for logging RabbitMQ related information.

METHOD DESCRIPTION __init__

Initializes the RabbitLoggingMixin object.

_get_log_context

Overrides the _get_log_context method of the LoggingMixin class to include RabbitMQ related context information.

fmt

Returns the log format string.

_setup_log_context

Sets up the log context by updating the maximum lengths of the queue and exchange names.

Initialize the class.

PARAMETER DESCRIPTION *args

Variable length argument list

TYPE: Any DEFAULT: ()

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: access_logger

log_level

Logging level

TYPE: int DEFAULT: INFO

log_fmt

Optional log format

TYPE: Optional[str] DEFAULT: None

**kwargs

Arbitrary keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/shared/logging.py
def __init__(\n    self,\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        *args: Variable length argument list\n        logger: Optional logger object\n        log_level: Logging level\n        log_fmt: Optional log format\n        **kwargs: Arbitrary keyword arguments\n\n    Returns:\n        None\n\n    \"\"\"\n    super().__init__(\n        *args,\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n        **kwargs,\n    )\n    self._max_queue_len = 4\n    self._max_exchange_len = 4\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/logging/RabbitLoggingMixin/#faststream.rabbit.shared.logging.RabbitLoggingMixin.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/logging/RabbitLoggingMixin/#faststream.rabbit.shared.logging.RabbitLoggingMixin.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/logging/RabbitLoggingMixin/#faststream.rabbit.shared.logging.RabbitLoggingMixin.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/","title":"ABCPublisher","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher","title":"faststream.rabbit.shared.publisher.ABCPublisher dataclass","text":"

Bases: ABC, BasePublisher[MsgType], BaseRMQInformation

A class representing an ABCPublisher.

","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.exchange","title":"exchange class-attribute instance-attribute","text":"
exchange: Optional[RabbitExchange] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.immediate","title":"immediate class-attribute instance-attribute","text":"
immediate: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.message_kwargs","title":"message_kwargs class-attribute instance-attribute","text":"
message_kwargs: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.persist","title":"persist class-attribute instance-attribute","text":"
persist: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.priority","title":"priority class-attribute instance-attribute","text":"
priority: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.queue","title":"queue class-attribute instance-attribute","text":"
queue: RabbitQueue = field(default=RabbitQueue(''))\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.virtual_host","title":"virtual_host class-attribute instance-attribute","text":"
virtual_host: str = '/'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.publish","title":"publish abstractmethod async","text":"
publish(\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

correlation_id

Optional correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/publisher.py
@abstractmethod\nasync def publish(\n    self,\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        correlation_id: Optional correlation ID for the message.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRoute/","title":"RabbitRoute","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/","title":"RabbitRouter","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter","title":"faststream.rabbit.shared.router.RabbitRouter","text":"
RabbitRouter(\n    prefix: str = \"\",\n    handlers: Sequence[\n        RabbitRoute[IncomingMessage, SendableMessage]\n    ] = (),\n    **kwargs: Any\n)\n

Bases: BrokerRouter[int, IncomingMessage]

A class representing a RabbitMQ router for handling incoming messages.

METHOD DESCRIPTION __init__

initializes the RabbitRouter object

subscriber

decorator for subscribing to a queue and registering a handler function

Override the __init__ method of the parent class.

PARAMETER DESCRIPTION prefix

A prefix string

TYPE: str DEFAULT: ''

handlers

A sequence of RabbitRoute objects

TYPE: Sequence[BrokerRoute[IncomingMessage, SendableMessage]] DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported

Source code in faststream/rabbit/shared/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[RabbitRoute[IncomingMessage, SendableMessage]] = (),\n    **kwargs: Any,\n) -> None:\n    \"\"\"Override the `__init__` method of the parent class.\n\n    Args:\n        prefix: A prefix string\n        handlers: A sequence of RabbitRoute objects\n        **kwargs: Additional keyword arguments\n\n    Raises:\n        NotImplementedError: If silent animals are not supported\n\n    \"\"\"\n    for h in handlers:\n        if (q := h.kwargs.pop(\"queue\", None)) is None:\n            q, h.args = h.args[0], h.args[1:]\n        queue = RabbitQueue.validate(q)\n        new_q = model_copy(queue, update={\"name\": prefix + queue.name})\n        h.args = (new_q, *h.args)\n\n    super().__init__(prefix, handlers, **kwargs)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    *broker_args: Any,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        IncomingMessage, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function to subscribe to a RabbitMQ queue.

PARAMETER DESCRIPTION self

the instance of the class

queue

the queue to subscribe to, can be a string or a RabbitQueue object

*broker_args

additional arguments for the broker

DEFAULT: ()

**broker_kwargs

additional keyword arguments for the broker

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn]]

A callable object that wraps the handler function for the incoming messages from the queue.

RAISES DESCRIPTION TypeError

If the queue is not a string or a RabbitQueue object

Source code in faststream/rabbit/shared/router.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    queue: Union[str, RabbitQueue],\n    *broker_args: Any,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function to subscribe to a RabbitMQ queue.\n\n    Args:\n        self : the instance of the class\n        queue : the queue to subscribe to, can be a string or a RabbitQueue object\n        *broker_args : additional arguments for the broker\n        **broker_kwargs : additional keyword arguments for the broker\n\n    Returns:\n        A callable object that wraps the handler function for the incoming messages from the queue.\n\n    Raises:\n        TypeError: If the queue is not a string or a RabbitQueue object\n\n    \"\"\"\n    q = RabbitQueue.validate(queue)\n    new_q = model_copy(q, update={\"name\": self.prefix + q.name})\n    return self._wrap_subscriber(new_q, *broker_args, **broker_kwargs)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/BaseRMQInformation/","title":"BaseRMQInformation","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/BaseRMQInformation/#faststream.rabbit.shared.schemas.BaseRMQInformation","title":"faststream.rabbit.shared.schemas.BaseRMQInformation dataclass","text":"

BaseRMQInformation.

","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/BaseRMQInformation/#faststream.rabbit.shared.schemas.BaseRMQInformation.exchange","title":"exchange class-attribute instance-attribute","text":"
exchange: Optional[RabbitExchange] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/BaseRMQInformation/#faststream.rabbit.shared.schemas.BaseRMQInformation.queue","title":"queue class-attribute instance-attribute","text":"
queue: RabbitQueue = field(default=RabbitQueue(''))\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/BaseRMQInformation/#faststream.rabbit.shared.schemas.BaseRMQInformation.virtual_host","title":"virtual_host class-attribute instance-attribute","text":"
virtual_host: str = '/'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/","title":"RabbitExchange","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange","title":"faststream.rabbit.shared.schemas.RabbitExchange","text":"
RabbitExchange(\n    name: str,\n    type: ExchangeType = ExchangeType.DIRECT,\n    durable: bool = False,\n    auto_delete: bool = False,\n    internal: bool = False,\n    passive: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_to: Optional[RabbitExchange] = None,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n)\n

Bases: NameRequired

A class to represent a RabbitMQ exchange.

METHOD DESCRIPTION __hash__

returns the hash value of the exchange

__init__

initializes the RabbitExchange object

Initialize a RabbitExchange object.

PARAMETER DESCRIPTION name

Name of the exchange.

TYPE: str

type

Type of the exchange. Defaults to ExchangeType.DIRECT.

TYPE: ExchangeType DEFAULT: DIRECT

durable

Whether the exchange should survive broker restarts. Defaults to False.

TYPE: bool DEFAULT: False

auto_delete

Whether the exchange should be deleted when no longer in use. Defaults to False.

TYPE: bool DEFAULT: False

internal

Whether the exchange is used for internal purposes and should not be published to directly. Defaults to False.

TYPE: bool DEFAULT: False

passive

Whether to check if the exchange exists before creating it. Defaults to False.

TYPE: bool DEFAULT: False

arguments

Additional arguments for the exchange. Defaults to None.

TYPE: Optional[AnyDict] DEFAULT: None

timeout

Timeout for the operation. Defaults to None.

TYPE: TimeoutType DEFAULT: None

robust

Whether to use robust mode for the exchange. Defaults to True.

TYPE: bool DEFAULT: True

bind_to

Exchange to bind to. Defaults to None.

TYPE: Optional[RabbitExchange] DEFAULT: None

bind_arguments

Arguments for the binding. Defaults to None.

TYPE: Optional[AnyDict] DEFAULT: None

routing_key

Routing key for the exchange. Defaults to \"\".

TYPE: str DEFAULT: ''

RAISES DESCRIPTION NotImplementedError Source code in faststream/rabbit/shared/schemas.py
def __init__(\n    self,\n    name: str,\n    type: ExchangeType = ExchangeType.DIRECT,\n    durable: bool = False,\n    auto_delete: bool = False,\n    internal: bool = False,\n    passive: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_to: Optional[\"RabbitExchange\"] = None,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n) -> None:\n    \"\"\"Initialize a RabbitExchange object.\n\n    Args:\n        name (str): Name of the exchange.\n        type (ExchangeType, optional): Type of the exchange. Defaults to ExchangeType.DIRECT.\n        durable (bool, optional): Whether the exchange should survive broker restarts. Defaults to False.\n        auto_delete (bool, optional): Whether the exchange should be deleted when no longer in use. Defaults to False.\n        internal (bool, optional): Whether the exchange is used for internal purposes and should not be published to directly. Defaults to False.\n        passive (bool, optional): Whether to check if the exchange exists before creating it. Defaults to False.\n        arguments (Optional[AnyDict], optional): Additional arguments for the exchange. Defaults to None.\n        timeout (TimeoutType, optional): Timeout for the operation. Defaults to None.\n        robust (bool, optional): Whether to use robust mode for the exchange. Defaults to True.\n        bind_to (Optional[\"RabbitExchange\"], optional): Exchange to bind to. Defaults to None.\n        bind_arguments (Optional[AnyDict], optional): Arguments for the binding. Defaults to None.\n        routing_key (str, optional): Routing key for the exchange. Defaults to \"\".\n\n    Raises:\n        NotImplementedError:\n\n    \"\"\"\n    if routing_key and bind_to is None:  # pragma: no cover\n        warnings.warn(\n            (\n                \"\\nRabbitExchange `routing_key` is using to bind exchange to another one\"\n                \"\\nIt can be used only with the `bind_to` argument, please setup it too\"\n            ),\n            category=RuntimeWarning,\n            stacklevel=1,\n        )\n\n    super().__init__(\n        name=name,\n        type=type.value,\n        durable=durable,\n        auto_delete=auto_delete,\n        routing_key=routing_key,\n        bind_to=bind_to,\n        bind_arguments=bind_arguments,\n        robust=robust,\n        internal=internal,\n        passive=passive,\n        timeout=timeout,\n        arguments=arguments,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.arguments","title":"arguments class-attribute instance-attribute","text":"
arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.auto_delete","title":"auto_delete class-attribute instance-attribute","text":"
auto_delete: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.bind_arguments","title":"bind_arguments class-attribute instance-attribute","text":"
bind_arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.bind_to","title":"bind_to class-attribute instance-attribute","text":"
bind_to: Optional[RabbitExchange] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.durable","title":"durable class-attribute instance-attribute","text":"
durable: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.internal","title":"internal class-attribute instance-attribute","text":"
internal: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.passive","title":"passive class-attribute instance-attribute","text":"
passive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.robust","title":"robust class-attribute instance-attribute","text":"
robust: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.type","title":"type class-attribute instance-attribute","text":"
type: str = ExchangeType.DIRECT.value\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/","title":"RabbitQueue","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue","title":"faststream.rabbit.shared.schemas.RabbitQueue","text":"
RabbitQueue(\n    name: str,\n    durable: bool = False,\n    exclusive: bool = False,\n    passive: bool = False,\n    auto_delete: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n)\n

Bases: NameRequired

A class to represent a RabbitMQ queue.

METHOD DESCRIPTION __hash__

returns the hash value of the queue

routing

returns the routing key of the queue

__init__

initializes the RabbitQueue object with the given parameters

Initialize a class object.

PARAMETER DESCRIPTION name

The name of the object.

TYPE: str

durable

Whether the object is durable. Defaults to False.

TYPE: bool DEFAULT: False

exclusive

Whether the object is exclusive. Defaults to False.

TYPE: bool DEFAULT: False

passive

Whether the object is passive. Defaults to False.

TYPE: bool DEFAULT: False

auto_delete

Whether the object is auto delete. Defaults to False.

TYPE: bool DEFAULT: False

arguments

Additional arguments for the object. Defaults to None.

TYPE: dict DEFAULT: None

timeout

Timeout for the object. Defaults to None.

TYPE: TimeoutType DEFAULT: None

robust

Whether the object is robust. Defaults to True.

TYPE: bool DEFAULT: True

bind_arguments

Bind arguments for the object. Defaults to None.

TYPE: dict DEFAULT: None

routing_key

Routing key for the object. Defaults to \"\".

TYPE: str DEFAULT: ''

Source code in faststream/rabbit/shared/schemas.py
def __init__(\n    self,\n    name: str,\n    durable: bool = False,\n    exclusive: bool = False,\n    passive: bool = False,\n    auto_delete: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n) -> None:\n    \"\"\"Initialize a class object.\n\n    Args:\n        name (str): The name of the object.\n        durable (bool, optional): Whether the object is durable. Defaults to False.\n        exclusive (bool, optional): Whether the object is exclusive. Defaults to False.\n        passive (bool, optional): Whether the object is passive. Defaults to False.\n        auto_delete (bool, optional): Whether the object is auto delete. Defaults to False.\n        arguments (dict, optional): Additional arguments for the object. Defaults to None.\n        timeout (TimeoutType, optional): Timeout for the object. Defaults to None.\n        robust (bool, optional): Whether the object is robust. Defaults to True.\n        bind_arguments (dict, optional): Bind arguments for the object. Defaults to None.\n        routing_key (str, optional): Routing key for the object. Defaults to \"\".\n\n    \"\"\"\n    re, routing_key = compile_path(routing_key, replace_symbol=\"*\")\n    super().__init__(\n        name=name,\n        path_regex=re,\n        durable=durable,\n        exclusive=exclusive,\n        bind_arguments=bind_arguments,\n        routing_key=routing_key,\n        robust=robust,\n        passive=passive,\n        auto_delete=auto_delete,\n        arguments=arguments,\n        timeout=timeout,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.arguments","title":"arguments class-attribute instance-attribute","text":"
arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.auto_delete","title":"auto_delete class-attribute instance-attribute","text":"
auto_delete: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.bind_arguments","title":"bind_arguments class-attribute instance-attribute","text":"
bind_arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.durable","title":"durable class-attribute instance-attribute","text":"
durable: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.exclusive","title":"exclusive class-attribute instance-attribute","text":"
exclusive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'arbitrary_types_allowed': True}\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.name","title":"name class-attribute instance-attribute","text":"
name: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.passive","title":"passive class-attribute instance-attribute","text":"
passive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.path_regex","title":"path_regex class-attribute instance-attribute","text":"
path_regex: Optional[Pattern[str]] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.robust","title":"robust class-attribute instance-attribute","text":"
robust: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.routing","title":"routing property","text":"
routing: str\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.Config.arbitrary_types_allowed","title":"arbitrary_types_allowed class-attribute instance-attribute","text":"
arbitrary_types_allowed = True\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/ReplyConfig/","title":"ReplyConfig","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/ReplyConfig/#faststream.rabbit.shared.schemas.ReplyConfig","title":"faststream.rabbit.shared.schemas.ReplyConfig","text":"

Bases: BaseModel

","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/ReplyConfig/#faststream.rabbit.shared.schemas.ReplyConfig.immediate","title":"immediate class-attribute instance-attribute","text":"
immediate: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/ReplyConfig/#faststream.rabbit.shared.schemas.ReplyConfig.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/ReplyConfig/#faststream.rabbit.shared.schemas.ReplyConfig.persist","title":"persist class-attribute instance-attribute","text":"
persist: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/get_routing_hash/","title":"get_routing_hash","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/get_routing_hash/#faststream.rabbit.shared.schemas.get_routing_hash","title":"faststream.rabbit.shared.schemas.get_routing_hash","text":"
get_routing_hash(\n    queue: RabbitQueue,\n    exchange: Optional[RabbitExchange] = None,\n) -> int\n

Calculate the routing hash for a RabbitMQ queue and exchange.

PARAMETER DESCRIPTION queue

The RabbitMQ queue.

TYPE: RabbitQueue

exchange

The RabbitMQ exchange (optional).

TYPE: Optional[RabbitExchange] DEFAULT: None

RETURNS DESCRIPTION int

The routing hash as an integer.

Source code in faststream/rabbit/shared/schemas.py
def get_routing_hash(\n    queue: RabbitQueue,\n    exchange: Optional[RabbitExchange] = None,\n) -> int:\n    \"\"\"Calculate the routing hash for a RabbitMQ queue and exchange.\n\n    Args:\n        queue: The RabbitMQ queue.\n        exchange: The RabbitMQ exchange (optional).\n\n    Returns:\n        The routing hash as an integer.\n\n    \"\"\"\n    return hash(queue) + hash(exchange or \"\")\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/utils/build_url/","title":"build_url","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/utils/build_url/#faststream.rabbit.shared.utils.build_url","title":"faststream.rabbit.shared.utils.build_url","text":"
build_url(\n    url: Union[str, URL, None] = None,\n    *,\n    host: Optional[str] = None,\n    port: Optional[int] = None,\n    login: Optional[str] = None,\n    password: Optional[str] = None,\n    virtualhost: Optional[str] = None,\n    ssl: Optional[bool] = None,\n    ssl_options: Optional[SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    **kwargs: Any\n) -> URL\n
Source code in faststream/rabbit/shared/utils.py
def build_url(\n    url: Union[str, URL, None] = None,\n    *,\n    host: Optional[str] = None,\n    port: Optional[int] = None,\n    login: Optional[str] = None,\n    password: Optional[str] = None,\n    virtualhost: Optional[str] = None,\n    ssl: Optional[bool] = None,\n    ssl_options: Optional[SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    **kwargs: Any,\n) -> URL:\n    original_url = make_url(url)\n\n    return make_url(\n        host=host or original_url.host or \"localhost\",\n        port=port or original_url.port or 5672,\n        login=login or original_url.user or \"guest\",\n        password=password or original_url.password or \"guest\",\n        virtualhost=virtualhost or removeprefix(original_url.path, \"/\"),\n        ssl=ssl or original_url.scheme == \"amqps\",\n        ssl_options=ssl_options,\n        client_properties=client_properties,\n        **{\n            **kwargs,\n            **dict(original_url.query),\n        },\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/utils/removeprefix/","title":"removeprefix","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/utils/removeprefix/#faststream.rabbit.shared.utils.removeprefix","title":"faststream.rabbit.shared.utils.removeprefix","text":"
removeprefix(string: str, prefix: str) -> str\n
Source code in faststream/rabbit/shared/utils.py
def removeprefix(string: str, prefix: str) -> str:\n    if string.startswith(prefix):\n        return string[len(prefix) :]\n    return string\n
","boost":0.5},{"location":"api/faststream/rabbit/test/FakeProducer/","title":"FakeProducer","text":"","boost":0.5},{"location":"api/faststream/rabbit/test/FakeProducer/#faststream.rabbit.test.FakeProducer","title":"faststream.rabbit.test.FakeProducer","text":"
FakeProducer(broker: RabbitBroker)\n

Bases: AioPikaFastProducer

A fake RabbitMQ producer for testing purposes.

This class extends AioPikaFastProducer and is used to simulate RabbitMQ message publishing during tests.

Initialize a FakeProducer instance.

PARAMETER DESCRIPTION broker

The RabbitBroker instance to be used for message publishing.

TYPE: RabbitBroker

Source code in faststream/rabbit/test.py
def __init__(self, broker: RabbitBroker) -> None:\n    \"\"\"\n    Initialize a FakeProducer instance.\n\n    Args:\n        broker (RabbitBroker): The RabbitBroker instance to be used for message publishing.\n    \"\"\"\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/rabbit/test/FakeProducer/#faststream.rabbit.test.FakeProducer.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/rabbit/test/FakeProducer/#faststream.rabbit.test.FakeProducer.declarer","title":"declarer instance-attribute","text":"
declarer: RabbitDeclarer = declarer\n
","boost":0.5},{"location":"api/faststream/rabbit/test/FakeProducer/#faststream.rabbit.test.FakeProducer.publish","title":"publish async","text":"
publish(\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message to a RabbitMQ queue or exchange.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: AioPikaSendableMessage DEFAULT: ''

queue

The target queue for the message.

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The target exchange for the message.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key for the message.

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory.

TYPE: bool DEFAULT: True

immediate

Whether the message should be sent immediately.

TYPE: bool DEFAULT: False

timeout

The timeout for the message.

TYPE: TimeoutType DEFAULT: None

rpc

Whether the message is for RPC.

TYPE: bool DEFAULT: False

rpc_timeout

The RPC timeout.

TYPE: float DEFAULT: 30.0

raise_timeout

Whether to raise a timeout exception.

TYPE: bool DEFAULT: False

persist

Whether to persist the message.

TYPE: bool DEFAULT: False

reply_to

The reply-to address for RPC messages.

TYPE: str DEFAULT: None

**message_kwargs

Additional message properties and content.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

Optional[SendableMessage]: The published message if successful, or None if not.

Source code in faststream/rabbit/test.py
async def publish(\n    self,\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"\n    Publish a message to a RabbitMQ queue or exchange.\n\n    Args:\n        message (AioPikaSendableMessage, optional): The message to be published.\n        queue (Union[RabbitQueue, str], optional): The target queue for the message.\n        exchange (Union[RabbitExchange, str, None], optional): The target exchange for the message.\n        routing_key (str, optional): The routing key for the message.\n        mandatory (bool, optional): Whether the message is mandatory.\n        immediate (bool, optional): Whether the message should be sent immediately.\n        timeout (TimeoutType, optional): The timeout for the message.\n        rpc (bool, optional): Whether the message is for RPC.\n        rpc_timeout (float, optional): The RPC timeout.\n        raise_timeout (bool, optional): Whether to raise a timeout exception.\n        persist (bool, optional): Whether to persist the message.\n        reply_to (str, optional): The reply-to address for RPC messages.\n        **message_kwargs (Any): Additional message properties and content.\n\n    Returns:\n        Optional[SendableMessage]: The published message if successful, or None if not.\n    \"\"\"\n    exch = RabbitExchange.validate(exchange)\n\n    incoming = build_message(\n        message=message,\n        queue=queue,\n        exchange=exch,\n        routing_key=routing_key,\n        reply_to=reply_to,\n        **message_kwargs,\n    )\n\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        if handler.exchange == exch:\n            call: bool = False\n\n            if (\n                handler.exchange is None\n                or handler.exchange.type == ExchangeType.DIRECT\n            ):\n                call = handler.queue.name == incoming.routing_key\n\n            elif handler.exchange.type == ExchangeType.FANOUT:\n                call = True\n\n            elif handler.exchange.type == ExchangeType.TOPIC:\n                call = bool(\n                    re.match(\n                        handler.queue.routing_key.replace(\".\", r\"\\.\").replace(\n                            \"*\", \".*\"\n                        ),\n                        incoming.routing_key or \"\",\n                    )\n                )\n\n            elif handler.exchange.type == ExchangeType.HEADERS:  # pramga: no branch\n                queue_headers = (handler.queue.bind_arguments or {}).copy()\n                msg_headers = incoming.headers\n\n                if not queue_headers:\n                    call = True\n\n                else:\n                    matcher = queue_headers.pop(\"x-match\", \"all\")\n\n                    full = True\n                    none = True\n                    for k, v in queue_headers.items():\n                        if msg_headers.get(k) != v:\n                            full = False\n                        else:\n                            none = False\n\n                    if not none:\n                        call = (matcher == \"any\") or full\n\n            else:  # pragma: no cover\n                raise AssertionError(\"unreachable\")\n\n            if call:\n                r = await call_handler(\n                    handler=handler,\n                    message=incoming,\n                    rpc=rpc,\n                    rpc_timeout=rpc_timeout,\n                    raise_timeout=raise_timeout,\n                )\n\n                if rpc:  # pragma: no branch\n                    return r\n\n    return None\n
","boost":0.5},{"location":"api/faststream/rabbit/test/PatchedMessage/","title":"PatchedMessage","text":"","boost":0.5},{"location":"api/faststream/rabbit/test/PatchedMessage/#faststream.rabbit.test.PatchedMessage","title":"faststream.rabbit.test.PatchedMessage","text":"

Bases: IncomingMessage

Patched message class for testing purposes.

This class extends aio_pika's IncomingMessage class and is used to simulate RabbitMQ message handling during tests.

","boost":0.5},{"location":"api/faststream/rabbit/test/PatchedMessage/#faststream.rabbit.test.PatchedMessage.ack","title":"ack async","text":"
ack(multiple: bool = False) -> None\n

Asynchronously acknowledge a message.

PARAMETER DESCRIPTION multiple

Whether to acknowledge multiple messages at once. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/test.py
async def ack(self, multiple: bool = False) -> None:\n    \"\"\"Asynchronously acknowledge a message.\n\n    Args:\n        multiple (bool, optional): Whether to acknowledge multiple messages at once. Defaults to False.\n\n    Returns:\n        None\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/rabbit/test/PatchedMessage/#faststream.rabbit.test.PatchedMessage.nack","title":"nack async","text":"
nack(multiple: bool = False, requeue: bool = True) -> None\n

Nack the message.

PARAMETER DESCRIPTION multiple

Whether to nack multiple messages. Default is False.

TYPE: bool DEFAULT: False

requeue

Whether to requeue the message. Default is True.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/test.py
async def nack(self, multiple: bool = False, requeue: bool = True) -> None:\n    \"\"\"Nack the message.\n\n    Args:\n        multiple: Whether to nack multiple messages. Default is False.\n        requeue: Whether to requeue the message. Default is True.\n\n    Returns:\n        None\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/rabbit/test/PatchedMessage/#faststream.rabbit.test.PatchedMessage.reject","title":"reject async","text":"
reject(requeue: bool = False) -> None\n

Rejects a task.

PARAMETER DESCRIPTION requeue

Whether to requeue the task if it fails (default: False)

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/test.py
async def reject(self, requeue: bool = False) -> None:\n    \"\"\"Rejects a task.\n\n    Args:\n        requeue: Whether to requeue the task if it fails (default: False)\n\n    Returns:\n        None\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/","title":"TestRabbitBroker","text":"","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker","title":"faststream.rabbit.test.TestRabbitBroker","text":"
TestRabbitBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[RabbitBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: RabbitBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: RabbitBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(\n        queue=publisher.queue,\n        exchange=publisher.exchange,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: RabbitBroker, publisher: Any\n) -> None\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef patch_publisher(broker: RabbitBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: RabbitBroker, publisher: Publisher\n) -> None\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: RabbitBroker,\n    publisher: Publisher,\n) -> None:\n    broker.handlers.pop(\n        publisher._get_routing_hash(),\n        None,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/test/build_message/","title":"build_message","text":"","boost":0.5},{"location":"api/faststream/rabbit/test/build_message/#faststream.rabbit.test.build_message","title":"faststream.rabbit.test.build_message","text":"
build_message(\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any\n) -> PatchedMessage\n

Build a patched RabbitMQ message for testing.

PARAMETER DESCRIPTION message

The message content.

TYPE: AioPikaSendableMessage DEFAULT: ''

queue

The message queue.

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The message exchange.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The message routing key.

TYPE: str DEFAULT: ''

reply_to

The reply-to queue.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional message arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION PatchedMessage

A patched RabbitMQ message.

TYPE: PatchedMessage

Source code in faststream/rabbit/test.py
def build_message(\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any,\n) -> PatchedMessage:\n    \"\"\"\n    Build a patched RabbitMQ message for testing.\n\n    Args:\n        message (AioPikaSendableMessage): The message content.\n        queue (Union[RabbitQueue, str]): The message queue.\n        exchange (Union[RabbitExchange, str, None]): The message exchange.\n        routing_key (str): The message routing key.\n        reply_to (Optional[str]): The reply-to queue.\n        **message_kwargs (Any): Additional message arguments.\n\n    Returns:\n        PatchedMessage: A patched RabbitMQ message.\n    \"\"\"\n    que = RabbitQueue.validate(queue)\n    exch = RabbitExchange.validate(exchange)\n    msg = AioPikaParser.encode_message(\n        message=message,\n        persist=False,\n        reply_to=reply_to,\n        callback_queue=None,\n        **message_kwargs,\n    )\n\n    routing = routing_key or (getattr(que, \"name\", \"\"))\n\n    return PatchedMessage(\n        aiormq.abc.DeliveredMessage(\n            delivery=spec.Basic.Deliver(\n                exchange=getattr(exch, \"name\", \"\"),\n                routing_key=routing,\n            ),\n            header=ContentHeader(\n                properties=spec.Basic.Properties(\n                    content_type=msg.content_type,\n                    message_id=str(uuid4()),\n                    headers=msg.headers,\n                    reply_to=reply_to,\n                )\n            ),\n            body=msg.body,\n            channel=AsyncMock(),\n        )\n    )\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/","title":"ListSub","text":"","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub","title":"faststream.redis.ListSub","text":"
ListSub(\n    channel: str,\n    batch: bool = False,\n    max_records: PositiveInt = 10,\n    polling_interval: PositiveFloat = 0.1,\n)\n

Bases: NameRequired

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    channel: str,\n    batch: bool = False,\n    max_records: PositiveInt = 10,\n    polling_interval: PositiveFloat = 0.1,\n) -> None:\n    super().__init__(\n        name=channel,\n        batch=batch,\n        max_records=max_records,\n        polling_interval=polling_interval,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.max_records","title":"max_records class-attribute instance-attribute","text":"
max_records: PositiveInt = 10\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: PositiveFloat = 0.1\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.records","title":"records property","text":"
records: Optional[PositiveInt]\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/","title":"PubSub","text":"","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub","title":"faststream.redis.PubSub","text":"
PubSub(\n    channel: str,\n    pattern: bool = False,\n    polling_interval: PositiveFloat = 1.0,\n)\n

Bases: NameRequired

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    channel: str,\n    pattern: bool = False,\n    polling_interval: PositiveFloat = 1.0,\n) -> None:\n    reg, path = compile_path(channel, replace_symbol=\"*\")\n\n    if reg is not None:\n        pattern = True\n\n    super().__init__(\n        name=path,\n        path_regex=reg,\n        pattern=pattern,\n        polling_interval=polling_interval,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.last_id","title":"last_id class-attribute instance-attribute","text":"
last_id: str = '$'\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'arbitrary_types_allowed': True}\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.path_regex","title":"path_regex class-attribute instance-attribute","text":"
path_regex: Optional[Pattern[str]] = None\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.pattern","title":"pattern class-attribute instance-attribute","text":"
pattern: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: PositiveFloat = 1.0\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.Config.arbitrary_types_allowed","title":"arbitrary_types_allowed class-attribute instance-attribute","text":"
arbitrary_types_allowed = True\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/","title":"RedisBroker","text":"","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker","title":"faststream.redis.RedisBroker","text":"
RedisBroker(\n    url: str = \"redis://localhost:6379\",\n    polling_interval: Optional[float] = None,\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"custom\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: RedisLoggingMixin, BrokerAsyncUsecase[AnyRedisDict, 'Redis[bytes]']

Source code in faststream/redis/broker.py
def __init__(\n    self,\n    url: str = \"redis://localhost:6379\",\n    polling_interval: Optional[float] = None,\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"custom\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    self.global_polling_interval = polling_interval\n    self._producer = None\n\n    super().__init__(\n        url=url,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n    )\n\n    url_kwargs = urlparse(self.url)\n    self.protocol = protocol or url_kwargs.scheme\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.global_polling_interval","title":"global_polling_interval instance-attribute","text":"
global_polling_interval = polling_interval\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[int, Handler]\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol or url_kwargs.scheme\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.connect","title":"connect async","text":"
connect(*args: Any, **kwargs: Any) -> Redis[bytes]\n
Source code in faststream/redis/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> \"Redis[bytes]\":\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, **kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.publish_batch","title":"publish_batch async","text":"
publish_batch(*args: Any, **kwargs: Any) -> None\n
Source code in faststream/redis/broker.py
async def publish_batch(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish_batch(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.publisher","title":"publisher","text":"
publisher(\n    channel: Union[Channel, PubSub, None] = None,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/redis/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    channel: Union[Channel, PubSub, None] = None,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    channel = PubSub.validate(channel)\n    list = ListSub.validate(list)\n    stream = StreamSub.validate(stream)\n\n    any_of = channel or list or stream\n    if any_of is None:\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    key = Handler.get_routing_hash(any_of)\n    publisher = self._publishers.get(\n        key,\n        Publisher(\n            channel=channel,\n            list=list,\n            stream=stream,\n            headers=headers,\n            reply_to=reply_to,\n            # AsyncAPI\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(key, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.start","title":"start async","text":"
start() -> None\n
Source code in faststream/redis/broker.py
async def start(self) -> None:\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n    assert self._connection, NOT_CONNECTED_YET  # nosec B101\n\n    for handler in self.handlers.values():\n        if (stream := handler.stream_sub) is not None and stream.group:\n            try:\n                await self._connection.xgroup_create(\n                    name=stream.name,\n                    groupname=stream.group,\n                    mkstream=True,\n                )\n            except ResponseError as e:\n                if \"already exists\" not in str(e):\n                    raise e\n\n        c = self._get_log_context(None, handler.channel_name)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self._connection)\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Any, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[AnyRedisDict, RedisMessage]] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[Any, P_HandlerParams, T_HandlerReturn],\n]:\n    channel = PubSub.validate(channel)\n    list = ListSub.validate(list)\n    stream = StreamSub.validate(stream)\n\n    if (any_of := channel or list or stream) is None:\n        raise ValueError(\n            \"You should specify `channel`, `list`, `stream` subscriber type\"\n        )\n\n    if all((channel, list)):\n        raise ValueError(\"You can't use `PubSub` and `ListSub` both\")\n    elif all((channel, stream)):\n        raise ValueError(\"You can't use `PubSub` and `StreamSub` both\")\n    elif all((list, stream)):\n        raise ValueError(\"You can't use `ListSub` and `StreamSub` both\")\n\n    self._setup_log_context(channel=any_of.name)\n    super().subscriber()\n\n    key = Handler.get_routing_hash(any_of)\n    handler = self.handlers[key] = self.handlers.get(\n        key,\n        Handler(  # type: ignore[abstract]\n            log_context_builder=partial(\n                self._get_log_context,\n                channel=any_of.name,\n            ),\n            graceful_timeout=self.graceful_timeout,\n            # Redis\n            channel=channel,\n            list=list,\n            stream=stream,\n            # AsyncAPI\n            title=title,\n            description=description,\n            include_in_schema=include_in_schema,\n        ),\n    )\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[AnyRedisDict, P_HandlerParams, T_HandlerReturn,]:\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,  # type: ignore[arg-type]\n            decoder=decoder or self._global_decoder,  # type: ignore[arg-type]\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/redis/RedisRoute/","title":"RedisRoute","text":"","boost":0.5},{"location":"api/faststream/redis/RedisRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/redis/RedisRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/redis/RedisRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/redis/RedisRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/","title":"RedisRouter","text":"","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter","title":"faststream.redis.RedisRouter","text":"
RedisRouter(\n    prefix: str = \"\",\n    handlers: Sequence[RedisRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    include_in_schema: bool = True\n)\n

Bases: RedisRouter

Source code in faststream/redis/router.py
            publisher.list, update={\"name\": prefix + publisher.list.name}\n        )\n    elif publisher.stream is not None:\n        publisher.stream = model_copy(\n            publisher.stream, update={\"name\": prefix + publisher.stream.name}\n        )\n    else:\n        raise AssertionError(\"unreachable\")\n    return publisher\n\n@override\ndef publisher(  # type: ignore[override]\n    self,\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.publisher","title":"publisher","text":"
publisher(\n    channel: Union[str, PubSub, None] = None,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/redis/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    channel: Union[str, PubSub, None] = None,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    if not any((stream, list, channel)):\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            channel=PubSub.validate(channel),\n            list=ListSub.validate(list),\n            stream=StreamSub.validate(stream),\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[str, PubSub, None] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Any, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/router.py
) -> Publisher:\n    if not any((stream, list, channel)):\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            channel=PubSub.validate(channel),\n            list=ListSub.validate(list),\n            stream=StreamSub.validate(stream),\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/","title":"StreamSub","text":"","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub","title":"faststream.redis.StreamSub","text":"
StreamSub(\n    stream: str,\n    polling_interval: Optional[PositiveInt] = 100,\n    group: Optional[str] = None,\n    consumer: Optional[str] = None,\n    batch: bool = False,\n    no_ack: bool = False,\n    last_id: Optional[str] = None,\n)\n

Bases: NameRequired

Redis Stream subscriber parameters

PARAMETER DESCRIPTION stream

(str): Redis Stream name.

TYPE: str

polling_interval

(int:ms | None): wait message block.

TYPE: Optional[PositiveInt] DEFAULT: 100

group

(str | None): consumer group name.

TYPE: Optional[str] DEFAULT: None

consumer

(str | None): consumer name.

TYPE: Optional[str] DEFAULT: None

batch

(bool): consume messages in batches.

TYPE: bool DEFAULT: False

no_ack

(bool): do not add message to PEL.

TYPE: bool DEFAULT: False

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    stream: str,\n    polling_interval: Optional[PositiveInt] = 100,\n    group: Optional[str] = None,\n    consumer: Optional[str] = None,\n    batch: bool = False,\n    no_ack: bool = False,\n    last_id: Optional[str] = None,\n) -> None:\n    \"\"\"\n    Redis Stream subscriber parameters\n\n    Args:\n        stream: (str): Redis Stream name.\n        polling_interval: (int:ms | None): wait message block.\n        group: (str | None): consumer group name.\n        consumer: (str | None): consumer name.\n        batch: (bool): consume messages in batches.\n        no_ack: (bool): do not add message to PEL.\n    \"\"\"\n    if (group and not consumer) or (not group and consumer):\n        raise ValueError(\"You should specify `group` and `consumer` both\")\n\n    if group and consumer:\n        msg: Optional[str] = None\n\n        if last_id:\n            msg = \"`last_id` has no effect with consumer group\"\n\n        if no_ack:\n            msg = \"`no_ack` has no effect with consumer group\"\n\n        if msg:\n            warnings.warn(\n                message=msg,\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n    super().__init__(\n        name=stream,\n        group=group,\n        consumer=consumer,\n        polling_interval=polling_interval,\n        batch=batch,\n        no_ack=no_ack,\n        last_id=last_id or \"$\",\n    )\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.consumer","title":"consumer class-attribute instance-attribute","text":"
consumer: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.group","title":"group class-attribute instance-attribute","text":"
group: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.last_id","title":"last_id class-attribute instance-attribute","text":"
last_id: str = '$'\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.no_ack","title":"no_ack class-attribute instance-attribute","text":"
no_ack: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: Optional[PositiveInt] = Field(\n    default=100, description=\"ms\"\n)\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/redis/TestApp/#faststream.broker.test.TestApp","title":"faststream.broker.test.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/redis/TestApp/#faststream.broker.test.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/","title":"TestRedisBroker","text":"","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker","title":"faststream.redis.TestRedisBroker","text":"
TestRedisBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[RedisBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: RedisBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/redis/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: RedisBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(\n        channel=publisher.channel,\n        list=publisher.list,\n        stream=publisher.stream,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: RedisBroker, publisher: Any\n) -> None\n
Source code in faststream/redis/test.py
@staticmethod\ndef patch_publisher(\n    broker: RedisBroker,\n    publisher: Any,\n) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: RedisBroker, publisher: Publisher\n) -> None\n
Source code in faststream/redis/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: RedisBroker,\n    publisher: Publisher,\n) -> None:\n    any_of = publisher.channel or publisher.list or publisher.stream\n    assert any_of  # nosec B101\n    broker.handlers.pop(Handler.get_routing_hash(any_of), None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/","title":"Handler","text":"","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler","title":"faststream.redis.asyncapi.Handler","text":"
Handler(\n    *,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    channel: Optional[PubSub] = None,\n    list: Optional[ListSub] = None,\n    stream: Optional[StreamSub] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True\n)\n

Bases: LogicRedisHandler

Source code in faststream/redis/handler.py
def __init__(\n    self,\n    *,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # Redis info\n    channel: Optional[PubSub] = None,\n    list: Optional[ListSub] = None,\n    stream: Optional[StreamSub] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    self.channel = channel\n    self.list_sub = list\n    self.stream_sub = stream\n\n    self.subscription = None\n    self.task = None\n\n    self.last_id = stream.last_id if stream else \"$\"\n\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.channel","title":"channel instance-attribute","text":"
channel = channel\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.channel_name","title":"channel_name property","text":"
channel_name: str\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.last_id","title":"last_id instance-attribute","text":"
last_id = stream.last_id if stream else '$'\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.list_sub","title":"list_sub instance-attribute","text":"
list_sub = list\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.name","title":"name property","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.stream_sub","title":"stream_sub instance-attribute","text":"
stream_sub = stream\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.subscription","title":"subscription instance-attribute","text":"
subscription: Optional[RPubSub] = None\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.task","title":"task instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        AnyDict, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[AnyDict, RedisMessage]],\n    decoder: Optional[CustomDecoder[RedisMessage]],\n    filter: Filter[RedisMessage],\n    middlewares: Optional[\n        Sequence[Callable[[AnyDict], BaseMiddleware]]\n    ]\n) -> None\n
Source code in faststream/redis/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[AnyDict, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[AnyDict, RedisMessage]],\n    decoder: Optional[CustomDecoder[RedisMessage]],\n    filter: Filter[RedisMessage],\n    middlewares: Optional[Sequence[Callable[[AnyDict], BaseMiddleware]]],\n) -> None:\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, RedisParser.parse_message),\n        decoder=resolve_custom_func(decoder, RedisParser.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/redis/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.task is not None:\n        if not self.task.done():\n            self.task.cancel()\n        self.task = None\n\n    if self.subscription is not None:\n        await self.subscription.unsubscribe()\n        await self.subscription.aclose()  # type: ignore[attr-defined]\n        self.subscription = None\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(channel: Hashable) -> int\n
Source code in faststream/redis/handler.py
@staticmethod\ndef get_routing_hash(channel: Hashable) -> int:\n    return hash(channel)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/redis/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    method = None\n    if self.list_sub is not None:\n        method = \"lpop\"\n\n    elif (ch := self.channel) is not None:\n        if ch.pattern:\n            method = \"psubscribe\"\n        else:\n            method = \"subscribe\"\n\n    elif (stream := self.stream_sub) is not None:\n        if stream.group:\n            method = \"xreadgroup\"\n        else:\n            method = \"xread\"\n\n    else:\n        raise AssertionError(\"unreachable\")\n\n    return {\n        self.name: Channel(\n            description=self.description,\n            subscribe=Operation(\n                message=Message(\n                    title=f\"{self.name}:Message\",\n                    payload=resolve_payloads(payloads),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                redis=redis.ChannelBinding(\n                    channel=self.channel_name,\n                    group_name=getattr(self.stream_sub, \"group\", None),\n                    consumer_name=getattr(self.stream_sub, \"consumer\", None),\n                    method=method,\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.start","title":"start async","text":"
start(client: Redis[bytes]) -> None\n
Source code in faststream/redis/handler.py
@override\nasync def start(self, client: \"Redis[bytes]\") -> None:  # type: ignore[override]\n    self.started = anyio.Event()\n\n    consume: Union[\n        Callable[[], Awaitable[Optional[AnyRedisDict]]],\n        Callable[[], Awaitable[Optional[Sequence[AnyRedisDict]]]],\n    ]\n    sleep: float\n\n    if (list_sub := self.list_sub) is not None:\n        sleep = list_sub.polling_interval\n        consume = partial(\n            self._consume_list_msg,\n            client=client,\n        )\n        self.started.set()\n\n    elif (channel := self.channel) is not None:\n        self.subscription = psub = client.pubsub()\n\n        if channel.pattern:\n            await psub.psubscribe(channel.name)\n        else:\n            await psub.subscribe(channel.name)\n\n        consume = partial(\n            psub.get_message,\n            ignore_subscribe_messages=True,\n            timeout=channel.polling_interval,\n        )\n        sleep = 0.01\n        self.started.set()\n\n    elif self.stream_sub is not None:\n        consume = partial(  # type: ignore[assignment]\n            self._consume_stream_msg,\n            client=client,\n        )\n        sleep = 0.01\n\n    else:\n        raise AssertionError(\"unreachable\")\n\n    await super().start()\n    self.task = asyncio.create_task(self._consume(consume, sleep))\n    # wait until Stream starts to consume\n    await anyio.sleep(0.01)\n    await self.started.wait()\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/","title":"Publisher","text":"","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher","title":"faststream.redis.asyncapi.Publisher","text":"

Bases: LogicPublisher

","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.channel","title":"channel class-attribute instance-attribute","text":"
channel: Optional[PubSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.channel_name","title":"channel_name property","text":"
channel_name: str\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[AnyDict] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.list","title":"list class-attribute instance-attribute","text":"
list: Optional[ListSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.name","title":"name property","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.stream","title":"stream class-attribute instance-attribute","text":"
stream: Optional[StreamSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    channel: Union[str, PubSub, None] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage,\n    channel: Union[str, PubSub, None] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n\n    channel = PubSub.validate(channel or self.channel)\n    list = ListSub.validate(list or self.list)\n    stream = StreamSub.validate(stream or self.stream)\n\n    assert any(\n        (channel, list, stream)\n    ), \"You have to specify outgoing channel\"  # nosec B101\n\n    headers_to_send = (self.headers or {}).copy()\n    if headers is not None:\n        headers_to_send.update(headers)\n\n    if getattr(list, \"batch\", False):\n        await self._producer.publish_batch(\n            *message,\n            list=list.name,  # type: ignore[union-attr]\n        )\n        return None\n\n    else:\n        return await self._producer.publish(\n            message=message,\n            channel=getattr(channel, \"name\", None),\n            list=getattr(list, \"name\", None),\n            stream=getattr(stream, \"name\", None),\n            reply_to=reply_to or self.reply_to,\n            correlation_id=correlation_id,\n            headers=headers_to_send,\n            rpc=rpc,\n            rpc_timeout=rpc_timeout,\n            raise_timeout=raise_timeout,\n        )\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/redis/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    method = None\n    if self.list is not None:\n        method = \"rpush\"\n    elif self.channel is not None:\n        method = \"publish\"\n    elif self.stream is not None:\n        method = \"xadd\"\n    else:\n        raise AssertionError(\"unreachable\")\n\n    return {\n        self.name: Channel(\n            description=self.description,\n            publish=Operation(\n                message=Message(\n                    title=f\"{self.name}:Message\",\n                    payload=resolve_payloads(payloads, \"Publisher\"),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                redis=redis.ChannelBinding(\n                    channel=self.channel_name,\n                    method=method,\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/","title":"RedisBroker","text":"","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker","title":"faststream.redis.broker.RedisBroker","text":"
RedisBroker(\n    url: str = \"redis://localhost:6379\",\n    polling_interval: Optional[float] = None,\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"custom\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: RedisLoggingMixin, BrokerAsyncUsecase[AnyRedisDict, 'Redis[bytes]']

Source code in faststream/redis/broker.py
def __init__(\n    self,\n    url: str = \"redis://localhost:6379\",\n    polling_interval: Optional[float] = None,\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"custom\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    self.global_polling_interval = polling_interval\n    self._producer = None\n\n    super().__init__(\n        url=url,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n    )\n\n    url_kwargs = urlparse(self.url)\n    self.protocol = protocol or url_kwargs.scheme\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.global_polling_interval","title":"global_polling_interval instance-attribute","text":"
global_polling_interval = polling_interval\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[int, Handler]\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol or url_kwargs.scheme\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.connect","title":"connect async","text":"
connect(*args: Any, **kwargs: Any) -> Redis[bytes]\n
Source code in faststream/redis/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> \"Redis[bytes]\":\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, **kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.publish_batch","title":"publish_batch async","text":"
publish_batch(*args: Any, **kwargs: Any) -> None\n
Source code in faststream/redis/broker.py
async def publish_batch(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish_batch(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.publisher","title":"publisher","text":"
publisher(\n    channel: Union[Channel, PubSub, None] = None,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/redis/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    channel: Union[Channel, PubSub, None] = None,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    channel = PubSub.validate(channel)\n    list = ListSub.validate(list)\n    stream = StreamSub.validate(stream)\n\n    any_of = channel or list or stream\n    if any_of is None:\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    key = Handler.get_routing_hash(any_of)\n    publisher = self._publishers.get(\n        key,\n        Publisher(\n            channel=channel,\n            list=list,\n            stream=stream,\n            headers=headers,\n            reply_to=reply_to,\n            # AsyncAPI\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(key, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.start","title":"start async","text":"
start() -> None\n
Source code in faststream/redis/broker.py
async def start(self) -> None:\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n    assert self._connection, NOT_CONNECTED_YET  # nosec B101\n\n    for handler in self.handlers.values():\n        if (stream := handler.stream_sub) is not None and stream.group:\n            try:\n                await self._connection.xgroup_create(\n                    name=stream.name,\n                    groupname=stream.group,\n                    mkstream=True,\n                )\n            except ResponseError as e:\n                if \"already exists\" not in str(e):\n                    raise e\n\n        c = self._get_log_context(None, handler.channel_name)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self._connection)\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Any, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[AnyRedisDict, RedisMessage]] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[Any, P_HandlerParams, T_HandlerReturn],\n]:\n    channel = PubSub.validate(channel)\n    list = ListSub.validate(list)\n    stream = StreamSub.validate(stream)\n\n    if (any_of := channel or list or stream) is None:\n        raise ValueError(\n            \"You should specify `channel`, `list`, `stream` subscriber type\"\n        )\n\n    if all((channel, list)):\n        raise ValueError(\"You can't use `PubSub` and `ListSub` both\")\n    elif all((channel, stream)):\n        raise ValueError(\"You can't use `PubSub` and `StreamSub` both\")\n    elif all((list, stream)):\n        raise ValueError(\"You can't use `ListSub` and `StreamSub` both\")\n\n    self._setup_log_context(channel=any_of.name)\n    super().subscriber()\n\n    key = Handler.get_routing_hash(any_of)\n    handler = self.handlers[key] = self.handlers.get(\n        key,\n        Handler(  # type: ignore[abstract]\n            log_context_builder=partial(\n                self._get_log_context,\n                channel=any_of.name,\n            ),\n            graceful_timeout=self.graceful_timeout,\n            # Redis\n            channel=channel,\n            list=list,\n            stream=stream,\n            # AsyncAPI\n            title=title,\n            description=description,\n            include_in_schema=include_in_schema,\n        ),\n    )\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[AnyRedisDict, P_HandlerParams, T_HandlerReturn,]:\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,  # type: ignore[arg-type]\n            decoder=decoder or self._global_decoder,  # type: ignore[arg-type]\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/redis/fastapi/Context/#faststream.broker.fastapi.context.Context","title":"faststream.broker.fastapi.context.Context","text":"
Context(name: str) -> Any\n
Source code in faststream/broker/fastapi/context.py
def Context(name: str) -> Any:\n    return params.Depends(\n        lambda: context.resolve(name),\n        use_cache=True,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/","title":"RedisRouter","text":"","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter","title":"faststream.redis.fastapi.RedisRouter","text":"
RedisRouter(\n    url: str = \"redis://localhost:6379\",\n    polling_interval: Optional[float] = None,\n    *,\n    host: str = \"localhost\",\n    port: Union[str, int] = 6379,\n    db: Union[str, int] = 0,\n    client_name: Optional[str] = None,\n    health_check_interval: float = 0,\n    max_connections: Optional[int] = None,\n    socket_timeout: Optional[float] = None,\n    socket_connect_timeout: Optional[float] = None,\n    socket_read_size: int = 65536,\n    socket_keepalive: bool = False,\n    socket_keepalive_options: Optional[\n        Mapping[int, Union[int, bytes]]\n    ] = None,\n    socket_type: int = 0,\n    retry_on_timeout: bool = False,\n    encoding: str = \"utf-8\",\n    encoding_errors: str = \"strict\",\n    decode_responses: bool = False,\n    parser_class: Type[BaseParser] = DefaultParser,\n    connection_class: Type[Connection] = Connection,\n    encoder_class: Type[Encoder] = Encoder,\n    security: Optional[BaseSecurity] = None,\n    graceful_timeout: Optional[float] = None,\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    asyncapi_url: Optional[str] = None,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"custom\",\n    description: Optional[str] = None,\n    asyncapi_tags: Optional[Sequence[asyncapi.Tag]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    setup_state: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n)\n

Bases: StreamRouter[AnyRedisDict]

Source code in faststream/redis/fastapi.py
@staticmethod\ndef _setup_log_context(  # type: ignore[override]\n    main_broker: RB,\n    including_broker: RB,\n) -> None:\n    for h in including_broker.handlers.values():\n        main_broker._setup_log_context(h.channel_name)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.broker","title":"broker instance-attribute","text":"
broker: BrokerAsyncUsecase[\n    MsgType, Any\n] = self.broker_class(\n    *connection_args,\n    apply_types=False,\n    tags=asyncapi_tags,\n    **connection_kwars\n)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.broker_class","title":"broker_class class-attribute instance-attribute","text":"
broker_class = RB\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any\n) -> HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n]\n

Add an API message queue route.

PARAMETER DESCRIPTION path

The path of the route.

TYPE: Union[NameRequired, str]

*extra

Additional path segments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint function to be called for this route.

TYPE: Callable[P_HandlerParams, T_HandlerReturn]

dependencies

The dependencies required by the endpoint function.

TYPE: Sequence[Depends]

**broker_kwargs

Additional keyword arguments to be passed to the broker.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]

The handler call wrapper for the route.

Source code in faststream/broker/fastapi/router.py
def add_api_mq_route(\n    self,\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any,\n) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n    \"\"\"Add an API message queue route.\n\n    Args:\n        path: The path of the route.\n        *extra: Additional path segments.\n        endpoint: The endpoint function to be called for this route.\n        dependencies: The dependencies required by the endpoint function.\n        **broker_kwargs: Additional keyword arguments to be passed to the broker.\n\n    Returns:\n        The handler call wrapper for the route.\n\n    \"\"\"\n    route: StreamRoute[MsgType, P_HandlerParams, T_HandlerReturn] = StreamRoute(\n        path,\n        *extra,\n        endpoint=endpoint,\n        dependencies=dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        broker=self.broker,\n        **broker_kwargs,\n    )\n    self.routes.append(route)\n    return route.handler\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.publisher","title":"publisher","text":"
publisher(\n    channel: Union[Channel, PubSub, None] = None,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    dependencies: Sequence[Depends] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Any, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/fastapi.py
def subscriber(\n    self,\n    channel: Union[str, PubSub, None] = None,\n    *,\n    dependencies: Optional[Sequence[Depends]] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[AnyRedisDict, P_HandlerParams, T_HandlerReturn],\n]:\n    return super().subscriber(\n        path=channel,\n        dependencies=dependencies,\n        **broker_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/","title":"LogicRedisHandler","text":"","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler","title":"faststream.redis.handler.LogicRedisHandler","text":"
LogicRedisHandler(\n    *,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    channel: Optional[PubSub] = None,\n    list: Optional[ListSub] = None,\n    stream: Optional[StreamSub] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True\n)\n

Bases: AsyncHandler[AnyRedisDict]

Source code in faststream/redis/handler.py
def __init__(\n    self,\n    *,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # Redis info\n    channel: Optional[PubSub] = None,\n    list: Optional[ListSub] = None,\n    stream: Optional[StreamSub] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    self.channel = channel\n    self.list_sub = list\n    self.stream_sub = stream\n\n    self.subscription = None\n    self.task = None\n\n    self.last_id = stream.last_id if stream else \"$\"\n\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.channel","title":"channel instance-attribute","text":"
channel = channel\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.channel_name","title":"channel_name property","text":"
channel_name: str\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.last_id","title":"last_id instance-attribute","text":"
last_id = stream.last_id if stream else '$'\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.list_sub","title":"list_sub instance-attribute","text":"
list_sub = list\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.stream_sub","title":"stream_sub instance-attribute","text":"
stream_sub = stream\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.subscription","title":"subscription instance-attribute","text":"
subscription: Optional[RPubSub] = None\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.task","title":"task instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        AnyDict, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[AnyDict, RedisMessage]],\n    decoder: Optional[CustomDecoder[RedisMessage]],\n    filter: Filter[RedisMessage],\n    middlewares: Optional[\n        Sequence[Callable[[AnyDict], BaseMiddleware]]\n    ]\n) -> None\n
Source code in faststream/redis/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[AnyDict, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[AnyDict, RedisMessage]],\n    decoder: Optional[CustomDecoder[RedisMessage]],\n    filter: Filter[RedisMessage],\n    middlewares: Optional[Sequence[Callable[[AnyDict], BaseMiddleware]]],\n) -> None:\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, RedisParser.parse_message),\n        decoder=resolve_custom_func(decoder, RedisParser.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/redis/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.task is not None:\n        if not self.task.done():\n            self.task.cancel()\n        self.task = None\n\n    if self.subscription is not None:\n        await self.subscription.unsubscribe()\n        await self.subscription.aclose()  # type: ignore[attr-defined]\n        self.subscription = None\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(channel: Hashable) -> int\n
Source code in faststream/redis/handler.py
@staticmethod\ndef get_routing_hash(channel: Hashable) -> int:\n    return hash(channel)\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.start","title":"start async","text":"
start(client: Redis[bytes]) -> None\n
Source code in faststream/redis/handler.py
@override\nasync def start(self, client: \"Redis[bytes]\") -> None:  # type: ignore[override]\n    self.started = anyio.Event()\n\n    consume: Union[\n        Callable[[], Awaitable[Optional[AnyRedisDict]]],\n        Callable[[], Awaitable[Optional[Sequence[AnyRedisDict]]]],\n    ]\n    sleep: float\n\n    if (list_sub := self.list_sub) is not None:\n        sleep = list_sub.polling_interval\n        consume = partial(\n            self._consume_list_msg,\n            client=client,\n        )\n        self.started.set()\n\n    elif (channel := self.channel) is not None:\n        self.subscription = psub = client.pubsub()\n\n        if channel.pattern:\n            await psub.psubscribe(channel.name)\n        else:\n            await psub.subscribe(channel.name)\n\n        consume = partial(\n            psub.get_message,\n            ignore_subscribe_messages=True,\n            timeout=channel.polling_interval,\n        )\n        sleep = 0.01\n        self.started.set()\n\n    elif self.stream_sub is not None:\n        consume = partial(  # type: ignore[assignment]\n            self._consume_stream_msg,\n            client=client,\n        )\n        sleep = 0.01\n\n    else:\n        raise AssertionError(\"unreachable\")\n\n    await super().start()\n    self.task = asyncio.create_task(self._consume(consume, sleep))\n    # wait until Stream starts to consume\n    await anyio.sleep(0.01)\n    await self.started.wait()\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/","title":"AnyRedisDict","text":"","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict","title":"faststream.redis.message.AnyRedisDict","text":"

Bases: PubSubMessage

","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.channel","title":"channel instance-attribute","text":"
channel: bytes\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.data","title":"data instance-attribute","text":"
data: Union[bytes, List[bytes]]\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.message_id","title":"message_id instance-attribute","text":"
message_id: NotRequired[str]\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.message_ids","title":"message_ids instance-attribute","text":"
message_ids: NotRequired[List[str]]\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.pattern","title":"pattern instance-attribute","text":"
pattern: NotRequired[Optional[bytes]]\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.type","title":"type instance-attribute","text":"
type: Literal['stream', 'list', 'message', 'batch']\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/","title":"BatchMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage","title":"faststream.redis.message.BatchMessage","text":"

Bases: PubSubMessage

","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage.channel","title":"channel instance-attribute","text":"
channel: bytes\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage.data","title":"data instance-attribute","text":"
data: List[bytes]\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage.message_id","title":"message_id instance-attribute","text":"
message_id: NotRequired[str]\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage.message_ids","title":"message_ids instance-attribute","text":"
message_ids: NotRequired[List[str]]\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage.type","title":"type instance-attribute","text":"
type: Literal['batch']\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchRedisMessage/","title":"BatchRedisMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/BatchRedisMessage/#faststream.redis.message.BatchRedisMessage","title":"faststream.redis.message.BatchRedisMessage","text":"

Bases: RedisAckMixin[BatchMessage]

","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/","title":"OneMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage","title":"faststream.redis.message.OneMessage","text":"

Bases: PubSubMessage

","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.channel","title":"channel instance-attribute","text":"
channel: bytes\n
","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.data","title":"data instance-attribute","text":"
data: bytes\n
","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.message_id","title":"message_id instance-attribute","text":"
message_id: NotRequired[str]\n
","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.message_ids","title":"message_ids instance-attribute","text":"
message_ids: NotRequired[List[str]]\n
","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.pattern","title":"pattern instance-attribute","text":"
pattern: NotRequired[Optional[bytes]]\n
","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.type","title":"type instance-attribute","text":"
type: Literal['stream', 'list', 'message']\n
","boost":0.5},{"location":"api/faststream/redis/message/OneRedisMessage/","title":"OneRedisMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/OneRedisMessage/#faststream.redis.message.OneRedisMessage","title":"faststream.redis.message.OneRedisMessage","text":"

Bases: RedisAckMixin[OneMessage]

","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/","title":"PubSubMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage","title":"faststream.redis.message.PubSubMessage","text":"

Bases: TypedDict

","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage.channel","title":"channel instance-attribute","text":"
channel: bytes\n
","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage.data","title":"data instance-attribute","text":"
data: Union[bytes, List[bytes]]\n
","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage.message_id","title":"message_id instance-attribute","text":"
message_id: NotRequired[str]\n
","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage.message_ids","title":"message_ids instance-attribute","text":"
message_ids: NotRequired[List[str]]\n
","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage.type","title":"type instance-attribute","text":"
type: str\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/","title":"RedisAckMixin","text":"","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin","title":"faststream.redis.message.RedisAckMixin","text":"

Bases: StreamMessage[MsgType]

","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.ack","title":"ack async","text":"
ack(redis: Redis[bytes], **kwargs: Any) -> None\n
Source code in faststream/redis/message.py
@override\nasync def ack(  # type: ignore[override]\n    self,\n    redis: \"Redis[bytes]\",\n    **kwargs: Any,\n) -> None:\n    if (\n        not self.commited\n        and (ids := self.raw_message.get(\"message_ids\"))\n        and (handler := context.get_local(\"handler_\"))\n        and (stream := handler.stream_sub)\n        and (group := stream.group)\n    ):\n        await redis.xack(self.raw_message[\"channel\"], group, *ids)  # type: ignore[no-untyped-call]\n        await super().ack()\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.nack","title":"nack async","text":"
nack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def nack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.reject","title":"reject async","text":"
reject(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def reject(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisMessage/","title":"RedisMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/RedisMessage/#faststream.redis.message.RedisMessage","title":"faststream.redis.message.RedisMessage","text":"

Bases: RedisAckMixin[AnyRedisDict]

","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/","title":"RawMessage","text":"","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/#faststream.redis.parser.RawMessage","title":"faststream.redis.parser.RawMessage","text":"

Bases: BaseModel

","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/#faststream.redis.parser.RawMessage.data","title":"data instance-attribute","text":"
data: bytes\n
","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/#faststream.redis.parser.RawMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = Field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/#faststream.redis.parser.RawMessage.build","title":"build classmethod","text":"
build(\n    message: SendableMessage,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n) -> RawMessage\n
Source code in faststream/redis/parser.py
@classmethod\ndef build(\n    cls,\n    message: SendableMessage,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n) -> \"RawMessage\":\n    payload, content_type = encode_message(message)\n\n    headers_to_send = {\n        \"correlation_id\": correlation_id or str(uuid4()),\n    }\n\n    if content_type:\n        headers_to_send[\"content-type\"] = content_type\n\n    if reply_to:\n        headers_to_send[\"reply_to\"] = reply_to\n\n    if headers is not None:\n        headers_to_send.update(headers)\n\n    return cls(\n        data=payload,\n        headers=headers_to_send,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/#faststream.redis.parser.RawMessage.encode","title":"encode classmethod","text":"
encode(\n    message: SendableMessage,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n) -> str\n
Source code in faststream/redis/parser.py
@classmethod\ndef encode(\n    cls,\n    message: SendableMessage,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n) -> str:\n    return model_to_json(\n        cls.build(\n            message=message,\n            reply_to=reply_to,\n            headers=headers,\n            correlation_id=correlation_id,\n        )\n    )\n
","boost":0.5},{"location":"api/faststream/redis/parser/RedisParser/","title":"RedisParser","text":"","boost":0.5},{"location":"api/faststream/redis/parser/RedisParser/#faststream.redis.parser.RedisParser","title":"faststream.redis.parser.RedisParser","text":"","boost":0.5},{"location":"api/faststream/redis/parser/RedisParser/#faststream.redis.parser.RedisParser.decode_message","title":"decode_message async staticmethod","text":"
decode_message(msg: OneRedisMessage) -> DecodedMessage\n
Source code in faststream/redis/parser.py
@staticmethod\nasync def decode_message(\n    msg: OneRedisMessage,\n) -> DecodedMessage:\n    return decode_message(msg)\n
","boost":0.5},{"location":"api/faststream/redis/parser/RedisParser/#faststream.redis.parser.RedisParser.parse_message","title":"parse_message async classmethod","text":"
parse_message(\n    message: Union[OneMessage, BatchMessage]\n) -> Union[OneRedisMessage, BatchRedisMessage]\n
Source code in faststream/redis/parser.py
@classmethod\nasync def parse_message(\n    cls,\n    message: Union[OneMessage, BatchMessage],\n) -> Union[OneRedisMessage, BatchRedisMessage]:\n    id_ = str(uuid4())\n\n    if message[\"type\"] == \"batch\":\n        data = dump_json(\n            [cls.parse_one_msg(x)[0] for x in message[\"data\"]]\n        ).encode()\n\n        return BatchRedisMessage(\n            raw_message=message,\n            body=data,\n            content_type=\"application/json\",\n            message_id=id_,\n            correlation_id=id_,\n        )\n\n    else:\n        data, headers = cls.parse_one_msg(message[\"data\"])\n\n        channel = message.get(\"channel\", b\"\").decode()\n\n        handler = context.get_local(\"handler_\")\n        path_re: Optional[Pattern[str]]\n        path: AnyDict = {}\n        if (\n            handler\n            and handler.channel is not None\n            and (path_re := handler.channel.path_regex) is not None\n            and (match := path_re.match(channel)) is not None\n        ):\n            path = match.groupdict()\n\n        return OneRedisMessage(\n            raw_message=message,\n            body=data,\n            path=path,\n            headers=headers,\n            reply_to=headers.get(\"reply_to\", \"\"),\n            content_type=headers.get(\"content-type\", \"\"),\n            message_id=message.get(\"message_id\", id_),\n            correlation_id=headers.get(\"correlation_id\", id_),\n        )\n
","boost":0.5},{"location":"api/faststream/redis/parser/RedisParser/#faststream.redis.parser.RedisParser.parse_one_msg","title":"parse_one_msg staticmethod","text":"
parse_one_msg(raw_data: bytes) -> Tuple[bytes, AnyDict]\n
Source code in faststream/redis/parser.py
@staticmethod\ndef parse_one_msg(raw_data: bytes) -> Tuple[bytes, AnyDict]:\n    try:\n        obj = model_parse(RawMessage, raw_data)\n    except Exception:\n        # Raw Redis message format\n        data = raw_data\n        headers: AnyDict = {}\n    else:\n        # FastStream message format\n        data = obj.data\n        headers = obj.headers\n\n    return data, headers\n
","boost":0.5},{"location":"api/faststream/redis/producer/RedisFastProducer/","title":"RedisFastProducer","text":"","boost":0.5},{"location":"api/faststream/redis/producer/RedisFastProducer/#faststream.redis.producer.RedisFastProducer","title":"faststream.redis.producer.RedisFastProducer","text":"
RedisFastProducer(\n    connection: Redis[bytes],\n    parser: Union[\n        None,\n        AsyncCustomParser[OneMessage, OneRedisMessage],\n        AsyncCustomParser[BatchMessage, BatchRedisMessage],\n    ],\n    decoder: Union[\n        None,\n        AsyncCustomDecoder[OneRedisMessage],\n        AsyncCustomDecoder[BatchRedisMessage],\n    ],\n)\n
Source code in faststream/redis/producer.py
def __init__(\n    self,\n    connection: \"Redis[bytes]\",\n    parser: Union[\n        None,\n        AsyncCustomParser[OneMessage, OneRedisMessage],\n        AsyncCustomParser[BatchMessage, BatchRedisMessage],\n    ],\n    decoder: Union[\n        None,\n        AsyncCustomDecoder[OneRedisMessage],\n        AsyncCustomDecoder[BatchRedisMessage],\n    ],\n) -> None:\n    self._connection = connection\n    self._parser = resolve_custom_func(\n        parser,  # type: ignore[arg-type,assignment]\n        RedisParser.parse_message,\n    )\n    self._decoder = resolve_custom_func(decoder, RedisParser.decode_message)\n
","boost":0.5},{"location":"api/faststream/redis/producer/RedisFastProducer/#faststream.redis.producer.RedisFastProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    channel: Optional[str] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Optional[str] = None,\n    stream: Optional[str] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/producer.py
async def publish(\n    self,\n    message: SendableMessage,\n    channel: Optional[str] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Optional[str] = None,\n    stream: Optional[str] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    if not any((channel, list, stream)):\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    psub: Optional[PubSub] = None\n    if rpc is True:\n        if reply_to:\n            raise WRONG_PUBLISH_ARGS\n\n        reply_to = str(uuid4())\n        psub = self._connection.pubsub()\n        await psub.subscribe(reply_to)\n\n    msg = RawMessage.encode(\n        message=message,\n        reply_to=reply_to,\n        headers=headers,\n        correlation_id=correlation_id,\n    )\n\n    if channel is not None:\n        await self._connection.publish(channel, msg)\n    elif list is not None:\n        await self._connection.rpush(list, msg)\n    elif stream is not None:\n        await self._connection.xadd(stream, {DATA_KEY: msg})\n    else:\n        raise AssertionError(\"unreachable\")\n\n    if psub is None:\n        return None\n\n    else:\n        m = None\n        with timeout_scope(rpc_timeout, raise_timeout):\n            # skip subscribe message\n            await psub.get_message(\n                ignore_subscribe_messages=True,\n                timeout=rpc_timeout or 0.0,\n            )\n\n            # get real response\n            m = await psub.get_message(\n                ignore_subscribe_messages=True,\n                timeout=rpc_timeout or 0.0,\n            )\n\n        await psub.unsubscribe()\n        await psub.aclose()  # type: ignore[attr-defined]\n\n        if m is None:\n            if raise_timeout:\n                raise TimeoutError()\n            else:\n                return None\n        else:\n            return await self._decoder(await self._parser(m))\n
","boost":0.5},{"location":"api/faststream/redis/producer/RedisFastProducer/#faststream.redis.producer.RedisFastProducer.publish_batch","title":"publish_batch async","text":"
publish_batch(*msgs: SendableMessage, list: str) -> None\n
Source code in faststream/redis/producer.py
async def publish_batch(\n    self,\n    *msgs: SendableMessage,\n    list: str,\n) -> None:\n    batch = (encode_message(msg)[0] for msg in msgs)\n    await self._connection.rpush(list, *batch)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/","title":"LogicPublisher","text":"","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher","title":"faststream.redis.publisher.LogicPublisher dataclass","text":"

Bases: BasePublisher[AnyRedisDict]

","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.channel","title":"channel class-attribute instance-attribute","text":"
channel: Optional[PubSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.channel_name","title":"channel_name property","text":"
channel_name: str\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[AnyDict] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.list","title":"list class-attribute instance-attribute","text":"
list: Optional[ListSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.stream","title":"stream class-attribute instance-attribute","text":"
stream: Optional[StreamSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    channel: Union[str, PubSub, None] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage,\n    channel: Union[str, PubSub, None] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n\n    channel = PubSub.validate(channel or self.channel)\n    list = ListSub.validate(list or self.list)\n    stream = StreamSub.validate(stream or self.stream)\n\n    assert any(\n        (channel, list, stream)\n    ), \"You have to specify outgoing channel\"  # nosec B101\n\n    headers_to_send = (self.headers or {}).copy()\n    if headers is not None:\n        headers_to_send.update(headers)\n\n    if getattr(list, \"batch\", False):\n        await self._producer.publish_batch(\n            *message,\n            list=list.name,  # type: ignore[union-attr]\n        )\n        return None\n\n    else:\n        return await self._producer.publish(\n            message=message,\n            channel=getattr(channel, \"name\", None),\n            list=getattr(list, \"name\", None),\n            stream=getattr(stream, \"name\", None),\n            reply_to=reply_to or self.reply_to,\n            correlation_id=correlation_id,\n            headers=headers_to_send,\n            rpc=rpc,\n            rpc_timeout=rpc_timeout,\n            raise_timeout=raise_timeout,\n        )\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/","title":"RedisRouter","text":"","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter","title":"faststream.redis.router.RedisRouter","text":"
RedisRouter(\n    prefix: str = \"\",\n    handlers: Sequence[RedisRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    include_in_schema: bool = True\n)\n

Bases: RedisRouter

Source code in faststream/redis/router.py
            publisher.list, update={\"name\": prefix + publisher.list.name}\n        )\n    elif publisher.stream is not None:\n        publisher.stream = model_copy(\n            publisher.stream, update={\"name\": prefix + publisher.stream.name}\n        )\n    else:\n        raise AssertionError(\"unreachable\")\n    return publisher\n\n@override\ndef publisher(  # type: ignore[override]\n    self,\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.publisher","title":"publisher","text":"
publisher(\n    channel: Union[str, PubSub, None] = None,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/redis/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    channel: Union[str, PubSub, None] = None,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    if not any((stream, list, channel)):\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            channel=PubSub.validate(channel),\n            list=ListSub.validate(list),\n            stream=StreamSub.validate(stream),\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[str, PubSub, None] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Any, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/router.py
) -> Publisher:\n    if not any((stream, list, channel)):\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            channel=PubSub.validate(channel),\n            list=ListSub.validate(list),\n            stream=StreamSub.validate(stream),\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/","title":"ListSub","text":"","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub","title":"faststream.redis.schemas.ListSub","text":"
ListSub(\n    channel: str,\n    batch: bool = False,\n    max_records: PositiveInt = 10,\n    polling_interval: PositiveFloat = 0.1,\n)\n

Bases: NameRequired

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    channel: str,\n    batch: bool = False,\n    max_records: PositiveInt = 10,\n    polling_interval: PositiveFloat = 0.1,\n) -> None:\n    super().__init__(\n        name=channel,\n        batch=batch,\n        max_records=max_records,\n        polling_interval=polling_interval,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.max_records","title":"max_records class-attribute instance-attribute","text":"
max_records: PositiveInt = 10\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: PositiveFloat = 0.1\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.records","title":"records property","text":"
records: Optional[PositiveInt]\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/","title":"PubSub","text":"","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub","title":"faststream.redis.schemas.PubSub","text":"
PubSub(\n    channel: str,\n    pattern: bool = False,\n    polling_interval: PositiveFloat = 1.0,\n)\n

Bases: NameRequired

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    channel: str,\n    pattern: bool = False,\n    polling_interval: PositiveFloat = 1.0,\n) -> None:\n    reg, path = compile_path(channel, replace_symbol=\"*\")\n\n    if reg is not None:\n        pattern = True\n\n    super().__init__(\n        name=path,\n        path_regex=reg,\n        pattern=pattern,\n        polling_interval=polling_interval,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.last_id","title":"last_id class-attribute instance-attribute","text":"
last_id: str = '$'\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'arbitrary_types_allowed': True}\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.path_regex","title":"path_regex class-attribute instance-attribute","text":"
path_regex: Optional[Pattern[str]] = None\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.pattern","title":"pattern class-attribute instance-attribute","text":"
pattern: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: PositiveFloat = 1.0\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.Config.arbitrary_types_allowed","title":"arbitrary_types_allowed class-attribute instance-attribute","text":"
arbitrary_types_allowed = True\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/","title":"StreamSub","text":"","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub","title":"faststream.redis.schemas.StreamSub","text":"
StreamSub(\n    stream: str,\n    polling_interval: Optional[PositiveInt] = 100,\n    group: Optional[str] = None,\n    consumer: Optional[str] = None,\n    batch: bool = False,\n    no_ack: bool = False,\n    last_id: Optional[str] = None,\n)\n

Bases: NameRequired

Redis Stream subscriber parameters

PARAMETER DESCRIPTION stream

(str): Redis Stream name.

TYPE: str

polling_interval

(int:ms | None): wait message block.

TYPE: Optional[PositiveInt] DEFAULT: 100

group

(str | None): consumer group name.

TYPE: Optional[str] DEFAULT: None

consumer

(str | None): consumer name.

TYPE: Optional[str] DEFAULT: None

batch

(bool): consume messages in batches.

TYPE: bool DEFAULT: False

no_ack

(bool): do not add message to PEL.

TYPE: bool DEFAULT: False

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    stream: str,\n    polling_interval: Optional[PositiveInt] = 100,\n    group: Optional[str] = None,\n    consumer: Optional[str] = None,\n    batch: bool = False,\n    no_ack: bool = False,\n    last_id: Optional[str] = None,\n) -> None:\n    \"\"\"\n    Redis Stream subscriber parameters\n\n    Args:\n        stream: (str): Redis Stream name.\n        polling_interval: (int:ms | None): wait message block.\n        group: (str | None): consumer group name.\n        consumer: (str | None): consumer name.\n        batch: (bool): consume messages in batches.\n        no_ack: (bool): do not add message to PEL.\n    \"\"\"\n    if (group and not consumer) or (not group and consumer):\n        raise ValueError(\"You should specify `group` and `consumer` both\")\n\n    if group and consumer:\n        msg: Optional[str] = None\n\n        if last_id:\n            msg = \"`last_id` has no effect with consumer group\"\n\n        if no_ack:\n            msg = \"`no_ack` has no effect with consumer group\"\n\n        if msg:\n            warnings.warn(\n                message=msg,\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n    super().__init__(\n        name=stream,\n        group=group,\n        consumer=consumer,\n        polling_interval=polling_interval,\n        batch=batch,\n        no_ack=no_ack,\n        last_id=last_id or \"$\",\n    )\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.consumer","title":"consumer class-attribute instance-attribute","text":"
consumer: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.group","title":"group class-attribute instance-attribute","text":"
group: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.last_id","title":"last_id class-attribute instance-attribute","text":"
last_id: str = '$'\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.no_ack","title":"no_ack class-attribute instance-attribute","text":"
no_ack: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: Optional[PositiveInt] = Field(\n    default=100, description=\"ms\"\n)\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/security/parse_security/","title":"parse_security","text":"","boost":0.5},{"location":"api/faststream/redis/security/parse_security/#faststream.redis.security.parse_security","title":"faststream.redis.security.parse_security","text":"
parse_security(security: Optional[BaseSecurity]) -> AnyDict\n
Source code in faststream/redis/security.py
def parse_security(security: Optional[BaseSecurity]) -> AnyDict:\n    if security is None:\n        return {}\n    elif isinstance(security, SASLPlaintext):\n        return _parse_sasl_plaintext(security)\n    elif isinstance(security, BaseSecurity):\n        return _parse_base_security(security)\n    else:\n        raise NotImplementedError(f\"RedisBroker does not support {type(security)}\")\n
","boost":0.5},{"location":"api/faststream/redis/shared/logging/RedisLoggingMixin/","title":"RedisLoggingMixin","text":"","boost":0.5},{"location":"api/faststream/redis/shared/logging/RedisLoggingMixin/#faststream.redis.shared.logging.RedisLoggingMixin","title":"faststream.redis.shared.logging.RedisLoggingMixin","text":"
RedisLoggingMixin(\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any\n)\n

Bases: LoggingMixin

Source code in faststream/redis/shared/logging.py
def __init__(\n    self,\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any,\n) -> None:\n    super().__init__(\n        *args,\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n        **kwargs,\n    )\n    self._message_id_ln = 15\n    self._max_channel_name = 4\n
","boost":0.5},{"location":"api/faststream/redis/shared/logging/RedisLoggingMixin/#faststream.redis.shared.logging.RedisLoggingMixin.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/redis/shared/logging/RedisLoggingMixin/#faststream.redis.shared.logging.RedisLoggingMixin.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/redis/shared/logging/RedisLoggingMixin/#faststream.redis.shared.logging.RedisLoggingMixin.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRoute/","title":"RedisRoute","text":"","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/","title":"RedisRouter","text":"","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter","title":"faststream.redis.shared.router.RedisRouter","text":"
RedisRouter(\n    prefix: str = \"\",\n    handlers: Sequence[\n        RedisRoute[AnyRedisDict, SendableMessage]\n    ] = (),\n    **kwargs: Any\n)\n

Bases: BrokerRouter[int, AnyRedisDict]

Source code in faststream/redis/shared/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[RedisRoute[AnyRedisDict, SendableMessage]] = (),\n    **kwargs: Any,\n) -> None:\n    for h in handlers:\n        if not (channel := h.kwargs.pop(\"channel\", None)):\n            if list := h.kwargs.pop(\"list\", None):\n                h.kwargs[\"list\"] = prefix + list\n                continue\n\n            elif stream := h.kwargs.pop(\"stream\", None):\n                h.kwargs[\"stream\"] = prefix + stream\n                continue\n\n            channel, h.args = h.args[0], h.args[1:]\n\n        h.args = (prefix + channel, *h.args)\n\n    super().__init__(prefix, handlers, **kwargs)\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        AnyRedisDict, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/shared/router.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[AnyRedisDict, P_HandlerParams, T_HandlerReturn],\n]:\n    channel = PubSub.validate(channel)\n    list = ListSub.validate(list)\n    stream = StreamSub.validate(stream)\n\n    return self._wrap_subscriber(\n        channel=model_copy(channel, update={\"name\": self.prefix + channel.name})\n        if channel\n        else None,\n        list=model_copy(list, update={\"name\": self.prefix + list.name})\n        if list\n        else None,\n        stream=model_copy(stream, update={\"name\": self.prefix + stream.name})\n        if stream\n        else None,\n        **broker_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/test/FakeProducer/","title":"FakeProducer","text":"","boost":0.5},{"location":"api/faststream/redis/test/FakeProducer/#faststream.redis.test.FakeProducer","title":"faststream.redis.test.FakeProducer","text":"
FakeProducer(broker: RedisBroker)\n

Bases: RedisFastProducer

Source code in faststream/redis/test.py
def __init__(self, broker: RedisBroker) -> None:\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/redis/test/FakeProducer/#faststream.redis.test.FakeProducer.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/redis/test/FakeProducer/#faststream.redis.test.FakeProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    channel: Optional[str] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Optional[str] = None,\n    stream: Optional[str] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/test.py
@override\nasync def publish(\n    self,\n    message: SendableMessage,\n    channel: Optional[str] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Optional[str] = None,\n    stream: Optional[str] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    any_of = channel or list or stream\n    if any_of is None:\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        call = False\n        batch = False\n\n        if channel and (ch := handler.channel) is not None:\n            call = bool(\n                (not ch.pattern and ch.name == channel)\n                or (\n                    ch.pattern\n                    and re.match(\n                        ch.name.replace(\".\", \"\\\\.\").replace(\"*\", \".*\"),\n                        channel,\n                    )\n                )\n            )\n\n        if list and (ls := handler.list_sub) is not None:\n            batch = ls.batch\n            call = list == ls.name\n\n        if stream and (st := handler.stream_sub) is not None:\n            batch = st.batch\n            call = stream == st.name\n\n        if call:\n            r = await call_handler(\n                handler=handler,\n                message=build_message(\n                    message=[message] if batch else message,\n                    channel=any_of,\n                    headers=headers,\n                    correlation_id=correlation_id,\n                    reply_to=reply_to,\n                ),\n                rpc=rpc,\n                rpc_timeout=rpc_timeout,\n                raise_timeout=raise_timeout,\n            )\n\n            if rpc:  # pragma: no branch\n                return r\n\n    return None\n
","boost":0.5},{"location":"api/faststream/redis/test/FakeProducer/#faststream.redis.test.FakeProducer.publish_batch","title":"publish_batch async","text":"
publish_batch(*msgs: SendableMessage, list: str) -> None\n
Source code in faststream/redis/test.py
async def publish_batch(\n    self,\n    *msgs: SendableMessage,\n    list: str,\n) -> None:\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        if handler.list_sub and handler.list_sub.name == list:\n            await call_handler(\n                handler=handler,\n                message=build_message(\n                    message=msgs,\n                    channel=list,\n                ),\n            )\n\n    return None\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/","title":"TestRedisBroker","text":"","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker","title":"faststream.redis.test.TestRedisBroker","text":"
TestRedisBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[RedisBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: RedisBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/redis/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: RedisBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(\n        channel=publisher.channel,\n        list=publisher.list,\n        stream=publisher.stream,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: RedisBroker, publisher: Any\n) -> None\n
Source code in faststream/redis/test.py
@staticmethod\ndef patch_publisher(\n    broker: RedisBroker,\n    publisher: Any,\n) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: RedisBroker, publisher: Publisher\n) -> None\n
Source code in faststream/redis/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: RedisBroker,\n    publisher: Publisher,\n) -> None:\n    any_of = publisher.channel or publisher.list or publisher.stream\n    assert any_of  # nosec B101\n    broker.handlers.pop(Handler.get_routing_hash(any_of), None)\n
","boost":0.5},{"location":"api/faststream/redis/test/build_message/","title":"build_message","text":"","boost":0.5},{"location":"api/faststream/redis/test/build_message/#faststream.redis.test.build_message","title":"faststream.redis.test.build_message","text":"
build_message(\n    message: SendableMessage,\n    channel: str,\n    *,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[AnyDict] = None\n) -> AnyRedisDict\n
Source code in faststream/redis/test.py
def build_message(\n    message: SendableMessage,\n    channel: str,\n    *,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[AnyDict] = None,\n) -> AnyRedisDict:\n    data = RawMessage.encode(\n        message=message,\n        reply_to=reply_to,\n        headers=headers,\n        correlation_id=correlation_id,\n    )\n    return AnyRedisDict(\n        channel=channel.encode(),\n        data=data.encode(),\n        type=\"message\",\n    )\n
","boost":0.5},{"location":"api/faststream/security/BaseSecurity/","title":"BaseSecurity","text":"","boost":0.5},{"location":"api/faststream/security/BaseSecurity/#faststream.security.BaseSecurity","title":"faststream.security.BaseSecurity","text":"
BaseSecurity(\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Base class for defining security configurations.

This class provides a base for defining security configurations for communication with a broker. It allows setting SSL encryption and provides methods to retrieve security requirements and schemas.

PARAMETER DESCRIPTION ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements in the form of a list of dictionaries.

get_schema

Get the security schema as a dictionary.

Source code in faststream/security.py
def __init__(\n    self,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    if ssl_context is not None:\n        use_ssl = True\n\n    self.use_ssl = use_ssl\n    self.ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/security/BaseSecurity/#faststream.security.BaseSecurity.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/security/BaseSecurity/#faststream.security.BaseSecurity.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/security/BaseSecurity/#faststream.security.BaseSecurity.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return []\n
","boost":0.5},{"location":"api/faststream/security/BaseSecurity/#faststream.security.BaseSecurity.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {}\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/","title":"SASLPlaintext","text":"","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext","title":"faststream.security.SASLPlaintext","text":"
SASLPlaintext(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/PLAINTEXT authentication.

This class defines security configuration for SASL/PLAINTEXT authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/PLAINTEXT authentication.

get_schema

Get the security schema for SASL/PLAINTEXT authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/PLAINTEXT authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/PLAINTEXT authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"user-password\": []}]\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/PLAINTEXT authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/PLAINTEXT authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"user-password\": {\"type\": \"userPassword\"}}\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/","title":"SASLScram256","text":"","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256","title":"faststream.security.SASLScram256","text":"
SASLScram256(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/SCRAM-SHA-256 authentication.

This class defines security configuration for SASL/SCRAM-SHA-256 authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/SCRAM-SHA-256 authentication.

get_schema

Get the security schema for SASL/SCRAM-SHA-256 authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/SCRAM-SHA-256 authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/SCRAM-SHA-256 authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"scram256\": []}]\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/SCRAM-SHA-256 authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/SCRAM-SHA-256 authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"scram256\": {\"type\": \"scramSha256\"}}\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/","title":"SASLScram512","text":"","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512","title":"faststream.security.SASLScram512","text":"
SASLScram512(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/SCRAM-SHA-512 authentication.

This class defines security configuration for SASL/SCRAM-SHA-512 authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/SCRAM-SHA-512 authentication.

get_schema

Get the security schema for SASL/SCRAM-SHA-512 authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/SCRAM-SHA-512 authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/SCRAM-SHA-512 authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"scram512\": []}]\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/SCRAM-SHA-512 authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/SCRAM-SHA-512 authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"scram512\": {\"type\": \"scramSha512\"}}\n
","boost":0.5},{"location":"api/faststream/utils/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/utils/Context/#faststream.utils.Context","title":"faststream.utils.Context","text":"
Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n    )\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/","title":"ContextRepo","text":"","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo","title":"faststream.utils.ContextRepo","text":"
ContextRepo()\n

Bases: Singleton

A class to represent a context repository.

METHOD DESCRIPTION __init__

initializes the ContextRepo object

set_global

sets a global context variable

reset_global

resets a global context variable

set_local

sets a local context variable

reset_local

resets a local context variable

get_local

gets the value of a local context variable

clear

clears the global and scope context

get

gets the value of a context variable

__getattr__

gets the value of a context variable using attribute access

context

gets the current context as a dictionary

scope

creates a context scope for a specific key and value

Initialize the class.

Source code in faststream/utils/context/main.py
def __init__(self) -> None:\n    \"\"\"Initialize the class.\n\n    Attributes:\n        _global_context : a dictionary representing the global context\n        _scope_context : a dictionary representing the scope context\n    \"\"\"\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.context","title":"context property","text":"
context: AnyDict\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.clear","title":"clear","text":"
clear() -> None\n
Source code in faststream/utils/context/main.py
def clear(self) -> None:\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.get","title":"get","text":"
get(key: str, default: Any = None) -> Any\n

Get the value associated with a key.

PARAMETER DESCRIPTION key

The key to retrieve the value for.

TYPE: str

RETURNS DESCRIPTION Any

The value associated with the key.

Source code in faststream/utils/context/main.py
def get(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value associated with a key.\n\n    Args:\n        key: The key to retrieve the value for.\n\n    Returns:\n        The value associated with the key.\n    \"\"\"\n    return self._global_context.get(key, self.get_local(key, default))\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.get_local","title":"get_local","text":"
get_local(key: str, default: Any = None) -> Any\n

Get the value of a local variable.

PARAMETER DESCRIPTION key

The key of the local variable to retrieve.

TYPE: str

RETURNS DESCRIPTION Any

The value of the local variable.

Source code in faststream/utils/context/main.py
def get_local(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value of a local variable.\n\n    Args:\n        key: The key of the local variable to retrieve.\n\n    Returns:\n        The value of the local variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is not None:  # pragma: no branch\n        return context_var.get()\n    else:\n        return default\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.reset_global","title":"reset_global","text":"
reset_global(key: str) -> None\n

Resets a key in the global context.

PARAMETER DESCRIPTION key

The key to reset in the global context.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_global(self, key: str) -> None:\n    \"\"\"Resets a key in the global context.\n\n    Args:\n        key (str): The key to reset in the global context.\n\n    Returns:\n        None\n    \"\"\"\n    self._global_context.pop(key, None)\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.reset_local","title":"reset_local","text":"
reset_local(key: str, tag: Token[Any]) -> None\n

Resets the local context for a given key.

PARAMETER DESCRIPTION key

The key to reset the local context for.

TYPE: str

tag

The tag associated with the local context.

TYPE: Token[Any]

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_local(self, key: str, tag: \"Token[Any]\") -> None:\n    \"\"\"Resets the local context for a given key.\n\n    Args:\n        key (str): The key to reset the local context for.\n        tag (Token[Any]): The tag associated with the local context.\n\n    Returns:\n        None\n    \"\"\"\n    self._scope_context[key].reset(tag)\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.resolve","title":"resolve","text":"
resolve(argument: str) -> Any\n

Resolve the context of an argument.

PARAMETER DESCRIPTION argument

A string representing the argument.

TYPE: str

RETURNS DESCRIPTION Any

The resolved context of the argument.

RAISES DESCRIPTION AttributeError

If the attribute does not exist in the context.

Source code in faststream/utils/context/main.py
def resolve(self, argument: str) -> Any:\n    \"\"\"Resolve the context of an argument.\n\n    Args:\n        argument: A string representing the argument.\n\n    Returns:\n        The resolved context of the argument.\n\n    Raises:\n        AttributeError: If the attribute does not exist in the context.\n    \"\"\"\n    first, *keys = argument.split(\".\")\n\n    if (v := self.get(first, _empty)) is _empty:\n        raise KeyError(f\"`{self.context}` does not contains `{first}` key\")\n\n    for i in keys:\n        if isinstance(v, Mapping):\n            v = v[i]\n        else:\n            v = getattr(v, i)\n    return v\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.scope","title":"scope","text":"
scope(key: str, value: Any) -> Iterator[None]\n

Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.

PARAMETER DESCRIPTION key

The key of the local variable

TYPE: str

value

The value to set the local variable to

TYPE: Any

YIELDS DESCRIPTION Iterator[None]

None

RETURNS DESCRIPTION Iterator[None]

An iterator that yields None

Source code in faststream/utils/context/main.py
@contextmanager\ndef scope(self, key: str, value: Any) -> Iterator[None]:\n    \"\"\"Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.\n\n    Args:\n        key: The key of the local variable\n        value: The value to set the local variable to\n\n    Yields:\n        None\n\n    Returns:\n        An iterator that yields None\n    \"\"\"\n    token = self.set_local(key, value)\n    try:\n        yield\n    finally:\n        self.reset_local(key, token)\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.set_global","title":"set_global","text":"
set_global(key: str, v: Any) -> None\n

Sets a value in the global context.

PARAMETER DESCRIPTION key

The key to set in the global context.

TYPE: str

v

The value to set.

TYPE: Any

RETURNS DESCRIPTION None

None.

Source code in faststream/utils/context/main.py
def set_global(self, key: str, v: Any) -> None:\n    \"\"\"Sets a value in the global context.\n\n    Args:\n        key: The key to set in the global context.\n        v: The value to set.\n\n    Returns:\n        None.\n    \"\"\"\n    self._global_context[key] = v\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.set_local","title":"set_local","text":"
set_local(key: str, value: T) -> Token[T]\n

Set a local context variable.

PARAMETER DESCRIPTION key

The key for the context variable.

TYPE: str

value

The value to set for the context variable.

TYPE: T

RETURNS DESCRIPTION Token[T]

Token[T]: A token representing the context variable.

Source code in faststream/utils/context/main.py
def set_local(self, key: str, value: T) -> \"Token[T]\":\n    \"\"\"Set a local context variable.\n\n    Args:\n        key (str): The key for the context variable.\n        value (T): The value to set for the context variable.\n\n    Returns:\n        Token[T]: A token representing the context variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is None:\n        context_var = ContextVar(key, default=None)\n        self._scope_context[key] = context_var\n    return context_var.set(value)\n
","boost":0.5},{"location":"api/faststream/utils/Depends/","title":"Depends","text":"","boost":0.5},{"location":"api/faststream/utils/Depends/#fast_depends.use.Depends","title":"fast_depends.use.Depends","text":"
Depends(\n    dependency: Callable[P, T],\n    *,\n    use_cache: bool = True,\n    cast: bool = True\n) -> Any\n
Source code in fast_depends/use.py
def Depends(\n    dependency: Callable[P, T],\n    *,\n    use_cache: bool = True,\n    cast: bool = True,\n) -> Any:\n    return model.Depends(\n        dependency=dependency,\n        use_cache=use_cache,\n        cast=cast,\n    )\n
","boost":0.5},{"location":"api/faststream/utils/Header/","title":"Header","text":"","boost":0.5},{"location":"api/faststream/utils/Header/#faststream.utils.Header","title":"faststream.utils.Header","text":"
Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.headers.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/","title":"NoCast","text":"","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast","title":"faststream.utils.NoCast","text":"
NoCast()\n

Bases: CustomField

A class that represents a custom field without casting.

METHOD DESCRIPTION __init__

Initializes the NoCast object.

use

Returns the provided keyword arguments as a dictionary.

Source code in faststream/utils/no_cast.py
def __init__(self) -> None:\n    super().__init__(cast=False)\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast.cast","title":"cast instance-attribute","text":"
cast: bool = cast\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast.param_name","title":"param_name instance-attribute","text":"
param_name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast.required","title":"required instance-attribute","text":"
required: bool = required\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast.set_param_name","title":"set_param_name","text":"
set_param_name(name: str) -> Cls\n
Source code in fast_depends/library/model.py
def set_param_name(self: Cls, name: str) -> Cls:\n    self.param_name = name\n    return self\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast.use","title":"use","text":"
use(**kwargs: Any) -> AnyDict\n

Return a dictionary containing the keyword arguments passed to the function.

PARAMETER DESCRIPTION **kwargs

Keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION AnyDict

Dictionary containing the keyword arguments

Source code in faststream/utils/no_cast.py
def use(self, **kwargs: Any) -> AnyDict:\n    \"\"\"Return a dictionary containing the keyword arguments passed to the function.\n\n    Args:\n        **kwargs: Keyword arguments\n\n    Returns:\n        Dictionary containing the keyword arguments\n    \"\"\"\n    return kwargs\n
","boost":0.5},{"location":"api/faststream/utils/Path/","title":"Path","text":"","boost":0.5},{"location":"api/faststream/utils/Path/#faststream.utils.Path","title":"faststream.utils.Path","text":"
Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.path.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/apply_types/","title":"apply_types","text":"","boost":0.5},{"location":"api/faststream/utils/apply_types/#fast_depends.use.inject","title":"fast_depends.use.inject","text":"
inject(\n    func: Optional[Callable[P, T]] = None,\n    *,\n    cast: bool = True,\n    extra_dependencies: Sequence[model.Depends] = (),\n    pydantic_config: Optional[ConfigDict] = None,\n    dependency_overrides_provider: Optional[\n        Any\n    ] = dependency_provider,\n    wrap_model: Callable[\n        [CallModel[P, T]], CallModel[P, T]\n    ] = lambda: x\n) -> Union[Callable[P, T], _InjectWrapper[P, T]]\n
Source code in fast_depends/use.py
def inject(\n    func: Optional[Callable[P, T]] = None,\n    *,\n    cast: bool = True,\n    extra_dependencies: Sequence[model.Depends] = (),\n    pydantic_config: Optional[ConfigDict] = None,\n    dependency_overrides_provider: Optional[Any] = dependency_provider,\n    wrap_model: Callable[[CallModel[P, T]], CallModel[P, T]] = lambda x: x,\n) -> Union[Callable[P, T], _InjectWrapper[P, T],]:\n    decorator = _wrap_inject(\n        dependency_overrides_provider=dependency_overrides_provider,\n        wrap_model=wrap_model,\n        extra_dependencies=extra_dependencies,\n        cast=cast,\n        pydantic_config=pydantic_config,\n    )\n\n    if func is None:\n        return decorator\n\n    else:\n        return decorator(func)\n
","boost":0.5},{"location":"api/faststream/utils/ast/find_ast_node/","title":"find_ast_node","text":"","boost":0.5},{"location":"api/faststream/utils/ast/find_ast_node/#faststream.utils.ast.find_ast_node","title":"faststream.utils.ast.find_ast_node","text":"
find_ast_node(\n    module: ast.Module, lineno: Optional[int]\n) -> Optional[ast.AST]\n
Source code in faststream/utils/ast.py
def find_ast_node(module: ast.Module, lineno: Optional[int]) -> Optional[ast.AST]:\n    if lineno is not None:  # pragma: no branch\n        for i in getattr(module, \"body\", ()):\n            if i.lineno == lineno:\n                return cast(ast.AST, i)\n\n            r = find_ast_node(i, lineno)\n            if r is not None:\n                return r\n\n    return None\n
","boost":0.5},{"location":"api/faststream/utils/ast/find_withitems/","title":"find_withitems","text":"","boost":0.5},{"location":"api/faststream/utils/ast/find_withitems/#faststream.utils.ast.find_withitems","title":"faststream.utils.ast.find_withitems","text":"
find_withitems(\n    node: Union[ast.With, ast.AsyncWith]\n) -> Iterator[ast.withitem]\n
Source code in faststream/utils/ast.py
def find_withitems(node: Union[ast.With, ast.AsyncWith]) -> Iterator[ast.withitem]:\n    if isinstance(node, (ast.With, ast.AsyncWith)):\n        yield from node.items\n\n    for i in getattr(node, \"body\", ()):\n        yield from find_withitems(i)\n
","boost":0.5},{"location":"api/faststream/utils/ast/get_withitem_calls/","title":"get_withitem_calls","text":"","boost":0.5},{"location":"api/faststream/utils/ast/get_withitem_calls/#faststream.utils.ast.get_withitem_calls","title":"faststream.utils.ast.get_withitem_calls","text":"
get_withitem_calls(\n    node: Union[ast.With, ast.AsyncWith]\n) -> List[str]\n
Source code in faststream/utils/ast.py
def get_withitem_calls(node: Union[ast.With, ast.AsyncWith]) -> List[str]:\n    return [\n        id\n        for i in find_withitems(node)\n        if (id := getattr(i.context_expr.func, \"id\", None))  # type: ignore[attr-defined]\n    ]\n
","boost":0.5},{"location":"api/faststream/utils/ast/is_contains_context_name/","title":"is_contains_context_name","text":"","boost":0.5},{"location":"api/faststream/utils/ast/is_contains_context_name/#faststream.utils.ast.is_contains_context_name","title":"faststream.utils.ast.is_contains_context_name","text":"
is_contains_context_name(scip_name: str, name: str) -> bool\n
Source code in faststream/utils/ast.py
def is_contains_context_name(scip_name: str, name: str) -> bool:\n    stack = traceback.extract_stack()[-3]\n    tree = read_source_ast(stack.filename)\n    node = cast(Union[ast.With, ast.AsyncWith], find_ast_node(tree, stack.lineno))\n    context_calls = get_withitem_calls(node)\n\n    try:\n        pos = context_calls.index(scip_name)\n    except ValueError:\n        pos = 1\n\n    return name in context_calls[pos:]\n
","boost":0.5},{"location":"api/faststream/utils/classes/Singleton/","title":"Singleton","text":"","boost":0.5},{"location":"api/faststream/utils/classes/Singleton/#faststream.utils.classes.Singleton","title":"faststream.utils.classes.Singleton","text":"

A class to implement the Singleton design pattern.

METHOD DESCRIPTION __new__

creates a new instance of the class if it doesn't exist, otherwise returns the existing instance

_drop

sets the instance to None, allowing a new instance to be created

","boost":0.5},{"location":"api/faststream/utils/context/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/utils/context/Context/#faststream.utils.context.Context","title":"faststream.utils.context.Context","text":"
Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/","title":"ContextRepo","text":"","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo","title":"faststream.utils.context.ContextRepo","text":"
ContextRepo()\n

Bases: Singleton

A class to represent a context repository.

METHOD DESCRIPTION __init__

initializes the ContextRepo object

set_global

sets a global context variable

reset_global

resets a global context variable

set_local

sets a local context variable

reset_local

resets a local context variable

get_local

gets the value of a local context variable

clear

clears the global and scope context

get

gets the value of a context variable

__getattr__

gets the value of a context variable using attribute access

context

gets the current context as a dictionary

scope

creates a context scope for a specific key and value

Initialize the class.

Source code in faststream/utils/context/main.py
def __init__(self) -> None:\n    \"\"\"Initialize the class.\n\n    Attributes:\n        _global_context : a dictionary representing the global context\n        _scope_context : a dictionary representing the scope context\n    \"\"\"\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.context","title":"context property","text":"
context: AnyDict\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.clear","title":"clear","text":"
clear() -> None\n
Source code in faststream/utils/context/main.py
def clear(self) -> None:\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.get","title":"get","text":"
get(key: str, default: Any = None) -> Any\n

Get the value associated with a key.

PARAMETER DESCRIPTION key

The key to retrieve the value for.

TYPE: str

RETURNS DESCRIPTION Any

The value associated with the key.

Source code in faststream/utils/context/main.py
def get(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value associated with a key.\n\n    Args:\n        key: The key to retrieve the value for.\n\n    Returns:\n        The value associated with the key.\n    \"\"\"\n    return self._global_context.get(key, self.get_local(key, default))\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.get_local","title":"get_local","text":"
get_local(key: str, default: Any = None) -> Any\n

Get the value of a local variable.

PARAMETER DESCRIPTION key

The key of the local variable to retrieve.

TYPE: str

RETURNS DESCRIPTION Any

The value of the local variable.

Source code in faststream/utils/context/main.py
def get_local(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value of a local variable.\n\n    Args:\n        key: The key of the local variable to retrieve.\n\n    Returns:\n        The value of the local variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is not None:  # pragma: no branch\n        return context_var.get()\n    else:\n        return default\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.reset_global","title":"reset_global","text":"
reset_global(key: str) -> None\n

Resets a key in the global context.

PARAMETER DESCRIPTION key

The key to reset in the global context.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_global(self, key: str) -> None:\n    \"\"\"Resets a key in the global context.\n\n    Args:\n        key (str): The key to reset in the global context.\n\n    Returns:\n        None\n    \"\"\"\n    self._global_context.pop(key, None)\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.reset_local","title":"reset_local","text":"
reset_local(key: str, tag: Token[Any]) -> None\n

Resets the local context for a given key.

PARAMETER DESCRIPTION key

The key to reset the local context for.

TYPE: str

tag

The tag associated with the local context.

TYPE: Token[Any]

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_local(self, key: str, tag: \"Token[Any]\") -> None:\n    \"\"\"Resets the local context for a given key.\n\n    Args:\n        key (str): The key to reset the local context for.\n        tag (Token[Any]): The tag associated with the local context.\n\n    Returns:\n        None\n    \"\"\"\n    self._scope_context[key].reset(tag)\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.resolve","title":"resolve","text":"
resolve(argument: str) -> Any\n

Resolve the context of an argument.

PARAMETER DESCRIPTION argument

A string representing the argument.

TYPE: str

RETURNS DESCRIPTION Any

The resolved context of the argument.

RAISES DESCRIPTION AttributeError

If the attribute does not exist in the context.

Source code in faststream/utils/context/main.py
def resolve(self, argument: str) -> Any:\n    \"\"\"Resolve the context of an argument.\n\n    Args:\n        argument: A string representing the argument.\n\n    Returns:\n        The resolved context of the argument.\n\n    Raises:\n        AttributeError: If the attribute does not exist in the context.\n    \"\"\"\n    first, *keys = argument.split(\".\")\n\n    if (v := self.get(first, _empty)) is _empty:\n        raise KeyError(f\"`{self.context}` does not contains `{first}` key\")\n\n    for i in keys:\n        if isinstance(v, Mapping):\n            v = v[i]\n        else:\n            v = getattr(v, i)\n    return v\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.scope","title":"scope","text":"
scope(key: str, value: Any) -> Iterator[None]\n

Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.

PARAMETER DESCRIPTION key

The key of the local variable

TYPE: str

value

The value to set the local variable to

TYPE: Any

YIELDS DESCRIPTION Iterator[None]

None

RETURNS DESCRIPTION Iterator[None]

An iterator that yields None

Source code in faststream/utils/context/main.py
@contextmanager\ndef scope(self, key: str, value: Any) -> Iterator[None]:\n    \"\"\"Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.\n\n    Args:\n        key: The key of the local variable\n        value: The value to set the local variable to\n\n    Yields:\n        None\n\n    Returns:\n        An iterator that yields None\n    \"\"\"\n    token = self.set_local(key, value)\n    try:\n        yield\n    finally:\n        self.reset_local(key, token)\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.set_global","title":"set_global","text":"
set_global(key: str, v: Any) -> None\n

Sets a value in the global context.

PARAMETER DESCRIPTION key

The key to set in the global context.

TYPE: str

v

The value to set.

TYPE: Any

RETURNS DESCRIPTION None

None.

Source code in faststream/utils/context/main.py
def set_global(self, key: str, v: Any) -> None:\n    \"\"\"Sets a value in the global context.\n\n    Args:\n        key: The key to set in the global context.\n        v: The value to set.\n\n    Returns:\n        None.\n    \"\"\"\n    self._global_context[key] = v\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.set_local","title":"set_local","text":"
set_local(key: str, value: T) -> Token[T]\n

Set a local context variable.

PARAMETER DESCRIPTION key

The key for the context variable.

TYPE: str

value

The value to set for the context variable.

TYPE: T

RETURNS DESCRIPTION Token[T]

Token[T]: A token representing the context variable.

Source code in faststream/utils/context/main.py
def set_local(self, key: str, value: T) -> \"Token[T]\":\n    \"\"\"Set a local context variable.\n\n    Args:\n        key (str): The key for the context variable.\n        value (T): The value to set for the context variable.\n\n    Returns:\n        Token[T]: A token representing the context variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is None:\n        context_var = ContextVar(key, default=None)\n        self._scope_context[key] = context_var\n    return context_var.set(value)\n
","boost":0.5},{"location":"api/faststream/utils/context/Header/","title":"Header","text":"","boost":0.5},{"location":"api/faststream/utils/context/Header/#faststream.utils.context.Header","title":"faststream.utils.context.Header","text":"
Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.headers.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/Path/","title":"Path","text":"","boost":0.5},{"location":"api/faststream/utils/context/Path/#faststream.utils.context.Path","title":"faststream.utils.context.Path","text":"
Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.path.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/builders/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/utils/context/builders/Context/#faststream.utils.context.builders.Context","title":"faststream.utils.context.builders.Context","text":"
Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/builders/Header/","title":"Header","text":"","boost":0.5},{"location":"api/faststream/utils/context/builders/Header/#faststream.utils.context.builders.Header","title":"faststream.utils.context.builders.Header","text":"
Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.headers.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/builders/Path/","title":"Path","text":"","boost":0.5},{"location":"api/faststream/utils/context/builders/Path/#faststream.utils.context.builders.Path","title":"faststream.utils.context.builders.Path","text":"
Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.path.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/","title":"ContextRepo","text":"","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo","title":"faststream.utils.context.main.ContextRepo","text":"
ContextRepo()\n

Bases: Singleton

A class to represent a context repository.

METHOD DESCRIPTION __init__

initializes the ContextRepo object

set_global

sets a global context variable

reset_global

resets a global context variable

set_local

sets a local context variable

reset_local

resets a local context variable

get_local

gets the value of a local context variable

clear

clears the global and scope context

get

gets the value of a context variable

__getattr__

gets the value of a context variable using attribute access

context

gets the current context as a dictionary

scope

creates a context scope for a specific key and value

Initialize the class.

Source code in faststream/utils/context/main.py
def __init__(self) -> None:\n    \"\"\"Initialize the class.\n\n    Attributes:\n        _global_context : a dictionary representing the global context\n        _scope_context : a dictionary representing the scope context\n    \"\"\"\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.context","title":"context property","text":"
context: AnyDict\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.clear","title":"clear","text":"
clear() -> None\n
Source code in faststream/utils/context/main.py
def clear(self) -> None:\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.get","title":"get","text":"
get(key: str, default: Any = None) -> Any\n

Get the value associated with a key.

PARAMETER DESCRIPTION key

The key to retrieve the value for.

TYPE: str

RETURNS DESCRIPTION Any

The value associated with the key.

Source code in faststream/utils/context/main.py
def get(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value associated with a key.\n\n    Args:\n        key: The key to retrieve the value for.\n\n    Returns:\n        The value associated with the key.\n    \"\"\"\n    return self._global_context.get(key, self.get_local(key, default))\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.get_local","title":"get_local","text":"
get_local(key: str, default: Any = None) -> Any\n

Get the value of a local variable.

PARAMETER DESCRIPTION key

The key of the local variable to retrieve.

TYPE: str

RETURNS DESCRIPTION Any

The value of the local variable.

Source code in faststream/utils/context/main.py
def get_local(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value of a local variable.\n\n    Args:\n        key: The key of the local variable to retrieve.\n\n    Returns:\n        The value of the local variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is not None:  # pragma: no branch\n        return context_var.get()\n    else:\n        return default\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.reset_global","title":"reset_global","text":"
reset_global(key: str) -> None\n

Resets a key in the global context.

PARAMETER DESCRIPTION key

The key to reset in the global context.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_global(self, key: str) -> None:\n    \"\"\"Resets a key in the global context.\n\n    Args:\n        key (str): The key to reset in the global context.\n\n    Returns:\n        None\n    \"\"\"\n    self._global_context.pop(key, None)\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.reset_local","title":"reset_local","text":"
reset_local(key: str, tag: Token[Any]) -> None\n

Resets the local context for a given key.

PARAMETER DESCRIPTION key

The key to reset the local context for.

TYPE: str

tag

The tag associated with the local context.

TYPE: Token[Any]

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_local(self, key: str, tag: \"Token[Any]\") -> None:\n    \"\"\"Resets the local context for a given key.\n\n    Args:\n        key (str): The key to reset the local context for.\n        tag (Token[Any]): The tag associated with the local context.\n\n    Returns:\n        None\n    \"\"\"\n    self._scope_context[key].reset(tag)\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.resolve","title":"resolve","text":"
resolve(argument: str) -> Any\n

Resolve the context of an argument.

PARAMETER DESCRIPTION argument

A string representing the argument.

TYPE: str

RETURNS DESCRIPTION Any

The resolved context of the argument.

RAISES DESCRIPTION AttributeError

If the attribute does not exist in the context.

Source code in faststream/utils/context/main.py
def resolve(self, argument: str) -> Any:\n    \"\"\"Resolve the context of an argument.\n\n    Args:\n        argument: A string representing the argument.\n\n    Returns:\n        The resolved context of the argument.\n\n    Raises:\n        AttributeError: If the attribute does not exist in the context.\n    \"\"\"\n    first, *keys = argument.split(\".\")\n\n    if (v := self.get(first, _empty)) is _empty:\n        raise KeyError(f\"`{self.context}` does not contains `{first}` key\")\n\n    for i in keys:\n        if isinstance(v, Mapping):\n            v = v[i]\n        else:\n            v = getattr(v, i)\n    return v\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.scope","title":"scope","text":"
scope(key: str, value: Any) -> Iterator[None]\n

Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.

PARAMETER DESCRIPTION key

The key of the local variable

TYPE: str

value

The value to set the local variable to

TYPE: Any

YIELDS DESCRIPTION Iterator[None]

None

RETURNS DESCRIPTION Iterator[None]

An iterator that yields None

Source code in faststream/utils/context/main.py
@contextmanager\ndef scope(self, key: str, value: Any) -> Iterator[None]:\n    \"\"\"Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.\n\n    Args:\n        key: The key of the local variable\n        value: The value to set the local variable to\n\n    Yields:\n        None\n\n    Returns:\n        An iterator that yields None\n    \"\"\"\n    token = self.set_local(key, value)\n    try:\n        yield\n    finally:\n        self.reset_local(key, token)\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.set_global","title":"set_global","text":"
set_global(key: str, v: Any) -> None\n

Sets a value in the global context.

PARAMETER DESCRIPTION key

The key to set in the global context.

TYPE: str

v

The value to set.

TYPE: Any

RETURNS DESCRIPTION None

None.

Source code in faststream/utils/context/main.py
def set_global(self, key: str, v: Any) -> None:\n    \"\"\"Sets a value in the global context.\n\n    Args:\n        key: The key to set in the global context.\n        v: The value to set.\n\n    Returns:\n        None.\n    \"\"\"\n    self._global_context[key] = v\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.set_local","title":"set_local","text":"
set_local(key: str, value: T) -> Token[T]\n

Set a local context variable.

PARAMETER DESCRIPTION key

The key for the context variable.

TYPE: str

value

The value to set for the context variable.

TYPE: T

RETURNS DESCRIPTION Token[T]

Token[T]: A token representing the context variable.

Source code in faststream/utils/context/main.py
def set_local(self, key: str, value: T) -> \"Token[T]\":\n    \"\"\"Set a local context variable.\n\n    Args:\n        key (str): The key for the context variable.\n        value (T): The value to set for the context variable.\n\n    Returns:\n        Token[T]: A token representing the context variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is None:\n        context_var = ContextVar(key, default=None)\n        self._scope_context[key] = context_var\n    return context_var.set(value)\n
","boost":0.5},{"location":"api/faststream/utils/context/path/compile_path/","title":"compile_path","text":"","boost":0.5},{"location":"api/faststream/utils/context/path/compile_path/#faststream.utils.context.path.compile_path","title":"faststream.utils.context.path.compile_path","text":"
compile_path(\n    path: str, replace_symbol: str\n) -> Tuple[Optional[Pattern[str]], str]\n
Source code in faststream/utils/context/path.py
def compile_path(\n    path: str,\n    replace_symbol: str,\n) -> Tuple[Optional[Pattern[str]], str]:\n    path_regex = \"^\"\n    path_format = \"\"\n\n    idx = 0\n    params = set()\n    duplicated_params = set()\n    for match in PARAM_REGEX.finditer(path):\n        param_name = match.groups(\"str\")[0]\n\n        path_regex += re.escape(path[idx : match.start()])\n        path_regex += f\"(?P<{param_name.replace('+', '')}>[^/]+)\"\n\n        path_format += path[idx : match.start()]\n        path_format += replace_symbol\n\n        if param_name in params:\n            duplicated_params.add(param_name)\n        else:\n            params.add(param_name)\n\n        idx = match.end()\n\n    if duplicated_params:\n        names = \", \".join(sorted(duplicated_params))\n        ending = \"s\" if len(duplicated_params) > 1 else \"\"\n        raise ValueError(f\"Duplicated param name{ending} {names} at path {path}\")\n\n    if idx == 0:\n        regex = None\n    else:\n        path_regex += re.escape(path[idx:]) + \"$\"\n        regex = re.compile(path_regex)\n\n    path_format += path[idx:]\n    return regex, path_format\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context","title":"faststream.utils.context.types.Context","text":"
Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n    prefix: str = \"\"\n)\n

Bases: CustomField

A class to represent a context.

METHOD DESCRIPTION __init__

constructor method

use

method to use the context

Initialize the object.

PARAMETER DESCRIPTION real_name

The real name of the object.

TYPE: str DEFAULT: ''

cast

Whether to cast the object.

TYPE: bool DEFAULT: False

default

The default value of the object.

TYPE: Any DEFAULT: _empty

RAISES DESCRIPTION TypeError

If the default value is not provided.

Source code in faststream/utils/context/types.py
def __init__(\n    self,\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n    prefix: str = \"\",\n) -> None:\n    \"\"\"Initialize the object.\n\n    Args:\n        real_name: The real name of the object.\n        cast: Whether to cast the object.\n        default: The default value of the object.\n\n    Raises:\n        TypeError: If the default value is not provided.\n    \"\"\"\n    self.name = real_name\n    self.default = default\n    self.prefix = prefix\n    super().__init__(\n        cast=cast,\n        required=(default is _empty),\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.cast","title":"cast instance-attribute","text":"
cast: bool = cast\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.default","title":"default instance-attribute","text":"
default = default\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.name","title":"name instance-attribute","text":"
name = real_name\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.param_name","title":"param_name instance-attribute","text":"
param_name: str\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.required","title":"required instance-attribute","text":"
required: bool = required\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.set_param_name","title":"set_param_name","text":"
set_param_name(name: str) -> Cls\n
Source code in fast_depends/library/model.py
def set_param_name(self: Cls, name: str) -> Cls:\n    self.param_name = name\n    return self\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.use","title":"use","text":"
use(**kwargs: Any) -> AnyDict\n

Use the given keyword arguments.

PARAMETER DESCRIPTION **kwargs

Keyword arguments to be used

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION AnyDict

A dictionary containing the updated keyword arguments

RAISES DESCRIPTION KeyError

If the parameter name is not found in the keyword arguments

AttributeError

If the parameter name is not a valid attribute

Source code in faststream/utils/context/types.py
def use(self, /, **kwargs: Any) -> AnyDict:\n    \"\"\"Use the given keyword arguments.\n\n    Args:\n        **kwargs: Keyword arguments to be used\n\n    Returns:\n        A dictionary containing the updated keyword arguments\n\n    Raises:\n        KeyError: If the parameter name is not found in the keyword arguments\n        AttributeError: If the parameter name is not a valid attribute\n    \"\"\"\n    name = f\"{self.prefix}{self.name or self.param_name}\"\n\n    try:\n        kwargs[self.param_name] = context.resolve(name)\n    except (KeyError, AttributeError):\n        if self.required is False:\n            kwargs[self.param_name] = self.default\n\n    return kwargs\n
","boost":0.5},{"location":"api/faststream/utils/data/filter_by_dict/","title":"filter_by_dict","text":"","boost":0.5},{"location":"api/faststream/utils/data/filter_by_dict/#faststream.utils.data.filter_by_dict","title":"faststream.utils.data.filter_by_dict","text":"
filter_by_dict(\n    typed_dict: Type[TypedDictCls], data: AnyDict\n) -> TypedDictCls\n

Filter a dictionary based on a typed dictionary.

PARAMETER DESCRIPTION typed_dict

The typed dictionary to filter by.

TYPE: Type[TypedDictCls]

data

The dictionary to filter.

TYPE: AnyDict

RETURNS DESCRIPTION TypedDictCls

A new instance of the typed dictionary with only the keys present in the data dictionary.

Source code in faststream/utils/data.py
def filter_by_dict(typed_dict: Type[TypedDictCls], data: AnyDict) -> TypedDictCls:\n    \"\"\"Filter a dictionary based on a typed dictionary.\n\n    Args:\n        typed_dict: The typed dictionary to filter by.\n        data: The dictionary to filter.\n\n    Returns:\n        A new instance of the typed dictionary with only the keys present in the data dictionary.\n    \"\"\"\n    annotations = typed_dict.__annotations__\n    return typed_dict(  # type: ignore\n        {k: v for k, v in data.items() if k in annotations}\n    )\n
","boost":0.5},{"location":"api/faststream/utils/functions/call_or_await/","title":"call_or_await","text":"","boost":0.5},{"location":"api/faststream/utils/functions/call_or_await/#fast_depends.utils.run_async","title":"fast_depends.utils.run_async async","text":"
run_async(\n    func: Union[Callable[P, T], Callable[P, Awaitable[T]]],\n    *args: P.args,\n    **kwargs: P.kwargs\n) -> T\n
Source code in fast_depends/utils.py
async def run_async(\n    func: Union[\n        Callable[P, T],\n        Callable[P, Awaitable[T]],\n    ],\n    *args: P.args,\n    **kwargs: P.kwargs,\n) -> T:\n    if is_coroutine_callable(func):\n        return await cast(Callable[P, Awaitable[T]], func)(*args, **kwargs)\n    else:\n        return await run_in_threadpool(cast(Callable[P, T], func), *args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/utils/functions/drop_response_type/","title":"drop_response_type","text":"","boost":0.5},{"location":"api/faststream/utils/functions/drop_response_type/#faststream.utils.functions.drop_response_type","title":"faststream.utils.functions.drop_response_type","text":"
drop_response_type(\n    model: CallModel[F_Spec, F_Return]\n) -> CallModel[F_Spec, F_Return]\n
Source code in faststream/utils/functions.py
def drop_response_type(\n    model: CallModel[F_Spec, F_Return]\n) -> CallModel[F_Spec, F_Return]:\n    model.response_model = None\n    return model\n
","boost":0.5},{"location":"api/faststream/utils/functions/fake_context/","title":"fake_context","text":"","boost":0.5},{"location":"api/faststream/utils/functions/fake_context/#faststream.utils.functions.fake_context","title":"faststream.utils.functions.fake_context async","text":"
fake_context(\n    *args: Any, **kwargs: Any\n) -> AsyncIterator[None]\n
Source code in faststream/utils/functions.py
@asynccontextmanager\nasync def fake_context(*args: Any, **kwargs: Any) -> AsyncIterator[None]:\n    yield None\n
","boost":0.5},{"location":"api/faststream/utils/functions/get_function_positional_arguments/","title":"get_function_positional_arguments","text":"","boost":0.5},{"location":"api/faststream/utils/functions/get_function_positional_arguments/#faststream.utils.functions.get_function_positional_arguments","title":"faststream.utils.functions.get_function_positional_arguments","text":"
get_function_positional_arguments(\n    func: AnyCallable,\n) -> List[str]\n

Get the positional arguments of a function.

PARAMETER DESCRIPTION func

The function to get the positional arguments from.

TYPE: AnyCallable

RETURNS DESCRIPTION List[str]

A list of strings representing the names of the positional arguments.

Source code in faststream/utils/functions.py
def get_function_positional_arguments(func: AnyCallable) -> List[str]:\n    \"\"\"Get the positional arguments of a function.\n\n    Args:\n        func: The function to get the positional arguments from.\n\n    Returns:\n        A list of strings representing the names of the positional arguments.\n    \"\"\"\n    signature = inspect.signature(func)\n\n    arg_kinds = (\n        inspect.Parameter.POSITIONAL_ONLY,\n        inspect.Parameter.POSITIONAL_OR_KEYWORD,\n    )\n\n    return [\n        param.name for param in signature.parameters.values() if param.kind in arg_kinds\n    ]\n
","boost":0.5},{"location":"api/faststream/utils/functions/timeout_scope/","title":"timeout_scope","text":"","boost":0.5},{"location":"api/faststream/utils/functions/timeout_scope/#faststream.utils.functions.timeout_scope","title":"faststream.utils.functions.timeout_scope","text":"
timeout_scope(\n    timeout: Optional[float] = 30,\n    raise_timeout: bool = False,\n) -> ContextManager[anyio.CancelScope]\n
Source code in faststream/utils/functions.py
def timeout_scope(\n    timeout: Optional[float] = 30,\n    raise_timeout: bool = False,\n) -> ContextManager[anyio.CancelScope]:\n    scope: Callable[[Optional[float]], ContextManager[anyio.CancelScope]]\n    if raise_timeout:\n        scope = anyio.fail_after\n    else:\n        scope = anyio.move_on_after\n\n    return scope(timeout)\n
","boost":0.5},{"location":"api/faststream/utils/functions/to_async/","title":"to_async","text":"","boost":0.5},{"location":"api/faststream/utils/functions/to_async/#faststream.utils.functions.to_async","title":"faststream.utils.functions.to_async","text":"
to_async(\n    func: Union[\n        Callable[F_Spec, F_Return],\n        Callable[F_Spec, Awaitable[F_Return]],\n    ]\n) -> Callable[F_Spec, Awaitable[F_Return]]\n

Converts a synchronous function to an asynchronous function.

PARAMETER DESCRIPTION func

The synchronous function to be converted.

TYPE: Union[Callable[F_Spec, F_Return], Callable[F_Spec, Awaitable[F_Return]]]

RETURNS DESCRIPTION Callable[F_Spec, Awaitable[F_Return]]

The asynchronous version of the input function.

Source code in faststream/utils/functions.py
def to_async(\n    func: Union[\n        Callable[F_Spec, F_Return],\n        Callable[F_Spec, Awaitable[F_Return]],\n    ]\n) -> Callable[F_Spec, Awaitable[F_Return]]:\n    \"\"\"Converts a synchronous function to an asynchronous function.\n\n    Args:\n        func: The synchronous function to be converted.\n\n    Returns:\n        The asynchronous version of the input function.\n    \"\"\"\n\n    @wraps(func)\n    async def to_async_wrapper(*args: F_Spec.args, **kwargs: F_Spec.kwargs) -> F_Return:\n        \"\"\"Wraps a function to make it asynchronous.\n\n        Args:\n            func: The function to be wrapped\n            args: Positional arguments to be passed to the function\n            kwargs: Keyword arguments to be passed to the function\n\n        Returns:\n            The result of the wrapped function\n\n        Raises:\n            Any exceptions raised by the wrapped function\n        \"\"\"\n        return await call_or_await(func, *args, **kwargs)\n\n    return to_async_wrapper\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/","title":"NoCast","text":"","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast","title":"faststream.utils.no_cast.NoCast","text":"
NoCast()\n

Bases: CustomField

A class that represents a custom field without casting.

METHOD DESCRIPTION __init__

Initializes the NoCast object.

use

Returns the provided keyword arguments as a dictionary.

Source code in faststream/utils/no_cast.py
def __init__(self) -> None:\n    super().__init__(cast=False)\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast.cast","title":"cast instance-attribute","text":"
cast: bool = cast\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast.param_name","title":"param_name instance-attribute","text":"
param_name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast.required","title":"required instance-attribute","text":"
required: bool = required\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast.set_param_name","title":"set_param_name","text":"
set_param_name(name: str) -> Cls\n
Source code in fast_depends/library/model.py
def set_param_name(self: Cls, name: str) -> Cls:\n    self.param_name = name\n    return self\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast.use","title":"use","text":"
use(**kwargs: Any) -> AnyDict\n

Return a dictionary containing the keyword arguments passed to the function.

PARAMETER DESCRIPTION **kwargs

Keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION AnyDict

Dictionary containing the keyword arguments

Source code in faststream/utils/no_cast.py
def use(self, **kwargs: Any) -> AnyDict:\n    \"\"\"Return a dictionary containing the keyword arguments passed to the function.\n\n    Args:\n        **kwargs: Keyword arguments\n\n    Returns:\n        Dictionary containing the keyword arguments\n    \"\"\"\n    return kwargs\n
","boost":0.5},{"location":"getting-started/","title":"QUICK START","text":"

Install using pip:

KafkaRabbitMQNATSRedis
pip install \"faststream[kafka]\"\n

Tip

To start a new project, we need a test broker container

docker run -d --rm -p 9092:9092 --name test-mq \\\n-e KAFKA_ENABLE_KRAFT=yes \\\n-e KAFKA_CFG_NODE_ID=1 \\\n-e KAFKA_CFG_PROCESS_ROLES=broker,controller \\\n-e KAFKA_CFG_CONTROLLER_LISTENER_NAMES=CONTROLLER \\\n-e KAFKA_CFG_LISTENERS=PLAINTEXT://:9092,CONTROLLER://:9093 \\\n-e KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP=CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT \\\n-e KAFKA_CFG_ADVERTISED_LISTENERS=PLAINTEXT://127.0.0.1:9092 \\\n-e KAFKA_BROKER_ID=1 \\\n-e KAFKA_CFG_CONTROLLER_QUORUM_VOTERS=1@kafka:9093 \\\n-e ALLOW_PLAINTEXT_LISTENER=yes \\\nbitnami/kafka:3.5.0\n

pip install \"faststream[rabbit]\"\n

Tip

To start a new project, we need a test broker container

docker run -d --rm -p 5672:5672 --name test-mq rabbitmq:alpine\n

pip install \"faststream[nats]\"\n

Tip

To start a new project, we need a test broker container

bash docker run -d --rm -p 4222:4222 --name test-mq nats -js\n

pip install \"faststream[redis]\"\n

Tip

To start a new project, we need a test broker container

bash docker run -d --rm -p 6379:6379 --name test-mq redis\n

","boost":10},{"location":"getting-started/#basic-usage","title":"Basic Usage","text":"

To create a basic application, add the following code to a new file (e.g. serve.py):

KafkaRabbitMQNATSRedis serve.py
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n
serve.py
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\n\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n
serve.py
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\n\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n
serve.py
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\n\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n

And just run this command:

faststream run serve:app\n

After running the command, you should see the following output:

Enjoy your new development experience!

Don't forget to stop the test broker container
docker container stop test-mq\n
","boost":10},{"location":"getting-started/logging/","title":"Application and Access Logging","text":"

FastStream uses two already configured loggers:

","boost":10},{"location":"getting-started/logging/#logging-requests","title":"Logging Requests","text":"

To log requests, it is strongly recommended to use the access_logger of your broker, as it is available from the Context of your application.

from faststream import Logger\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker()\n\n@broker.subscriber(\"test\")\nasync def func(logger: Logger):\n    logger.info(\"message received\")\n

This approach offers several advantages:

","boost":10},{"location":"getting-started/logging/#logging-levels","title":"Logging Levels","text":"

If you use the FastStream CLI, you can change the current logging level of the entire application directly from the command line.

The --log-level flag sets the current logging level for both the broker and the FastStream app. This allows you to configure the levels of not only the default loggers but also your custom loggers, if you use them inside FastStream.

faststream run serve:app --log-level debug\n

If you want to completely disable the default logging of FastStream, you can set logger=None

from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(logger=None)     # Disables broker logs\napp = FastStream(broker, logger=None)  # Disables application logs\n

Warning

Be careful: the logger that you get from the context will also have the value None if you turn off broker logging.

If you don't want to lose access to the `logger' inside your context but want to disable the default logs of FastStream, you can lower the level of logs that the broker publishes itself.

import logging\nfrom faststream.rabbit import RabbitBroker\n\n# Sets the broker logs to the DEBUG level\nbroker = RabbitBroker(log_level=logging.DEBUG)\n
","boost":10},{"location":"getting-started/logging/#formatting-logs","title":"Formatting Logs","text":"

If you are not satisfied with the current format of your application logs, you can change it directly in your broker's constructor.

from faststream.rabbit import RabbitBroker\nbroker = RabbitBroker(log_fmt=\"%(asctime)s %(levelname)s - %(message)s\")\n
","boost":10},{"location":"getting-started/logging/#logger-access","title":"Logger Access","text":"

If you want to override default logger's behavior, you can access them directly via logging.

import logging\nlogger = logging.getLogger(\"faststream\")\naccess_logger = logging.getLogger(\"faststream.access\")\n

Or you can import them from FastStream.

from faststream.log import access_logger, logger\n
","boost":10},{"location":"getting-started/logging/#using-your-own-loggers","title":"Using Your Own Loggers","text":"

Since FastStream works with the standard logging.Logger object, you can initiate an application and a broker using your own logger.

import logging\nfrom faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nlogger = logging.getLogger(\"my_logger\")\n\nbroker = RabbitBroker(logger=logger)\napp = FastStream(broker, logger=logger)\n

Note

Doing this, you doesn't change the CLI logs behavior (multiprocessing and hot reload logs). This was done to keep your log storage clear of unnecessary stuff.

This logger will be used only for FastStream and StreamBroker service messages and will be passed to your function through the Context.

By doing this, you will lose information about the context of the current request. However, you can retrieve it directly from the context anywhere in your code.

from faststream import context\nlog_context: dict[str, str] = context.get_local(\"log_context\")\n

This way, all broker handlers can get access to your broker logger right from the context:

from faststream import Logger\n\n@broker.subscriber(...)\nasync def handler(\n    msg,\n    logger: Logger,  # <-- YOUR logger here\n):\n    logger.info(msg)\n
","boost":10},{"location":"getting-started/logging/#structlog-example","title":"Structlog Example","text":"

Structlog is a production-ready logging solution for Python. It can be easely integrated with any log storage system, making it suitable for use in production projects.

Here is a quick tutorial on integrating Structlog with FastStream:

Start with the Structlog guide example:

import sys\nimport structlog\n\nshared_processors = [\n    structlog.processors.add_log_level,\n    structlog.processors.StackInfoRenderer(),\n    structlog.dev.set_exc_info,\n    structlog.processors.TimeStamper(fmt=\"iso\"),\n]\n\nif sys.stderr.isatty():\n    # terminal session\n    processors = shared_processors + [\n        structlog.dev.ConsoleRenderer()\n    ]\nelse:\n    # Docker container session\n    processors = shared_processors + [\n        structlog.processors.dict_tracebacks,\n        structlog.processors.JSONRenderer(),\n    ]\n\nstructlog.configure(\n    processors=processors,\n    logger_factory=structlog.PrintLoggerFactory(),\n    cache_logger_on_first_use=False,\n)\n\nlogger = structlog.get_logger()\n

We created a logger that prints messages to the console in a user-friendly format during development and uses JSON-formatted logs in production.

To integrate this logger with our FastStream application, we just need to access it through context information and pass it to our objects:

import logging\n\nimport structlog\n\nfrom faststream import FastStream, context\nfrom faststream.kafka import KafkaBroker\n\ndef merge_contextvars(\n    logger: structlog.types.WrappedLogger,\n    method_name: str,\n    event_dict: structlog.types.EventDict,\n) -> structlog.types.EventDict:\n    event_dict[\"extra\"] = event_dict.get(\n        \"extra\",\n        context.get(\"log_context\", {}),\n    )\n    return event_dict\n\nshared_processors = [\n    merge_contextvars,\n    ...\n]\n\n...\n\nbroker = KafkaBroker(logger=logger, log_level=logging.DEBUG)\napp = FastStream(broker, logger=logger)\n

And the job is done! Now you have a perfectly structured logs using Structlog.

","boost":10},{"location":"getting-started/asyncapi/custom/","title":"Customizing AsyncAPI Documentation for FastStream","text":"

In this guide, we will explore how to customize AsyncAPI documentation for your FastStream application. Whether you want to add custom app info, broker information, handlers, or fine-tune payload details, we'll walk you through each step.

","boost":10},{"location":"getting-started/asyncapi/custom/#prerequisites","title":"Prerequisites","text":"

Before we dive into customization, ensure you have a basic FastStream application up and running. If you haven't done that yet, let's setup a simple appication right now.

Copy the following code in your basic.py file:

from faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaMessage\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n@broker.publisher(\"output_data\")\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg):\n    # your processing logic\n    pass\n

Now, when you run

faststream docs serve basic:app\n
you should see the following documentation:

","boost":10},{"location":"getting-started/asyncapi/custom/#setup-custom-faststream-app-info","title":"Setup Custom FastStream App Info","text":"

Let's start by customizing the app information that appears in your AsyncAPI documentation. This is a great way to give your documentation a personal touch. Here's how:

  1. Locate the app configuration in your FastStream application.
  2. Update the title, version, and description fields to reflect your application's details.
  3. Save the changes.
  4. Serve your FastStream app documentation.

Copy the following code in your basic.py file, we have highligted the additional info passed to FastStream app:

from faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaMessage\nfrom faststream.asyncapi.schema import Contact, ExternalDocs, License, Tag\n\nbroker = KafkaBroker(\"localhost:9092\")\ndescription=\"\"\"# Title of the description\nThis description supports **Markdown** syntax\"\"\"\napp = FastStream(\n    broker,\n    title=\"My App\",\n    version=\"1.0.0\",\n    description=description,\n    license=License(name=\"MIT\", url=\"https://opensource.org/license/mit/\"),\n    terms_of_service=\"https://my-terms.com/\",\n    contact=Contact(name=\"support\", url=\"https://help.com/\"),\n)\n\n@broker.publisher(\"output_data\")\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg):\n    # your processing logic\n    pass\n

Now, when you run

faststream docs serve basic:app\n
you should see the following in your general app documentation:

Now, your documentation reflects your application's identity and purpose.

Note

The description field in the above example supports Markdown text.

","boost":10},{"location":"getting-started/asyncapi/custom/#setup-custom-broker-information","title":"Setup Custom Broker Information","text":"

The next step is to customize broker information. This helps users understand the messaging system your application uses. Follow these steps:

  1. Locate the broker configuration in your FastStream application.
  2. Update the description field.
  3. Update the asyncapi_url field with a non-sensitive URL if you want to conceal your broker's actual bootstrap server URL.
  4. Save the changes.
  5. Serve your FastStream app.

Copy the following code in your basic.py file, we have highligted the additional info passed to the FastStream app broker:

from faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaMessage\nfrom faststream.asyncapi.schema import Tag\n\nbroker = KafkaBroker(\n    \"localhost:9092\",\n    description=\"Kafka broker running locally\",\n    asyncapi_url=\"non-sensitive-url:9092\",\n)\napp = FastStream(broker)\n\n\n@broker.publisher(\"output_data\")\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg):\n    # your processing logic\n    pass\n

Now, when you run

faststream docs serve basic:app\n
you should see the description in your broker documentation:

Your AsyncAPI documentation now provides clear insights into the messaging infrastructure you're using.

","boost":10},{"location":"getting-started/asyncapi/custom/#setup-custom-handler-information","title":"Setup Custom Handler Information","text":"

Customizing handler information helps users comprehend the purpose and behavior of each message handler. Here's how to do it:

  1. Navigate to your handler definitions in your FastStream application.
  2. Add descriptions to each handler using description field.
  3. For subscriber, consumer function's docstring can be used as description.
  4. Add titles to each handler using title field adhering to URI format.
  5. Add publishing schema to publisher handler using schema field.
  6. Save the changes.
  7. Serve your FastStream app.

Copy the following code in your basic.py file, we have highligted the additional info passed to the FastStream app handlers:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaMessage\n\n\nclass DataBasic(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.publisher(\n    \"output_data\",\n    description=\"My publisher description\",\n    title=\"output_data:Produce\",\n    schema=DataBasic,\n)\n@broker.subscriber(\n    \"input_data\", title=\"input_data:Consume\"\n)\nasync def on_input_data(msg):\n    \"\"\"Consumer function\n\n    Args:\n        msg: input msg\n    \"\"\"\n    # your processing logic\n    pass\n

Now, when you run

faststream docs serve basic:app\n
you should see the descriptions in your handlers:

Now, your documentation is enriched with meaningful details about each message handler.

","boost":10},{"location":"getting-started/asyncapi/custom/#setup-payload-information-via-pydantic-model","title":"Setup Payload Information via Pydantic Model","text":"

To describe your message payload effectively, you can use Pydantic models. Here's how:

  1. Define Pydantic models for your message payloads.
  2. Annotate these models with descriptions and examples.
  3. Use these models as argument types or return types in your handlers.
  4. Save the changes.
  5. Serve your FastStream app.

Copy the following code in your basic.py file, we have highligted the creation of payload info and you can see it being passed to the return type and the msg argument type in the on_input_data function:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\n\nclass DataBasic(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.publisher(\"output_data\")\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: DataBasic) -> DataBasic:\n    # your processing logic\n    pass\n

Now, when you run

faststream docs serve basic:app\n
you should see the payload schema described in your documentation:

Your AsyncAPI documentation now showcases well-structured payload information.

","boost":10},{"location":"getting-started/asyncapi/custom/#generate-schemajson-customize-and-serve-it","title":"Generate Schema.json, customize and serve it","text":"

To take customization to the next level, you can manually modify the schema.json file. Follow these steps:

  1. Generate the initial schema.json by running
    faststream docs gen basic:app\n
  2. Manually edit the asyncapi.json file to add custom fields, descriptions, and details.
  3. Save your changes.
  4. Serve your FastStream app with the updated asyncapi.json by running
    faststream docs serve asyncapi.json\n

Now, you have fine-tuned control over your AsyncAPI documentation.

","boost":10},{"location":"getting-started/asyncapi/custom/#conclusion","title":"Conclusion","text":"

Customizing AsyncAPI documentation for your FastStream application not only enhances its appearance but also provides valuable insights to users. With these steps, you can create documentation that's not only informative but also uniquely yours.

Happy coding with your customized FastStream AsyncAPI documentation!

","boost":10},{"location":"getting-started/asyncapi/export/","title":"How to Generate and Serve AsyncAPI Documentation","text":"

In this guide, let's explore how to generate and serve AsyncAPI documentation for our FastStream application.

","boost":10},{"location":"getting-started/asyncapi/export/#writing-the-faststream-application","title":"Writing the FastStream Application","text":"

Here's an example Python application using FastStream that consumes data from a topic, increments the value, and outputs the data to another topic. Save it in a file called basic.py.

basic.py
from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n\n\nclass DataBasic(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.publisher(\"output_data\")\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: DataBasic, logger: Logger) -> DataBasic:\n    logger.info(msg)\n    return DataBasic(data=msg.data + 1.0)\n
","boost":10},{"location":"getting-started/asyncapi/export/#generating-the-asyncapi-specification","title":"Generating the AsyncAPI Specification","text":"

Now that we have a FastStream application, we can proceed with generating the AsyncAPI specification using a CLI command.

faststream docs gen basic:app\n

The above command will generate the AsyncAPI specification and save it in a file called asyncapi.json.

If you prefer yaml instead of json, please run the following command to generate asyncapi.yaml.

faststream docs gen --yaml basic:app\n

Tip

To generate the documentation in yaml format, please install the necessary dependency to work with YAML file format at first.

pip install PyYAML\n
","boost":10},{"location":"getting-started/asyncapi/hosting/","title":"Serving the AsyncAPI Documentation","text":"

FastStream provides a command to serve the AsyncAPI documentation.

Note

This feature requires an Internet connection to obtain the AsyncAPI HTML via CDN.

faststream docs serve basic:app\n

In the above command, we are providing the path in the format of python_module:FastStream. Alternatively, you can also specify asyncapi.json or asyncapi.yaml to serve the AsyncAPI documentation.

JSONYAML
faststream docs serve asyncapi.json\n
faststream docs serve asyncapi.yaml\n

After running the command, it should serve the AsyncAPI documentation on port 8000 and display the following logs in the terminal.

And you should be able to see the following page in your browser:

ShortExpand

Tip

The command also offers options to serve the documentation on a different host and port.

","boost":10},{"location":"getting-started/asyncapi/hosting/#customizing-asyncapi-documentation","title":"Customizing AsyncAPI Documentation","text":"

FastStream also provides query parameters to show and hide specific sections of AsyncAPI documentation.

You can use the following parameters control the visibility of relevant sections:

  1. sidebar: Whether to include the sidebar. Default is true.
  2. info: Whether to include the info section. Default is true.
  3. servers: Whether to include the servers section. Default is true.
  4. operations: Whether to include the operations section. Default is true.
  5. messages: Whether to include the messages section. Default is true.
  6. schemas: Whether to include the schemas section. Default is true.
  7. errors: Whether to include the errors section. Default is true.
  8. expandMessageExamples: Whether to expand message examples. Default is true.

For example, to hide the entire Servers section of the documentation, simply add servers=false as a query parameter, i.e., http://localhost:8000?servers=false. The resulting page would look like the image below:

Please use the above-listed query parameters to show and hide sections of the AsyncAPI documentation.

","boost":10},{"location":"getting-started/cli/","title":"CLI","text":"

FastStream has its own built-in CLI tool for your maximum comfort as a developer.

Thanks to typer and watchfiles. Their work is the basis of this tool.

faststream --help\n
","boost":10},{"location":"getting-started/cli/#running-the-project","title":"Running the Project","text":"","boost":10},{"location":"getting-started/cli/#multiprocessing-scaling","title":"Multiprocessing Scaling","text":"

FastStream allows you to scale application right from the command line by running you application in the Process pool.

Just set the --worker option to scale your application:

faststream run serve:app --workers 2\n
","boost":10},{"location":"getting-started/cli/#hot-reload","title":"Hot Reload","text":"

Thanks to watchfiles, written in Rust, you can work with your project easily. Edit the code as much as you like - the new version has already been launched and is waiting for your requests!

faststream run serve:app --reload\n

Tip

Please, install watchfiles if you want to use --reload feature

pip install watchfiles\n

By default FastStream watches for .py file changes, but you can specify an extra file extensions to watch by (your config files as an example)

faststream run serve:app --reload  --reload-ext .yml --realod-ext .yaml\n
","boost":10},{"location":"getting-started/cli/#environment-management","title":"Environment Management","text":"

You can pass any custom flags and launch options to the FastStream CLI even without first registering them. Just use them when launching the application - and they will be right in your environment.

Use this option to select environment files, configure logging, or at your discretion.

For example, we will pass the .env file to the context of our application:

faststream run serve:app --env=.env.dev\n
KafkaRabbitMQNATSRedis
from faststream import FastStream, ContextRepo\nfrom faststream.kafka import KafkaBroker\nfrom pydantic_settings import BaseSettings\n\nbroker = KafkaBroker()\n\napp = FastStream(broker)\n\nclass Settings(BaseSettings):\n    host: str = \"localhost:9092\"\n\n@app.on_startup\nasync def setup(env: str, context: ContextRepo):\n    settings = Settings(_env_file=env)\n    await broker.connect(settings.host)\n    context.set_global(\"settings\", settings)\n
from faststream import FastStream, ContextRepo\nfrom faststream.rabbit import RabbitBroker\nfrom pydantic_settings import BaseSettings\n\nbroker = RabbitBroker()\n\napp = FastStream(broker)\n\nclass Settings(BaseSettings):\n    host: str = \"amqp://guest:guest@localhost:5672/\" \n\n@app.on_startup\nasync def setup(env: str, context: ContextRepo):\n    settings = Settings(_env_file=env)\n    await broker.connect(settings.host)\n    context.set_global(\"settings\", settings)\n
from faststream import FastStream, ContextRepo\nfrom faststream.nats import NatsBroker\nfrom pydantic_settings import BaseSettings\n\nbroker = NatsBroker()\n\napp = FastStream(broker)\n\nclass Settings(BaseSettings):\n    host: str = \"nats://localhost:4222\"\n\n@app.on_startup\nasync def setup(env: str, context: ContextRepo):\n    settings = Settings(_env_file=env)\n    await broker.connect(settings.host)\n    context.set_global(\"settings\", settings)\n
from faststream import FastStream, ContextRepo\nfrom faststream.redis import RedisBroker\nfrom pydantic_settings import BaseSettings\n\nbroker = RedisBroker()\n\napp = FastStream(broker)\n\nclass Settings(BaseSettings):\n    host: str = \"redis://localhost:6379\"\n\n@app.on_startup\nasync def setup(env: str, context: ContextRepo):\n    settings = Settings(_env_file=env)\n    await broker.connect(settings.host)\n    context.set_global(\"settings\", settings)\n

Note

Note that the env parameter was passed to the setup function directly from the command line

All passed values can be of type bool, str or list[str].

In this case, the flags will be interpreted as follows:

You can use them both individually and together in unlimited quantities.

","boost":10},{"location":"getting-started/cli/#asyncapi-schema","title":"AsyncAPI Schema","text":"

Also, the FastStream CLI allows you to work with the AsyncAPI schema in a simple way.

You are able to generate .json or .yaml files by your application code or host HTML representation directly:

faststream docs --help\n

To learn more about the commands above, please visit AsyncAPI export and AsyncAPI hosting.

","boost":10},{"location":"getting-started/config/","title":"Settings and Environment Variables","text":"

In many cases, your application may require external settings or configurations, such as a broker connection or database credentials.

To manage these settings effectively, it's common to provide them through environment variables that can be read by the application.

","boost":10},{"location":"getting-started/config/#pydantic-settings","title":"Pydantic Settings","text":"

Fortunately, Pydantic provides a useful utility for handling settings coming from environment variables with Pydantic: Settings management.

","boost":10},{"location":"getting-started/config/#install-pydantic-settings","title":"Install pydantic-settings","text":"

First, install the pydantic-settings package:

pip install pydantic-settings\n

Info

In Pydantic v1, this functionality was included with the main package. Now it is distributed as an independent package so that you can choose not to install it if you don't need that functionality.

","boost":10},{"location":"getting-started/config/#create-the-settings-object","title":"Create the Settings Object","text":"

Import BaseSettings from Pydantic and create a subclass, similar to what you would do with a Pydantic model.

Just like with Pydantic models, you declare class attributes with type annotations and can use all the same validation features and tools, including different data types and additional validations with Field().

Pydantic v2Pydantic v1 config.py
from pydantic_settings import BaseSettings\n\n\nclass Settings(BaseSettings):\n    url: str = \"\"\n    queue: str = \"test-queue\"\n\n\nsettings = Settings()\n

Info

In Pydantic v1 you would import BaseSettings directly from pydantic instead of from pydantic_settings.

config.py
from pydantic import BaseSettings\n\n\nclass Settings(BaseSettings):\n    url: str = \"\"\n    queue: str = \"test-queue\"\n\n\nsettings = Settings()\n

When you create an instance of that Settings class (in this case, in the settings object), Pydantic will read the environment variables in a case-insensitive way. For example, an upper-case variable APP_NAME will still be read for the attribute app_name.

It will also convert and validate the data, so when you use that settings object, you will have data of the type you declared (e.g. items_per_user will be an int).

","boost":10},{"location":"getting-started/config/#using-the-settings","title":"Using the settings","text":"

Now you can use the new settings object in your application:

serve.py
import os\n\nfrom pydantic_settings import BaseSettings\n\nfrom faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\n\nclass Settings(BaseSettings):\n    url: str\n    queue: str = \"test-queue\"\n\n\nsettings = Settings(_env_file=os.getenv(\"ENV\", \".env\"))\n\nbroker = RabbitBroker(settings.url)\napp = FastStream(broker)\n\n\n@broker.subscriber(settings.queue)\nasync def handler(msg):\n    ...\n
","boost":10},{"location":"getting-started/config/#running-the-application","title":"Running the Application","text":"

You can run the application while passing the configuration parameters as environment variables. For example, you could set an URL:

URL=\"amqp://guest:guest@localhost:5672\" faststream run serve:app\n

Tip

To set multiple environment variables for a single command, separate them with spaces and put them all before the command.

","boost":10},{"location":"getting-started/config/#reading-a-env-file","title":"Reading a .env File","text":"

If you have many settings that may change frequently, especially in different environments, it might be useful to store them in a file and then read them as if they were environment variables.

This practice is common enough that it has a name; these environment variables are typically placed in a file named .env, commonly referred to as a \"dotenv\" file.

Tip

In Unix-like systems like Linux and macOS, a file starting with a dot (.) is considered a hidden file.

But a dotenv file doesn't really have to have that exact filename.

Pydantic supports reading from these types of files using an external library. You can learn more at Pydantic Settings: Dotenv (.env) support.

Tip

To use this feature, you need to install the python-dotenv library.

","boost":10},{"location":"getting-started/config/#the-env-file","title":"The .env File","text":"

You can create a .env file with contents like this:

URL=\"amqp://guest:guest@localhost:5672\"\nQUEUE=\"test-queue\"\n
","boost":10},{"location":"getting-started/config/#reading-settings-from-env","title":"Reading Settings from .env","text":"

Then update your config.py as follows:

import os\n\nfrom pydantic_settings import BaseSettings\n\n\nclass Settings(BaseSettings):\n    url: str\n    queue: str = \"test-queue\"\n\n\nsettings = Settings(_env_file=os.getenv(\"ENV\", \".env\"))\n

This way, you can specify different .env files directly from your terminal, which can be extremely helpful for various testing and production scenarios.

Note

By default, Pydantic will attempt to find a .env file. If it's not present, Pydantic will use the default field values.

","boost":10},{"location":"getting-started/config/#choosing-the-env-file-at-startup","title":"Choosing the .env File at Startup","text":"

Now you can run the apllication with different .env files like so:

ENV=.local.env faststream run serve:app\n

Or, for a production environment:

ENV=.production.env faststream run serve:app\n

Or even for a test environment:

ENV=.test.env pytest\n
","boost":10},{"location":"getting-started/context/","title":"Application Context","text":"

FastStreams has its own Dependency Injection container - Context, used to store application runtime objects and variables.

With this container, you can access both application scope and message processing scope objects. This functionality is similar to Depends usage.

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message=Context(),  # get access to raw message\n):\n    ...\n
from faststream import Context, FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message=Context(),  # get access to raw message\n):\n    ...\n
from faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message=Context(),  # get access to raw message\n):\n    ...\n
from faststream import Context, FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message=Context(),  # get access to raw message\n):\n    ...\n

But, with the Annotated Python feature usage, it is much closer to @pytest.fixture.

KafkaRabbitMQNATSRedis
from typing import Annotated\n\nfrom faststream import Context, FastStream\nfrom faststream.kafka import KafkaBroker\nfrom faststream.kafka.message import KafkaMessage\n\nMessage = Annotated[KafkaMessage, Context()]\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message: Message,  # get access to raw message\n):\n    ...\n
from typing import Annotated\n\nfrom faststream import Context, FastStream\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.rabbit.message import RabbitMessage\n\nMessage = Annotated[RabbitMessage, Context()]\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message: Message,  # get access to raw message\n):\n    ...\n
from typing import Annotated\n\nfrom faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.message import NatsMessage\n\nMessage = Annotated[NatsMessage, Context()]\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message: Message,  # get access to raw message\n):\n    ...\n
from typing import Annotated\n\nfrom faststream import Context, FastStream\nfrom faststream.redis import RedisBroker\nfrom faststream.redis.message import RedisMessage\n\nMessage = Annotated[RedisMessage, Context()]\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message: Message,  # get access to raw message\n):\n    ...\n
","boost":10},{"location":"getting-started/context/#usages","title":"Usages","text":"

By default, the context is available in the same place as Depends:

Tip

Fields obtained from the Context are editable, so editing them in a function means editing them everywhere.

","boost":10},{"location":"getting-started/context/#compatibility-with-regular-functions","title":"Compatibility with Regular Functions","text":"

To use context in other functions, use the @apply_types decorator. In this case, the context of the called function will correspond to the context of the event handler from which it was called.

from faststream import Context, apply_types\n\n@broker.subscriber(\"test\")\nasync def handler(body):\n    nested_func(body)\n\n@apply_types\ndef nested_func(body, logger=Context()):\n    logger.info(body)\n

In the example above, we did not pass the logger function at calling it; it was placed from context.

","boost":10},{"location":"getting-started/context/custom/","title":"Context Fields Declaration","text":"

You can also store your own objects in the Context.

","boost":10},{"location":"getting-started/context/custom/#global","title":"Global","text":"

To declare an application-level context field, you need to call the context.set_global method with with a key to indicate where the object will be placed in the context.

KafkaRabbitMQNATSRedis
from faststream import FastStream, ContextRepo, Context\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n@app.on_startup\nasync def set_global(context: ContextRepo):\n    context.set_global(\"secret_str\", \"my-perfect-secret\")\n
from faststream import FastStream, ContextRepo, Context\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n@app.on_startup\nasync def set_global(context: ContextRepo):\n    context.set_global(\"secret_str\", \"my-perfect-secret\")\n
from faststream import FastStream, ContextRepo, Context\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n@app.on_startup\nasync def set_global(context: ContextRepo):\n    context.set_global(\"secret_str\", \"my-perfect-secret\")\n
from faststream import FastStream, ContextRepo, Context\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n@app.on_startup\nasync def set_global(context: ContextRepo):\n    context.set_global(\"secret_str\", \"my-perfect-secret\")\n

Afterward, you can access your secret field in the usual way:

KafkaRabbitMQNATSRedis
@broker.subscriber(\"test-topic\")\nasync def handle(\n    msg: str,\n    secret_str: str=Context(),\n):\n    assert secret_str == \"my-perfect-secret\"\n
@broker.subscriber(\"test-queue\")\nasync def handle(\n    msg: str,\n    secret_str: str=Context(),\n):\n    assert secret_str == \"my-perfect-secret\"\n
@broker.subscriber(\"test-subject\")\nasync def handle(\n    msg: str,\n    secret_str: str=Context(),\n):\n    assert secret_str == \"my-perfect-secret\"\n
@broker.subscriber(\"test-channel\")\nasync def handle(\n    msg: str,\n    secret_str: str=Context(),\n):\n    assert secret_str == \"my-perfect-secret\"\n

In this case, the field becomes a global context field: it does not depend on the current message handler (unlike message)

To remove a field from the context use the reset_global method:

context.reset_global(\"my_key\")\n
","boost":10},{"location":"getting-started/context/custom/#local","title":"Local","text":"

To set a local context (available only within the message processing scope), use the context manager scope

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream, apply_types\nfrom faststream.kafka import KafkaBroker\nfrom faststream.kafka.annotations import ContextRepo, KafkaMessage\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    msg: str,\n    message: KafkaMessage,\n    context: ContextRepo,\n):\n    with context.scope(\"correlation_id\", message.correlation_id):\n        call()\n\n\n@apply_types\ndef call(\n    message: KafkaMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n
from faststream import Context, FastStream, apply_types\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.rabbit.annotations import ContextRepo, RabbitMessage\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    msg: str,\n    message: RabbitMessage,\n    context: ContextRepo,\n):\n    with context.scope(\"correlation_id\", message.correlation_id):\n        call()\n\n\n@apply_types\ndef call(\n    message: RabbitMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n
from faststream import Context, FastStream, apply_types\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import ContextRepo, NatsMessage\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    msg: str,\n    message: NatsMessage,\n    context: ContextRepo,\n):\n    with context.scope(\"correlation_id\", message.correlation_id):\n        call()\n\n\n@apply_types\ndef call(\n    message: NatsMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n
from faststream import Context, FastStream, apply_types\nfrom faststream.redis import RedisBroker\nfrom faststream.redis.annotations import ContextRepo, RedisMessage\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    msg: str,\n    message: RedisMessage,\n    context: ContextRepo,\n):\n    with context.scope(\"correlation_id\", message.correlation_id):\n        call()\n\n\n@apply_types\ndef call(\n    message: RedisMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n

You can also set the context by yourself, and it will remain within the current call stack until you clear it.

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream, apply_types, context\nfrom faststream.kafka import KafkaBroker\nfrom faststream.kafka.annotations import KafkaMessage\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    msg: str,\n    message: KafkaMessage,\n):\n    tag = context.set_local(\"correlation_id\", message.correlation_id)\n    call(tag)\n\n\n@apply_types\ndef call(\n    tag,\n    message: KafkaMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n    context.reset_local(\"correlation_id\", tag)\n
from faststream import Context, FastStream, apply_types, context\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.rabbit.annotations import RabbitMessage\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    msg: str,\n    message: RabbitMessage,\n):\n    tag = context.set_local(\"correlation_id\", message.correlation_id)\n    call(tag)\n\n\n@apply_types\ndef call(\n    tag,\n    message: RabbitMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n    context.reset_local(\"correlation_id\", tag)\n
from faststream import Context, FastStream, apply_types, context\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import NatsMessage\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    msg: str,\n    message: NatsMessage,\n):\n    tag = context.set_local(\"correlation_id\", message.correlation_id)\n    call(tag)\n\n\n@apply_types\ndef call(\n    tag,\n    message: NatsMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n    context.reset_local(\"correlation_id\", tag)\n
from faststream import Context, FastStream, apply_types, context\nfrom faststream.redis import RedisBroker\nfrom faststream.redis.annotations import RedisMessage\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    msg: str,\n    message: RedisMessage,\n):\n    tag = context.set_local(\"correlation_id\", message.correlation_id)\n    call(tag)\n\n\n@apply_types\ndef call(\n    tag,\n    message: RedisMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n    context.reset_local(\"correlation_id\", tag)\n
","boost":10},{"location":"getting-started/context/existed/","title":"Existing Fields","text":"

Context already contains some global objects that you can always access:

At the same time, thanks to contextlib.ContextVar, message is local for you current consumer scope.

","boost":10},{"location":"getting-started/context/existed/#access-to-context-fields","title":"Access to Context Fields","text":"

By default, the context searches for an object based on the argument name.

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker_object = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"test-topic\")\nasync def handle(\n    msg: str,\n    logger=Context(),\n    message=Context(),\n    broker=Context(),\n    context=Context(),\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream import Context, FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker_object = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"test-queue\")\nasync def handle(\n    msg: str,\n    logger=Context(),\n    message=Context(),\n    broker=Context(),\n    context=Context(),\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\n\nbroker_object = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"test-subject\")\nasync def handle(\n    msg: str,\n    logger=Context(),\n    message=Context(),\n    broker=Context(),\n    context=Context(),\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream import Context, FastStream\nfrom faststream.redis import RedisBroker\n\nbroker_object = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"test-channel\")\nasync def handle(\n    msg: str,\n    logger=Context(),\n    message=Context(),\n    broker=Context(),\n    context=Context(),\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
","boost":10},{"location":"getting-started/context/existed/#annotated-aliases","title":"Annotated Aliases","text":"

Also, FastStream has already created Annotated aliases to provide you with comfortable access to existing objects. You can import them directly from faststream or your broker-specific modules:

from faststream import Logger, ContextRepo\n
KafkaRabbitMQNATSRedis
from faststream.kafka.annotations import (\n    Logger, ContextRepo, KafkaMessage,\n    KafkaBroker, KafkaProducer, NoCast,\n)\n

faststream.kafka.KafkaMessage is an alias to faststream.kafka.annotations.KafkaMessage

from faststream.kafka import KafkaMessage\n

To use them, simply import and use them as subscriber argument annotations.

from faststream import Context, FastStream\nfrom faststream.kafka import KafkaBroker\nfrom faststream.kafka.annotations import (\n    ContextRepo,\n    KafkaMessage,\n    Logger,\n    KafkaBroker as BrokerAnnotation,\n)\n\nbroker_object = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"response-topic\")\nasync def handle_response(\n    msg: str,\n    logger: Logger,\n    message: KafkaMessage,\n    context: ContextRepo,\n    broker: BrokerAnnotation,\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream.rabbit.annotations import (\n    Logger, ContextRepo, RabbitMessage,\n    RabbitBroker, RabbitProducer, NoCast,\n)\n

faststream.rabbit.RabbitMessage is an alias to faststream.rabbit.annotations.RabbitMessage

from faststream.rabbit import RabbitMessage\n

To use them, simply import and use them as subscriber argument annotations.

from faststream import Context, FastStream\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.rabbit.annotations import (\n    ContextRepo,\n    RabbitMessage,\n    Logger,\n    RabbitBroker as BrokerAnnotation,\n)\n\nbroker_object = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"response-queue\")\nasync def handle_response(\n    msg: str,\n    logger: Logger,\n    message: RabbitMessage,\n    context: ContextRepo,\n    broker: BrokerAnnotation,\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream.nats.annotations import (\n    Logger, ContextRepo, NatsMessage,\n    NatsBroker, NatsProducer, NatsJsProducer,\n    Client, JsClient, NoCast,\n)\n

faststream.nats.NatsMessage is an alias to faststream.nats.annotations.NatsMessage

from faststream.nats import NatsMessage\n

To use them, simply import and use them as subscriber argument annotations.

from faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import (\n    ContextRepo,\n    NatsMessage,\n    Logger,\n    NatsBroker as BrokerAnnotation,\n)\n\nbroker_object = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"response-subject\")\nasync def handle_response(\n    msg: str,\n    logger: Logger,\n    message: NatsMessage,\n    context: ContextRepo,\n    broker: BrokerAnnotation,\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream.redis.annotations import (\n    Logger, ContextRepo, RedisMessage,\n    RedisBroker, Redis, NoCast,\n)\n

faststream.redis.RedisMessage is an alias to faststream.redis.annotations.RedisMessage

from faststream.redis import RedisMessage\n

To use them, simply import and use them as subscriber argument annotations.

from faststream import Context, FastStream\nfrom faststream.redis import RedisBroker\nfrom faststream.redis.annotations import (\n    ContextRepo,\n    RedisMessage,\n    Logger,\n    RedisBroker as BrokerAnnotation,\n)\n\nbroker_object = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"response-channel\")\nasync def handle_response(\n    msg: str,\n    logger: Logger,\n    message: RedisMessage,\n    context: ContextRepo,\n    broker: BrokerAnnotation,\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
","boost":10},{"location":"getting-started/context/extra/","title":"Context Extra Options","text":"

Additionally, Context provides you with some extra capabilities for working with containing objects.

","boost":10},{"location":"getting-started/context/extra/#default-values","title":"Default Values","text":"

For instance, if you attempt to access a field that doesn't exist in the global context, you will receive a pydantic.ValidationError exception.

However, you can set default values if needed.

KafkaRabbitMQNATSRedis
@broker.subscriber(\"test-topic\")\nasync def handle(\n    not_existed: None = Context(\"not_existed\", default=None),\n):\n    assert not_existed is None\n
@broker.subscriber(\"test-queue\")\nasync def handle(\n    not_existed: None = Context(\"not_existed\", default=None),\n):\n    assert not_existed is None\n
@broker.subscriber(\"test-subject\")\nasync def handle(\n    not_existed: None = Context(\"not_existed\", default=None),\n):\n    assert not_existed is None\n
@broker.subscriber(\"test-channel\")\nasync def handle(\n    not_existed: None = Context(\"not_existed\", default=None),\n):\n    assert not_existed is None\n
","boost":10},{"location":"getting-started/context/extra/#cast-context-types","title":"Cast Context Types","text":"

By default, context fields are NOT CAST to the type specified in their annotation.

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream, context\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\ncontext.set_global(\"secret\", \"1\")\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    secret: int = Context(),\n):\n    assert secret == \"1\"\n
from faststream import Context, FastStream, context\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\ncontext.set_global(\"secret\", \"1\")\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    secret: int = Context(),\n):\n    assert secret == \"1\"\n
from faststream import Context, FastStream, context\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\ncontext.set_global(\"secret\", \"1\")\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    secret: int = Context(),\n):\n    assert secret == \"1\"\n
from faststream import Context, FastStream, context\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\ncontext.set_global(\"secret\", \"1\")\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    secret: int = Context(),\n):\n    assert secret == \"1\"\n

If you require this functionality, you can enable the appropriate flag.

KafkaRabbitMQNATSRedis
@broker.subscriber(\"test-topic2\")\nasync def handle_int(\n    secret: int = Context(cast=True),\n):\n    assert secret == 1\n
@broker.subscriber(\"test-queue2\")\nasync def handle_int(\n    secret: int = Context(cast=True),\n):\n    assert secret == 1\n
@broker.subscriber(\"test-subject2\")\nasync def handle_int(\n    secret: int = Context(cast=True),\n):\n    assert secret == 1\n
@broker.subscriber(\"test-channel2\")\nasync def handle_int(\n    secret: int = Context(cast=True),\n):\n    assert secret == 1\n
","boost":10},{"location":"getting-started/context/fields/","title":"Access by Name","text":"

Sometimes, you may need to use a different name for the argument (not the one under which it is stored in the context) or get access to specific parts of the object. To do this, simply specify the name of what you want to access, and the context will provide you with the object.

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream\nfrom faststream.kafka import KafkaBroker\nfrom faststream.kafka.message import KafkaMessage\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    msg: KafkaMessage = Context(\"message\"),\n    correlation_id: str = Context(\"message.correlation_id\"),\n    user_header: str = Context(\"message.headers.user\"),\n):\n    assert msg.correlation_id == correlation_id\n    assert msg.headers[\"user\"] == user_header\n

This way you can get access to context object by its name

msg: KafkaMessage = Context(\"message\"),\n
from faststream import Context, FastStream\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.rabbit.message import RabbitMessage\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    msg: RabbitMessage = Context(\"message\"),\n    correlation_id: str = Context(\"message.correlation_id\"),\n    user_header: str = Context(\"message.headers.user\"),\n):\n    assert msg.correlation_id == correlation_id\n    assert msg.headers[\"user\"] == user_header\n

This way you can get access to context object by its name

msg: RabbitMessage = Context(\"message\"),\n
from faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.message import NatsMessage\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    msg: NatsMessage = Context(\"message\"),\n    correlation_id: str = Context(\"message.correlation_id\"),\n    user_header: str = Context(\"message.headers.user\"),\n):\n    assert msg.correlation_id == correlation_id\n    assert msg.headers[\"user\"] == user_header\n

This way you can get access to context object by its name

msg: NatsMessage = Context(\"message\"),\n
from faststream import Context, FastStream\nfrom faststream.redis import RedisBroker\nfrom faststream.redis.message import RedisMessage\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    msg: RedisMessage = Context(\"message\"),\n    correlation_id: str = Context(\"message.correlation_id\"),\n    user_header: str = Context(\"message.headers.user\"),\n):\n    assert msg.correlation_id == correlation_id\n    assert msg.headers[\"user\"] == user_header\n

This way you can get access to context object by its name

msg: RedisMessage = Context(\"message\"),\n

This way you can get access to context object specific field

correlation_id: str = Context(\"message.correlation_id\"),\n

Or even to a dict key

user_header: str = Context(\"message.headers.user\"),\n
","boost":10},{"location":"getting-started/contributing/CONTRIBUTING/","title":"Development","text":"

After cloning the project, you'll need to set up the development environment. Here are the guidelines on how to do this.

","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#virtual-environment-with-venv","title":"Virtual Environment with venv","text":"

Create a virtual environment in a directory using Python's venv module:

python -m venv venv\n

That will create a ./venv/ directory with Python binaries, allowing you to install packages in an isolated environment.

","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#activate-the-environment","title":"Activate the Environment","text":"

Activate the new environment with:

source ./venv/bin/activate\n

Ensure you have the latest pip version in your virtual environment:

python -m pip install --upgrade pip\n
","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#installing-dependencies","title":"Installing Dependencies","text":"

After activating the virtual environment as described above, run:

pip install -e \".[dev]\"\n

This will install all the dependencies and your local FastStream in your virtual environment.

","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#using-your-local-faststream","title":"Using Your local FastStream","text":"

If you create a Python file that imports and uses FastStream, and run it with the Python from your local environment, it will use your local FastStream source code.

Whenever you update your local FastStream source code, it will automatically use the latest version when you run your Python file again. This is because it is installed with -e.

This way, you don't have to \"install\" your local version to be able to test every change.

To use your local FastStream CLI, type:

python -m faststream ...\n
","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#running-tests","title":"Running Tests","text":"","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#pytest","title":"Pytest","text":"

To run tests with your current FastStream application and Python environment, use:

pytest tests\n# or\n./scripts/test.sh\n# with coverage output\n./scripts/test-cov.sh\n

In your project, you'll find some pytest marks:

By default, running pytest will execute \"not slow\" tests.

To run all tests use:

pytest -m 'all'\n

If you don't have a local broker instance running, you can run tests without those dependencies:

pytest -m 'not rabbit and not kafka and not nats and not redis'\n

To run tests based on RabbitMQ, Kafka, or other dependencies, the following dependencies are needed to be started as docker containers:

version: \"3\"\nservices:\n  # nosemgrep: yaml.docker-compose.security.writable-filesystem-service.writable-filesystem-service\n  rabbitmq:\n    image: rabbitmq:alpine\n    ports:\n      - \"5672:5672\"\n    # https://semgrep.dev/r?q=yaml.docker-compose.security.no-new-privileges.no-new-privileges\n    security_opt:\n      - no-new-privileges:true\n  # nosemgrep: yaml.docker-compose.security.writable-filesystem-service.writable-filesystem-service\n  kafka:\n    image: bitnami/kafka:3.5.0\n    ports:\n      - \"9092:9092\"\n    environment:\n      KAFKA_ENABLE_KRAFT: \"true\"\n      KAFKA_CFG_NODE_ID: \"1\"\n      KAFKA_CFG_PROCESS_ROLES: \"broker,controller\"\n      KAFKA_CFG_CONTROLLER_LISTENER_NAMES: \"CONTROLLER\"\n      KAFKA_CFG_LISTENERS: \"PLAINTEXT://:9092,CONTROLLER://:9093\"\n      KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP: \"CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT\"\n      KAFKA_CFG_ADVERTISED_LISTENERS: \"PLAINTEXT://127.0.0.1:9092\"\n      KAFKA_BROKER_ID: \"1\"\n      KAFKA_CFG_CONTROLLER_QUORUM_VOTERS: \"1@kafka:9093\"\n      ALLOW_PLAINTEXT_LISTENER: \"true\"\n    # https://semgrep.dev/r?q=yaml.docker-compose.security.no-new-privileges.no-new-privileges\n    security_opt:\n      - no-new-privileges:true\n  # nosemgrep: yaml.docker-compose.security.writable-filesystem-service.writable-filesystem-service\n  nats:\n    image: nats\n    command: -js\n    ports:\n      - 4222:4222\n      - 8222:8222  # management\n    # https://semgrep.dev/r?q=yaml.docker-compose.security.no-new-privileges.no-new-privileges\n    security_opt:\n      - no-new-privileges:true\n  # nosemgrep: yaml.docker-compose.security.writable-filesystem-service.writable-filesystem-service\n  redis:\n    image: redis:alpine\n    ports:\n      - 6379:6379\n    # https://semgrep.dev/r?q=yaml.docker-compose.security.no-new-privileges.no-new-privileges\n    security_opt:\n      - no-new-privileges:true\n

You can start the dependencies easily using provided script by running:

./scripts/start_test_env.sh\n

Once you are done with development and running tests, you can stop the dependencies' docker containers by running:

./scripts/stop_test_env.sh\n
","boost":3},{"location":"getting-started/contributing/docs/","title":"Documentation","text":"","boost":3},{"location":"getting-started/contributing/docs/#how-to-help","title":"How to help","text":"

You will be of invaluable help if you contribute to the documentation.

Such a contribution can be:

You can report all this in discussions on GitHub, start issue, or write about it in our discord group.

Note

Special thanks to those who are ready to offer help with the case and help in developing documentation, as well as translating it into other languages.

","boost":3},{"location":"getting-started/contributing/docs/#how-to-get-started","title":"How to get started","text":"

To develop the documentation, you don't even need to install the entire FastStream project as a whole.

Enough:

  1. Clone the project repository
  2. Create a virtual environment
    python -m venv venv\n
  3. Activate it
    source venv/bin/activate\n
  4. Install documentation dependencies
    pip install \".[devdocs]\"\n
  5. Go to the docs/ directory
  6. Start the local documentation server
    mkdocs serve\n

Now all changes in the documentation files will be reflected on your local version of the site. After making all the changes, you can issue a PR with them - and we will gladly accept it!

","boost":3},{"location":"getting-started/dependencies/","title":"Dependencies","text":"

FastStream uses the secondary library FastDepends for dependency management. This dependency system is literally borrowed from FastAPI, so if you know how to work with that framework, you'll be comfortable with dependencies in FastStream.

You can visit the FastDepends documentation for more details, but the key points and additions are covered here.

","boost":10},{"location":"getting-started/dependencies/#type-casting","title":"Type Casting","text":"

The key function in the dependency management and type conversion system in FastStream is the decorator @apply_types (also known as @inject in FastDepends).

By default, it applies to all event handlers, unless you disabled the same option when creating the broker.

KafkaRabbitMQNATSRedis
from faststream.kafka import KafkaBroker\nbroker = KafkaBroker(..., apply_types=False)\n
from faststream.rabbit import RabbitBroker\nbroker = RabbitBroker(..., apply_types=False)\n
from faststream.nats import NatsBroker\nbroker = NatsBroker(..., apply_types=False)\n
from faststream.redis import RedisBroker\nbroker = RedisBroker(..., apply_types=False)\n

Warning

Setting the apply_types=False flag not only disables type casting but also Depends and Context. If you want to disable only type casting, use validate=False instead.

This flag can be useful if you are using FastStream within another framework and you need to use its native dependency system.

","boost":10},{"location":"getting-started/dependencies/#dependency-injection","title":"Dependency Injection","text":"

To implement dependencies in FastStream, a special class called Depends is used

KafkaRabbitMQNATSRedis
from faststream import FastStream, Depends\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\ndef simple_dependency():\n    return 1\n\n@broker.subscriber(\"test\")\nasync def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
from faststream import FastStream, Depends\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\ndef simple_dependency():\n    return 1\n\n@broker.subscriber(\"test\")\nasync def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
from faststream import FastStream, Depends\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\ndef simple_dependency():\n    return 1\n\n@broker.subscriber(\"test\")\nasync def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
from faststream import FastStream, Depends\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\ndef simple_dependency():\n    return 1\n\n@broker.subscriber(\"test\")\nasync def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n

The first step: You need to declare a dependency, which can be any Callable object.

Callable

A \"Callable\" is an object that can be \"called\". It can be a function, a class, or a class method.

In other words, if you can write code like my_object() - my_object is Callable

KafkaRabbitMQNATSRedis
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n

Second step: Declare which dependencies you need using Depends

KafkaRabbitMQNATSRedis
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n

The last step: Just use the result of executing your dependency!

It's easy, isn't it?

Auto @apply_types

In the code above, we didn't use this decorator for our dependencies. However, it still applies to all functions used as dependencies. Please keep this in your mind.

","boost":10},{"location":"getting-started/dependencies/#top-level-dependencies","title":"Top-level Dependencies","text":"

If you don't need a dependency result, you can use the following code:

@broker.subscriber(\"test\")\ndef method(_ = Depends(...)): ...\n

But, using a special subscriber parameter is much more suitable:

@broker.subscriber(\"test\", dependencies=[Depends(...)])\ndef method(): ...\n

You can also declare broker-level dependencies, which will be applied to all broker's handlers:

broker = RabbitBroker(dependencies=[Depends(...)])\n
","boost":10},{"location":"getting-started/dependencies/#nested-dependencies","title":"Nested Dependencies","text":"

Dependencies can also contain other dependencies. This works in a very predictable way: just declare Depends in the dependent function.

KafkaRabbitMQNATSRedis
from faststream import FastStream, Depends\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\ndef another_dependency():\n    return 1\n\ndef simple_dependency(b: int = Depends(another_dependency)): # (1)\n    return b * 2\n\n@broker.subscriber(\"test\")\nasync def handler(\n    body: dict,\n    a: int = Depends(another_dependency),\n    b: int = Depends(simple_dependency)):\n    assert (a + b) == 3\n
  1. A nested dependency is called here
from faststream import FastStream, Depends\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\ndef another_dependency():\n    return 1\n\ndef simple_dependency(b: int = Depends(another_dependency)): # (1)\n    return b * 2\n\n@broker.subscriber(\"test\")\nasync def handler(\n    body: dict,\n    a: int = Depends(another_dependency),\n    b: int = Depends(simple_dependency)):\n    assert (a + b) == 3\n
  1. A nested dependency is called here
from faststream import FastStream, Depends\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\ndef another_dependency():\n    return 1\n\ndef simple_dependency(b: int = Depends(another_dependency)): # (1)\n    return b * 2\n\n@broker.subscriber(\"test\")\nasync def handler(\n    body: dict,\n    a: int = Depends(another_dependency),\n    b: int = Depends(simple_dependency)):\n    assert (a + b) == 3\n
  1. A nested dependency is called here
from faststream import FastStream, Depends\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\ndef another_dependency():\n    return 1\n\ndef simple_dependency(b: int = Depends(another_dependency)): # (1)\n    return b * 2\n\n@broker.subscriber(\"test\")\nasync def handler(\n    body: dict,\n    a: int = Depends(another_dependency),\n    b: int = Depends(simple_dependency)):\n    assert (a + b) == 3\n
  1. A nested dependency is called here

Caching

In the example above, the another_dependency function will be called at ONCE! FastDepends caches all dependency execution results within ONE @apply_types call stack. This means that all nested dependencies will receive the cached result of dependency execution. But, between different calls of the main function, these results will be different.

To prevent this behavior, just use Depends(..., cache=False). In this case, the dependency will be used for each function in the call stack where it is used.

","boost":10},{"location":"getting-started/dependencies/#use-with-regular-functions","title":"Use with Regular Functions","text":"

You can use the decorator @apply_types not only with @broker.subscriber(...), but also with regular functions, both synchronous and asynchronous.

SyncAsync
from faststream import Depends, apply_types\n\ndef simple_dependency(a: int, b: int = 3):\n    return a + b\n\n@apply_types\ndef method(a: int, d: int = Depends(simple_dependency)):\n    return a + d\n\ndef test_sync_dependency():\n    assert method(\"1\") == 5\n
import asyncio\nimport pytest\nfrom faststream import Depends, apply_types\n\nasync def simple_dependency(a: int, b: int = 3):\n    return a + b\n\ndef another_dependency(a: int):\n    return a\n\n@apply_types\nasync def method(\n    a: int,\n    b: int = Depends(simple_dependency),\n    c: int = Depends(another_dependency),\n):\n    return a + b + c\n\n@pytest.mark.asyncio\nasync def test_async_dependency():\n    assert 6 == await method(\"1\")\n

Be careful

In asynchronous code, you can use both synchronous and asynchronous dependencies. But in synchronous code, only synchronous dependencies are available to you.

","boost":10},{"location":"getting-started/dependencies/#casting-dependency-types","title":"Casting Dependency Types","text":"

FastDepends, used by FastStream, also gives the type return. This means that the value returned by the dependency will be be cast to the type twice: as return for dependencies and as the input argument of the main function. This does not incur additional costs if these types have the same annotation. Just keep it in mind. Or not... Anyway, I've warned you.

from faststream import Depends, apply_types\n\ndef simple_dependency(a: int, b: int = 3) -> str:\n    return a + b  # 'return' is cast to `str` for the first time\n\n@apply_types\ndef method(a: int, d: int = Depends(simple_dependency)):\n    # 'd' is cast to `int` for the second time\n    return a + d\n\nassert method(\"1\") == 5\n

Also, the result of executing the dependency is cached. If you use this dependency in N functions, this cached result will be converted to type N times (at the input to the function being used).

To avoid problems with this, use mypy or just be careful with the annotation of types in your project.

","boost":10},{"location":"getting-started/dependencies/global/","title":"Global","text":""},{"location":"getting-started/dependencies/testing/","title":"Testing","text":"

https://lancetnik.github.io/FastDepends/tutorial/overrides/

"},{"location":"getting-started/integrations/django/","title":"Using FastStream with Django","text":"

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel. It\u2019s free and open source.

In this tutorial, let's see how to use the FastStream app alongside a Django app.

","boost":10},{"location":"getting-started/integrations/django/#asgi","title":"ASGI","text":"

ASGI protocol supports lifespan events, and Django can be served as an ASGI application. So, the best way to integrate FastStream with the Django is by using ASGI lifespan. You can write it by yourself (it is really easy) or use something like this, but the prefered way for us is using Starlette Router.

Starlette Router allows you to serve any ASGI application you want, and it also supports lifespans. So, you can use it in your project to serve your regular Django ASGI and start up your FastStream broker too. Additionally, Starlette has much better static files support, providing an extra zero-cost feature.

","boost":10},{"location":"getting-started/integrations/django/#default-django-application","title":"Default Django Application","text":"

Well, lets take a look at a default Django asgi.py

asgi.py
import os\n\nfrom django.core.asgi import get_asgi_application\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\")\n\napplication = get_asgi_application()\n

You can already serve it using any ASGI server

For example, using uvicorn:

uvicorn asgi:app --workers 4\n

Or you can use Gunicorn with uvicorn workers

gunicorn asgi:app --workers 4 --worker-class uvicorn.workers.UvicornWorker\n

Your Django views, models and other stuff has no any changes if you serving it through ASGI, so you need no worry about it.

","boost":10},{"location":"getting-started/integrations/django/#faststream-integration","title":"FastStream Integration","text":"","boost":10},{"location":"getting-started/integrations/django/#serving-django-via-starlette","title":"Serving Django via Starlette","text":"

Now, we need to modify our asgi.py to serve it using Starlette

asgi.py
# regular Djano stuff\nimport os\n\nfrom django.core.asgi import get_asgi_application\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\")\n\ndjango_asgi = get_asgi_application()\n\n# Starlette serving\nfrom starlette.applications import Starlette\nfrom starlette.routing import Mount\n\napp = Starlette(\n    routes=(\n        Mount(\"/\", django_asgi()),  # redirect all requests to Django\n    ),\n)\n
","boost":10},{"location":"getting-started/integrations/django/#serving-static-files-with-starlette","title":"Serving static files with Starlette","text":"

Also, Starlette has a better static files provider than original Django one, so we can reuse it too.

Just add this line to your settings.py

settings.py
STATIC_ROOT = \"static/\"\n

And collect all static files by default Django command

python manage.py collectstatic\n

It creates a static/ directory in the root of your project, so you can serve it using Starlette

asgi.py
# Code above omitted \ud83d\udc46\n\nfrom starlette.staticfiles import StaticFiles\n\napp = Starlette(\n    routes=(\n        # /static is your STATIC_URL setting\n        Mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\"),\n        Mount(\"/\", get_asgi_application()),  # regular Django ASGI\n    ),\n)\n
","boost":10},{"location":"getting-started/integrations/django/#faststream-lifespan","title":"FastStream lifespan","text":"

Finally, we can add our FastStream integration like a regular lifespan

asgi.py
# Code above omitted \ud83d\udc46\n\nfrom contextlib import asynccontextmanager\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker()\n\n@asynccontextmanager\nasync def broker_lifespan(app):\n    await broker.start()\n    try:\n        yield\n    finally:\n        await broker.close()\n\napp = Starlette(\n    ...,\n    lifespan=broker_lifespan,\n)\n

Note

The code imports KafkaBroker as our application is going to connect with Kafka. Depending on your requirements, import the necessary service's broker from the options provided by FastStream, such as RabbitBroker, NatsBroker or KafkaBroker.

Full Example asgi.py
import os\nfrom contextlib import asynccontextmanager\n\nfrom django.core.asgi import get_asgi_application\nfrom starlette.applications import Starlette\nfrom starlette.routing import Mount\nfrom starlette.staticfiles import StaticFiles\nfrom faststream.kafka import KafkaBroker\n\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\")\n\nbroker = KafkaBroker()\n\n@asynccontextmanager\nasync def broker_lifespan(app):\n    await broker.start()\n    try:\n        yield\n    finally:\n        await broker.close()\n\napp = Starlette(\n    routes=(\n        Mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\"),\n        Mount(\"/\", get_asgi_application()),\n    ),\n    lifespan=broker_lifespan,\n)\n

This way we can easely integrate our FastStream apllication with the Django!

","boost":10},{"location":"getting-started/integrations/fastapi/","title":"FastAPI Plugin","text":"","boost":10},{"location":"getting-started/integrations/fastapi/#handling-messages","title":"Handling messages","text":"

FastStream can be used as a part of FastAPI.

Just import a StreamRouter you need and declare the message handler in the same way as with a regular FastStream application.

Tip

When used in this way, FastStream does not use its own dependency system but integrates into FastAPI. That is, you can use Depends, BackgroundTasks and other original FastAPI features as if it were a regular HTTP endpoint, but you can't use faststream.Context and faststream.Depends.

Note that the code below uses fastapi.Depends, not faststream.Depends.

Also, instead original faststream.Context you should use faststream.[broker].fastapi.Context (the same with already created annotations)

KafkaRabbitMQNATSRedis
from fastapi import Depends, FastAPI\nfrom pydantic import BaseModel\n\nfrom faststream.kafka.fastapi import KafkaRouter, Logger\n\nrouter = KafkaRouter(\"localhost:9092\")\n\nclass Incoming(BaseModel):\n    m: dict\n\ndef call():\n    return True\n\n@router.subscriber(\"test\")\n@router.publisher(\"response\")\nasync def hello(m: Incoming, logger: Logger, d=Depends(call)):\n    logger.info(m)\n    return {\"response\": \"Hello, Kafka!\"}\n\n@router.get(\"/\")\nasync def hello_http():\n    return \"Hello, HTTP!\"\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom pydantic import BaseModel\n\nfrom faststream.rabbit.fastapi import RabbitRouter, Logger\n\nrouter = RabbitRouter(\"amqp://guest:guest@localhost:5672/\")\n\nclass Incoming(BaseModel):\n    m: dict\n\ndef call():\n    return True\n\n@router.subscriber(\"test\")\n@router.publisher(\"response\")\nasync def hello(m: Incoming, logger: Logger, d=Depends(call)):\n    logger.info(m)\n    return {\"response\": \"Hello, Rabbit!\"}\n\n@router.get(\"/\")\nasync def hello_http():\n    return \"Hello, HTTP!\"\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom pydantic import BaseModel\n\nfrom faststream.nats.fastapi import NatsRouter, Logger\n\nrouter = NatsRouter(\"nats://localhost:4222\")\n\nclass Incoming(BaseModel):\n    m: dict\n\ndef call():\n    return True\n\n@router.subscriber(\"test\")\n@router.publisher(\"response\")\nasync def hello(m: Incoming, logger: Logger, d=Depends(call)):\n    logger.info(m)\n    return {\"response\": \"Hello, NATS!\"}\n\n@router.get(\"/\")\nasync def hello_http():\n    return \"Hello, HTTP!\"\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom pydantic import BaseModel\n\nfrom faststream.redis.fastapi import RedisRouter, Logger\n\nrouter = RedisRouter(\"redis://localhost:6379\")\n\nclass Incoming(BaseModel):\n    m: dict\n\ndef call():\n    return True\n\n@router.subscriber(\"test\")\n@router.publisher(\"response\")\nasync def hello(m: Incoming, logger: Logger, d=Depends(call)):\n    logger.info(m)\n    return {\"response\": \"Hello, Redis!\"}\n\n@router.get(\"/\")\nasync def hello_http():\n    return \"Hello, HTTP!\"\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n

When processing a message from a broker, the entire message body is placed simultaneously in both the body and path request parameters. You can access them in any way convenient for you. The message header is placed in headers.

Also, this router can be fully used as an HttpRouter (of which it is the inheritor). So, you can use it to declare any get, post, put and other HTTP methods. For example, this is done at line 20.

Warning

If your ASGI server does not support installing state inside lifespan, you can disable this behavior as follows:

router = StreamRouter(..., setup_state=False)\n

However, after that, you will not be able to access the broker from your application's state (but it is still available as the router.broker).

","boost":10},{"location":"getting-started/integrations/fastapi/#accessing-the-broker-object","title":"Accessing the Broker Object","text":"

Inside each router, there is a broker. You can easily access it if you need to send a message to MQ:

KafkaRabbitMQNATSRedis
from fastapi import FastAPI\n\nfrom faststream.kafka.fastapi import KafkaRouter\n\nrouter = KafkaRouter(\"localhost:9092\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\n@router.get(\"/\")\nasync def hello_http():\n    await router.broker.publish(\"Hello, Kafka!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.rabbit.fastapi import RabbitRouter\n\nrouter = RabbitRouter(\"amqp://guest:guest@localhost:5672/\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\n@router.get(\"/\")\nasync def hello_http():\n    await router.broker.publish(\"Hello, Rabbit!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.nats.fastapi import NatsRouter\n\nrouter = NatsRouter(\"nats://localhost:4222\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\n@router.get(\"/\")\nasync def hello_http():\n    await router.broker.publish(\"Hello, NATS!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.redis.fastapi import RedisRouter\n\nrouter = RedisRouter(\"redis://localhost:6379\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\n@router.get(\"/\")\nasync def hello_http():\n    await router.broker.publish(\"Hello, Redis!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n

Also, you can use the following Depends to access the broker if you want to use it at different parts of your program:

KafkaRabbitMQNATSRedis
from fastapi import Depends, FastAPI\nfrom typing_extensions import Annotated\n\nfrom faststream.kafka import KafkaBroker, fastapi\n\nrouter = fastapi.KafkaRouter(\"localhost:9092\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\ndef broker():\n    return router.broker\n\n\n@router.get(\"/\")\nasync def hello_http(broker: Annotated[KafkaBroker, Depends(broker)]):\n    await broker.publish(\"Hello, Kafka!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom typing_extensions import Annotated\n\nfrom faststream.rabbit import RabbitBroker, fastapi\n\nrouter = fastapi.RabbitRouter(\"amqp://guest:guest@localhost:5672/\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\ndef broker():\n    return router.broker\n\n\n@router.get(\"/\")\nasync def hello_http(broker: Annotated[RabbitBroker, Depends(broker)]):\n    await broker.publish(\"Hello, Rabbit!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom typing_extensions import Annotated\n\nfrom faststream.nats import NatsBroker, fastapi\n\nrouter = fastapi.NatsRouter(\"nats://localhost:4222\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\ndef broker():\n    return router.broker\n\n\n@router.get(\"/\")\nasync def hello_http(broker: Annotated[NatsBroker, Depends(broker)]):\n    await broker.publish(\"Hello, NATS!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom typing_extensions import Annotated\n\nfrom faststream.redis import RedisBroker, fastapi\n\nrouter = fastapi.RedisRouter(\"redis://localhost:6379\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\ndef broker():\n    return router.broker\n\n\n@router.get(\"/\")\nasync def hello_http(broker: Annotated[RedisBroker, Depends(broker)]):\n    await broker.publish(\"Hello, Redis!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n

Or you can access the broker from a FastAPI application state (if you don't disable it with setup_state=False):

from fastapi import Request\n\n@app.get(\"/\")\ndef main(request: Request):\n    broker = request.state.broker\n
","boost":10},{"location":"getting-started/integrations/fastapi/#after_startup","title":"@after_startup","text":"

The FastStream application has the @after_startup hook, which allows you to perform operations with your message broker after the connection is established. This can be extremely convenient for managing your brokers' objects and/or sending messages. This hook is also available for your FastAPI StreamRouter

KafkaRabbitMQNATSRedis
from fastapi import FastAPI\n\nfrom faststream.kafka.fastapi import KafkaRouter\n\nrouter = KafkaRouter(\"localhost:9092\")\n\n\n@router.subscriber(\"test\")\nasync def hello(msg: str):\n    return {\"response\": \"Hello, Kafka!\"}\n\n\n@router.after_startup\nasync def test(app: FastAPI):\n    await router.broker.publish(\"Hello!\", \"test\")\n\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.rabbit.fastapi import RabbitRouter\n\nrouter = RabbitRouter(\"amqp://guest:guest@localhost:5672/\")\n\n\n@router.subscriber(\"test\")\nasync def hello(msg: str):\n    return {\"response\": \"Hello, Rabbit!\"}\n\n\n@router.after_startup\nasync def test(app: FastAPI):\n    await router.broker.publish(\"Hello!\", \"test\")\n\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.nats.fastapi import NatsRouter\n\nrouter = NatsRouter(\"nats://localhost:4222\")\n\n\n@router.subscriber(\"test\")\nasync def hello(msg: str):\n    return {\"response\": \"Hello, NATS!\"}\n\n\n@router.after_startup\nasync def test(app: FastAPI):\n    await router.broker.publish(\"Hello!\", \"test\")\n\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.redis.fastapi import RedisRouter\n\nrouter = RedisRouter(\"redis://localhost:6379\")\n\n\n@router.subscriber(\"test\")\nasync def hello(msg: str):\n    return {\"response\": \"Hello, Redis!\"}\n\n\n@router.after_startup\nasync def test(app: FastAPI):\n    await router.broker.publish(\"Hello!\", \"test\")\n\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
","boost":10},{"location":"getting-started/integrations/fastapi/#documentation","title":"Documentation","text":"

When using FastStream as a router for FastAPI, the framework automatically registers endpoints for hosting AsyncAPI documentation into your application with the following default values:

KafkaRabbitMQNATSRedis
from faststream.kafka.fastapi import KafkaRouter\n\nrouter = KafkaRouter(\n    ...,\n    schema_url=\"/asyncapi\",\n    include_in_schema=True,\n)\n
from faststream.rabbit.fastapi import RabbitRouter\n\nrouter = RabbitRouter(\n    ...,\n    schema_url=\"/asyncapi\",\n    include_in_schema=True,\n)\n
from faststream.nats.fastapi import NatsRouter\n\nrouter = NatsRouter(\n    ...,\n    schema_url=\"/asyncapi\",\n    include_in_schema=True,\n)\n
from faststream.redis.fastapi import RedisRouter\n\nrouter = RedisRouter(\n    ...,\n    schema_url=\"/asyncapi\",\n    include_in_schema=True,\n)\n

This way, you will have three routes to interact with your application's AsyncAPI schema:

","boost":10},{"location":"getting-started/integrations/fastapi/#testing","title":"Testing","text":"

To test your FastAPI StreamRouter, you can still use it with the TestClient:

KafkaRabbitMQNATSRedis
import pytest\n\nfrom faststream.kafka import TestKafkaBroker, fastapi\n\nrouter = fastapi.KafkaRouter()\n\n\n@router.subscriber(\"test\")\nasync def handler(msg: str):\n    ...\n\n\n@pytest.mark.asyncio\nasync def test_router():\n    async with TestKafkaBroker(router.broker) as br:\n        await br.publish(\"Hi!\", \"test\")\n\n        handler.mock.assert_called_once_with(\"Hi!\")\n
import pytest\n\nfrom faststream.rabbit import TestRabbitBroker, fastapi\n\nrouter = fastapi.RabbitRouter()\n\n\n@router.subscriber(\"test\")\nasync def handler(msg: str):\n    ...\n\n\n@pytest.mark.asyncio\nasync def test_router():\n    async with TestRabbitBroker(router.broker) as br:\n        await br.publish(\"Hi!\", \"test\")\n\n        handler.mock.assert_called_once_with(\"Hi!\")\n
import pytest\n\nfrom faststream.nats import TestNatsBroker, fastapi\n\nrouter = fastapi.NatsRouter()\n\n\n@router.subscriber(\"test\")\nasync def handler(msg: str):\n    ...\n\n\n@pytest.mark.asyncio\nasync def test_router():\n    async with TestNatsBroker(router.broker) as br:\n        await br.publish(\"Hi!\", \"test\")\n\n        handler.mock.assert_called_once_with(\"Hi!\")\n
import pytest\n\nfrom faststream.redis import TestRedisBroker, fastapi\n\nrouter = fastapi.RedisRouter()\n\n\n@router.subscriber(\"test\")\nasync def handler(msg: str):\n    ...\n\n\n@pytest.mark.asyncio\nasync def test_router():\n    async with TestRedisBroker(router.broker) as br:\n        await br.publish(\"Hi!\", \"test\")\n\n        handler.mock.assert_called_once_with(\"Hi!\")\n
","boost":10},{"location":"getting-started/integrations/fastapi/#miltiple-routers","title":"Miltiple Routers","text":"

Using FastStream as a FastAPI plugin you are still able to separate messages processing logic between different routers (like with a regular HTTPRouter). But it can be confusing - how you should include multiple routers, if we have to setup router.lifespan_context as a FastAPI object lifespan.

You can make it in a two ways, depends on you reminds.

","boost":10},{"location":"getting-started/integrations/fastapi/#routers-nesting","title":"Routers nesting","text":"

If you want to use the SAME CONNECTION for all of you routers you should nest them each other and finally use only the core router to include it into FastAPI object.

KafkaRabbitMQNATSRedis
from fastapi import FastAPI\nfrom faststream.kafka.fastapi import KafkaRouter\n\ncore_router = KafkaRouter()\nnested_router = KafkaRouter()\n\n@core_router.subscriber(\"core-topic\")\nasync def handler():\n    ...\n\n@nested_router.subscriber(\"nested-topic\")\nasync def nested_handler():\n    ...\n\ncore_router.include_router(nested_router)\n\napp = FastAPI(lifespan=core_router.lifespan_context)\napp.include_router(core_router)\n
from fastapi import FastAPI\nfrom faststream.rabbit.fastapi import RabbitRouter\n\ncore_router = RabbitRouter()\nnested_router = RabbitRouter()\n\n@core_router.subscriber(\"core-queue\")\nasync def handler():\n    ...\n\n@nested_router.subscriber(\"nested-queue\")\nasync def nested_handler():\n    ...\n\ncore_router.include_router(nested_router)\n\napp = FastAPI(lifespan=core_router.lifespan_context)\napp.include_router(core_router)\n
from fastapi import FastAPI\nfrom faststream.nats.fastapi import NatsRouter\n\ncore_router = NatsRouter()\nnested_router = NatsRouter()\n\n@core_router.subscriber(\"core-subject\")\nasync def handler():\n    ...\n\n@nested_router.subscriber(\"nested-subject\")\nasync def nested_handler():\n    ...\n\ncore_router.include_router(nested_router)\n\napp = FastAPI(lifespan=core_router.lifespan_context)\napp.include_router(core_router)\n
from fastapi import FastAPI\nfrom faststream.redis.fastapi import RedisRouter\n\ncore_router = RedisRouter()\nnested_router = RedisRouter()\n\n@core_router.subscriber(\"core-channel\")\nasync def handler():\n    ...\n\n@nested_router.subscriber(\"nested-channel\")\nasync def nested_handler():\n    ...\n\ncore_router.include_router(nested_router)\n\napp = FastAPI(lifespan=core_router.lifespan_context)\napp.include_router(core_router)\n

This way the core router collects all nested routers publishers and subscribers and stores it like its own.

","boost":10},{"location":"getting-started/integrations/fastapi/#custom-lifespan","title":"Custom lifespan","text":"

Overwise, if you want to has multiple connections to different broker instances, you should start routers independently in your custom lifespan

KafkaRabbitMQNATSRedis
from contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom faststream.kafka.fastapi import KafkaRouter\n\ncore_router = KafkaRouter()\nnested_router = KafkaRouter()\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    async with (\n        core_router.lifespan_context(app),\n        nested_router.lifespan_context(app),\n    ):\n        yield\n\napp = FastAPI(lifespan=lifespan)\napp.include_router(core_router)\napp.include_router(nested_router)\n
from contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom faststream.rabbit.fastapi import RabbitRouter\n\ncore_router = RabbitRouter()\nnested_router = RabbitRouter()\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    async with (\n        core_router.lifespan_context(app),\n        nested_router.lifespan_context(app),\n    ):\n        yield\n\napp = FastAPI(lifespan=lifespan)\napp.include_router(core_router)\napp.include_router(nested_router)\n
from contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom faststream.nats.fastapi import NatsRouter\n\ncore_router = NatsRouter()\nnested_router = NatsRouter()\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    async with (\n        core_router.lifespan_context(app),\n        nested_router.lifespan_context(app),\n    ):\n        yield\n\napp = FastAPI(lifespan=lifespan)\napp.include_router(core_router)\napp.include_router(nested_router)\n
from contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom faststream.redis.fastapi import RedisRouter\n\ncore_router = RedisRouter()\nnested_router = RedisRouter()\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    async with (\n        core_router.lifespan_context(app),\n        nested_router.lifespan_context(app),\n    ):\n        yield\n\napp = FastAPI(lifespan=lifespan)\napp.include_router(core_router)\napp.include_router(nested_router)\n

Warning

This way you lose AsyncAPI schema, but we are working on it.

","boost":10},{"location":"getting-started/integrations/frameworks/","title":"INTEGRATIONS","text":"

FastStream brokers are very easy to integrate with any of your applications: it is enough to initialize the broker at startup and close it correctly at the end of your application.

Most HTTP frameworks have built-in lifecycle hooks for this.

FastAPILitestarAiohttpBlacksheepFalconQuartSanic

Tip

If you want to use FastStream in conjunction with FastAPI, perhaps you should use a special plugin

from contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    await broker.start()\n    yield\n    await broker.close()\n\napp = FastAPI(lifespan=lifespan)\n\n@app.get(\"/\")\ndef read_root():\n    return {\"Hello\": \"World\"}\n
from litestar import Litestar, get\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\n\n@broker.subscriber(\"queue\")\nasync def handle(msg):\n    print(msg)\n\n@get(\"/\")\nasync def index() -> str:\n    return \"Hello, world!\"\n\napp = Litestar(\n    [index],\n    on_startup=(broker.start,),\n    on_shutdown=(broker.close,),\n)\n
from aiohttp import web\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\nasync def start_broker(app):\n    await broker.start()\n\n\nasync def stop_broker(app):\n    await broker.close()\n\n\nasync def hello(request):\n    return web.Response(text=\"Hello, world\")\n\n\napp = web.Application()\napp.add_routes([web.get(\"/\", hello)])\napp.on_startup.append(start_broker)\napp.on_cleanup.append(stop_broker)\n\n\nif __name__ == \"__main__\":\n    web.run_app(app)\n
from blacksheep import Application\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\napp = Application()\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\n@app.on_start\nasync def start_broker(application: Application) -> None:\n    await broker.start()\n\n\n@app.on_stop\nasync def stop_broker(application: Application) -> None:\n    await broker.close()\n\n\n@app.route(\"/\")\nasync def home():\n    return \"Hello, World!\"\n
import falcon\nimport falcon.asgi\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\nclass ThingsResource:\n    async def on_get(self, req, resp):\n        resp.status = falcon.HTTP_200\n        resp.content_type = falcon.MEDIA_TEXT\n        resp.text = (\n            \"\\nTwo things awe me most, the starry sky \"\n            \"above me and the moral law within me.\\n\"\n            \"\\n\"\n            \"    ~ Immanuel Kant\\n\\n\"\n        )\n\n\nclass StreamMiddleware:\n    async def process_startup(self, scope, event):\n        await broker.start()\n\n    async def process_shutdown(self, scope, event):\n        await broker.close()\n\n\napp = falcon.asgi.App()\napp.add_middleware(StreamMiddleware())\napp.add_route(\"/things\", ThingsResource())\n
from quart import Quart\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\napp = Quart(__name__)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\n@app.before_serving\nasync def start_broker():\n    await broker.start()\n\n\n@app.after_serving\nasync def stop_broker():\n    await broker.close()\n\n\n@app.route(\"/\")\nasync def json():\n    return {\"hello\": \"world\"}\n
from sanic import Sanic\nfrom sanic.response import text\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\napp = Sanic(\"MyHelloWorldApp\")\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\n@app.after_server_start\nasync def start_broker(app, loop):\n    await broker.start()\n\n\n@app.after_server_stop\nasync def stop_broker(app, loop):\n    await broker.close()\n\n\n@app.get(\"/\")\nasync def hello_world(request):\n    return text(\"Hello, world.\")\n

However, even if such a hook is not provided, you can do it yourself.

Tornado
import asyncio\n\nimport tornado.web\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\nclass MainHandler(tornado.web.RequestHandler):\n    def get(self):\n        self.write(\"Hello, world\")\n\n\ndef make_app():\n    return tornado.web.Application(\n        [\n            (r\"/\", MainHandler),\n        ]\n    )\n\n\nasync def main():\n    app = make_app()\n    app.listen(8888)\n\n    await broker.start()\n    try:\n        await asyncio.Event().wait()\n    finally:\n        await broker.close()\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n
","boost":10},{"location":"getting-started/lifespan/","title":"Lifespan Events","text":"

Sometimes you need to define the logic that should be executed before launching the application. This means that the code will be executed once - even before your application starts receiving messages.

Also, you may need to terminate some processes after stopping the application. In this case, your code will also be executed exactly once: but after the completion of the main application.

Since this code is executed before the application starts and after it stops, it covers the entire lifecycle (lifespan) of the application.

This can be very useful for initializing your application settings at startup, raising a pool of connections to a database, or running machine learning models.

","boost":10},{"location":"getting-started/lifespan/context/","title":"Lifespan Context Manager","text":"

Also, you can define startup and shutdown logic using the lifespan parameter of the FastSTream app, and a \"context manager\" (I'll show you what that is in a second).

Let's start with an example from hooks page and refactor it using \"context manager\".

We create an async function lifespan() with yield like this:

KafkaRabbitMQNATSRedis
from contextlib import asynccontextmanager\n\nfrom faststream import Context, ContextRepo, FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n\ndef fake_ml_model_answer(x: float):\n    return x * 42\n\n\n@asynccontextmanager\nasync def lifespan(context: ContextRepo):\n    # load fake ML model\n    ml_models = { \"answer_to_everything\": fake_ml_model_answer }\n    context.set_global(\"model\", ml_models)\n\n    yield\n\n    # Clean up the ML models and release the resources\n    ml_models.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n\n\napp = FastStream(broker, lifespan=lifespan)\n
from contextlib import asynccontextmanager\n\nfrom faststream import Context, ContextRepo, FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\n\n\ndef fake_ml_model_answer(x: float):\n    return x * 42\n\n\n@asynccontextmanager\nasync def lifespan(context: ContextRepo):\n    # load fake ML model\n    ml_models = { \"answer_to_everything\": fake_ml_model_answer }\n    context.set_global(\"model\", ml_models)\n\n    yield\n\n    # Clean up the ML models and release the resources\n    ml_models.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n\n\napp = FastStream(broker, lifespan=lifespan)\n
from contextlib import asynccontextmanager\n\nfrom faststream import Context, ContextRepo, FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\n\n\ndef fake_ml_model_answer(x: float):\n    return x * 42\n\n\n@asynccontextmanager\nasync def lifespan(context: ContextRepo):\n    # load fake ML model\n    ml_models = { \"answer_to_everything\": fake_ml_model_answer }\n    context.set_global(\"model\", ml_models)\n\n    yield\n\n    # Clean up the ML models and release the resources\n    ml_models.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n\n\napp = FastStream(broker, lifespan=lifespan)\n
from contextlib import asynccontextmanager\n\nfrom faststream import Context, ContextRepo, FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\n\n\ndef fake_ml_model_answer(x: float):\n    return x * 42\n\n\n@asynccontextmanager\nasync def lifespan(context: ContextRepo):\n    # load fake ML model\n    ml_models = { \"answer_to_everything\": fake_ml_model_answer }\n    context.set_global(\"model\", ml_models)\n\n    yield\n\n    # Clean up the ML models and release the resources\n    ml_models.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n\n\napp = FastStream(broker, lifespan=lifespan)\n

As you can see, lifespan parameter is much suitable for case (than @app.on_startup and @app.after_shutdown separated calls) if you have object needs to process at application startup and shutdown both.

Tip

lifespan starts BEFORE your broken started (@app.on_startup hook) and AFTER broker was shutdown (@app.after_shutdown), so you can't publish any messages here.

If you want to make some actions will already/still running broker, please use @app.after_startup and @app.on_shutdown hooks.

Also, lifespan supports all FastStream hooks features:

","boost":10},{"location":"getting-started/lifespan/hooks/","title":"Lifespan Hooks","text":"","boost":10},{"location":"getting-started/lifespan/hooks/#usage-example","title":"Usage example","text":"

Let's imagine that your application uses pydantic as your settings manager.

I highly recommend using pydantic for these purposes, because this dependency is already used at FastStream and you don't have to install an additional package

Also, let's imagine that you have several .env, .env.development, .env.test, .env.production files with your application settings, and you want to switch them at startup without any code changes.

By passing optional arguments with the command line to your code FastStream allows you to do this easily.

","boost":10},{"location":"getting-started/lifespan/hooks/#lifespan","title":"Lifespan","text":"

Let's write some code for our example

KafkaRabbitMQNATSRedis
from pydantic_settings import BaseSettings\n\nfrom faststream import ContextRepo, FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker()\napp = FastStream(broker)\n\n\nclass Settings(BaseSettings):\n    host: str = \"localhost:9092\"\n\n\n@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
from pydantic_settings import BaseSettings\n\nfrom faststream import ContextRepo, FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\n\nclass Settings(BaseSettings):\n    host: str = \"amqp://guest:guest@localhost:5672/\" \n\n\n@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
from pydantic_settings import BaseSettings\n\nfrom faststream import ContextRepo, FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n\nclass Settings(BaseSettings):\n    host: str = \"nats://localhost:4222\"\n\n\n@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
from pydantic_settings import BaseSettings\n\nfrom faststream import ContextRepo, FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\nclass Settings(BaseSettings):\n    host: str = \"redis://localhost:6379\"\n\n\n@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n

Now this application can be run using the following command to manage the environment:

faststream run serve:app --env .env.test\n
","boost":10},{"location":"getting-started/lifespan/hooks/#details","title":"Details","text":"

Now let's look into a little more detail

To begin with, we used a decorator

@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n

to declare a function that should run when our application starts

The next step is to declare the arguments that our function will receive

@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n

In this case, the env field will be passed to the setup function from the arguments with the command line

Tip

The default lifecycle functions are used with the decorator @apply_types, therefore, all context fields and dependencies are available in them

Then, we initialized the settings of our application using the file passed to us from the command line

@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n

And put these settings in a global context

KafkaRabbitMQNATSRedis
@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
Note

Now we can access our settings anywhere in the application right from the context

from faststream import Context, apply_types\n@apply_types\nasync def func(settings = Context()): ...\n

The last step we initialized our broker: now, when the application starts, it will be ready to receive messages

@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
","boost":10},{"location":"getting-started/lifespan/hooks/#another-example","title":"Another example","text":"

Now let's imagine that we have a machine learning model that needs to process messages from some broker.

Initialization of such models usually takes a long time. It would be wise to do this at the start of the application, and not when processing each message.

You can initialize your model somewhere at the top of your module/file. However, in this case, this code will be run even just in case of importing this module, for example, during testing. It is unlikely that you want to run your model on every test run...

Therefore, it is worth initializing the model in the @app.on_startup hook.

Also, we don't want the model to finish its work incorrectly when the application is stopped. To avoid this, we need the hook @app.on_shutdown

KafkaRabbitMQNATSRedis
from faststream import Context, ContextRepo, FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\nml_models = {}  # fake ML model\n\n\ndef fake_answer_to_everything_ml_model(x: float):\n    return x * 42\n\n\n@app.on_startup\nasync def setup_model(context: ContextRepo):\n    # Load the ML model\n    ml_models[\"answer_to_everything\"] = fake_answer_to_everything_ml_model\n    context.set_global(\"model\", ml_models)\n\n\n@app.on_shutdown\nasync def shutdown_model(model: dict = Context()):\n    # Clean up the ML models and release the resources\n    model.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n
from faststream import Context, ContextRepo, FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\nml_models = {}  # fake ML model\n\n\ndef fake_answer_to_everything_ml_model(x: float):\n    return x * 42\n\n\n@app.on_startup\nasync def setup_model(context: ContextRepo):\n    # Load the ML model\n    ml_models[\"answer_to_everything\"] = fake_answer_to_everything_ml_model\n    context.set_global(\"model\", ml_models)\n\n\n@app.on_shutdown\nasync def shutdown_model(model: dict = Context()):\n    # Clean up the ML models and release the resources\n    model.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n
from faststream import Context, ContextRepo, FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\nml_models = {}  # fake ML model\n\n\ndef fake_answer_to_everything_ml_model(x: float):\n    return x * 42\n\n\n@app.on_startup\nasync def setup_model(context: ContextRepo):\n    # Load the ML model\n    ml_models[\"answer_to_everything\"] = fake_answer_to_everything_ml_model\n    context.set_global(\"model\", ml_models)\n\n\n@app.on_shutdown\nasync def shutdown_model(model: dict = Context()):\n    # Clean up the ML models and release the resources\n    model.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n
from faststream import Context, ContextRepo, FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\nml_models = {}  # fake ML model\n\n\ndef fake_answer_to_everything_ml_model(x: float):\n    return x * 42\n\n\n@app.on_startup\nasync def setup_model(context: ContextRepo):\n    # Load the ML model\n    ml_models[\"answer_to_everything\"] = fake_answer_to_everything_ml_model\n    context.set_global(\"model\", ml_models)\n\n\n@app.on_shutdown\nasync def shutdown_model(model: dict = Context()):\n    # Clean up the ML models and release the resources\n    model.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n
","boost":10},{"location":"getting-started/lifespan/hooks/#multiple-hooks","title":"Multiple hooks","text":"

If you want to declare multiple lifecycle hooks, they will be used in the order they are registered:

from faststream import Context, ContextRepo, FastStream\n\napp = FastStream()\n\n\n@app.on_startup\nasync def setup(context: ContextRepo):\n    context.set_global(\"field\", 1)\n\n\n@app.on_startup\nasync def setup_later(field: int = Context()):\n    assert field == 1\n
","boost":10},{"location":"getting-started/lifespan/hooks/#some-more-details","title":"Some more details","text":"","boost":10},{"location":"getting-started/lifespan/hooks/#async-or-not-async","title":"Async or not async","text":"

In the asynchronous version of the application, both asynchronous and synchronous methods can be used as hooks. In the synchronous version, only synchronous methods are available.

","boost":10},{"location":"getting-started/lifespan/hooks/#command-line-arguments","title":"Command line arguments","text":"

Command line arguments are available in all @app.on_startup hooks. To use them in other parts of the application, put them in the ContextRepo.

","boost":10},{"location":"getting-started/lifespan/hooks/#broker-initialization","title":"Broker initialization","text":"

The @app.on_startup hooks are called BEFORE the broker is launched by the application. The @app.after_shutdown hooks are triggered AFTER stopping the broker.

If you want to perform some actions AFTER initializing the broker: send messages, initialize objects, etc., you should use the @app.after_startup hook.

","boost":10},{"location":"getting-started/lifespan/test/","title":"Events Testing","text":"

In the most cases you are testing your subsriber/publisher functions, but sometimes you need to trigger some lifespan hooks in your tests too.

For this reason, FastStream has a special TestApp patcher working as a regular async context manager.

KafkaRabbitMQNATSRedis
import pytest\n\nfrom faststream import FastStream, TestApp\nfrom faststream.kafka import KafkaBroker, TestKafkaBroker\n\napp = FastStream(KafkaBroker())\n\n\n@app.after_startup\nasync def handle():\n    print(\"Calls in tests too!\")\n\n\n@pytest.mark.asyncio\nasync def test_lifespan():\n    async with (\n        TestKafkaBroker(app.broker, connect_only=True),\n        TestApp(app),\n    ):\n        # test something\n        pass\n
import pytest\n\nfrom faststream import FastStream, TestApp\nfrom faststream.rabbit import RabbitBroker, TestRabbitBroker\n\napp = FastStream(RabbitBroker())\n\n\n@app.after_startup\nasync def handle():\n    print(\"Calls in tests too!\")\n\n\n@pytest.mark.asyncio\nasync def test_lifespan():\n    async with (\n        TestRabbitBroker(app.broker, connect_only=True),\n        TestApp(app),\n    ):\n        # test something\n        pass\n
import pytest\n\nfrom faststream import FastStream, TestApp\nfrom faststream.nats import NatsBroker, TestNatsBroker\n\napp = FastStream(NatsBroker())\n\n\n@app.after_startup\nasync def handle():\n    print(\"Calls in tests too!\")\n\n\n@pytest.mark.asyncio\nasync def test_lifespan():\n    async with (\n        TestNatsBroker(app.broker, connect_only=True),\n        TestApp(app),\n    ):\n        # test something\n        pass\n
import pytest\n\nfrom faststream import FastStream, TestApp\nfrom faststream.redis import RedisBroker, TestRedisBroker\n\napp = FastStream(RedisBroker())\n\n\n@app.after_startup\nasync def handle():\n    print(\"Calls in tests too!\")\n\n\n@pytest.mark.asyncio\nasync def test_lifespan():\n    async with (\n        TestRedisBroker(app.broker, connect_only=True),\n        TestApp(app),\n    ):\n        # test something\n        pass\n
","boost":10},{"location":"getting-started/lifespan/test/#using-with-testbroker","title":"Using with TestBroker","text":"

If you want to use In-Memory patched broker in your tests, it's advisable to patch the broker first (before applying the application patch).

Also, TestApp and TestBroker are calling broker.start() both. According to the original logic, broker should be started in the FastStream application, but TestBroker applied first breaks this behavior. This reason TestApp prevents TestBroker broker.start() call if it placed incide TestBroker context.

This behavior is ruled by connect_only TestBroker argument. By default it has None value, but TestApp can set it to True/False by inner logic. To prevent this \"magic\", just setup connect_only argument manually.

Warning

With connect_only=False, all FastStream hooks will be called after broker was started, what can breaks some @app.on_startup logic.

","boost":10},{"location":"getting-started/middlewares/","title":"Middlewares","text":"

Middlewares are a powerful mechanism that allows you to add additional logic to any stage of the message processing pipeline.

This way, you can greatly extend your FastStream application with features such as:

Middlewares have several methods to override. You can implement some or all of them and use middlewares at the broker, router, or subscriber level. Thus, middlewares are the most flexible FastStream feature.

","boost":10},{"location":"getting-started/middlewares/#message-receive-wrapper","title":"Message Receive Wrapper","text":"

Unfortunately, this powerful feature has a somewhat complex signature too.

Using middlewares, you can wrap the entire message processing pipeline. In this case, you need to specify on_receive and after_processed methods:

from faststream import BaseMiddleware\n\nclass MyMiddleware(BaseMiddleware):\n    async def on_receive(self):\n        print(f\"Received: {self.message}\")\n        return await super().on_receive()\n\n    async def after_processed(self, exc_type, exc_val, exec_tb):\n        return await super().after_processed(exc_type, exc_val, exec_tb)\n

These methods should be overwritten only in a broker-level middlewares.

Broker(middlewares=[MyMiddleware])\n

In other cases, on_receive will be called at every subscriber filter function call.

Tip

Please always call super() methods at the end of your function; this is important for correct error processing.

","boost":10},{"location":"getting-started/middlewares/#message-consuming-wrapper","title":"Message Consuming Wrapper","text":"

Also, using middlewares, you are able to wrap consumer function calls directly.

In this case, you need to specify on_receive and after_processed methods:

from typing import Optional\n\nfrom faststream import BaseMiddleware:\nfrom faststream.types import DecodedMessage\n\nclass MyMiddleware(BaseMiddleware):\n    async def on_consume(self, msg: DecodedMessage) -> DecodedMessage:\n        return await super().on_consume(msg)\n\n    async def after_consume(self, err: Optional[Exception]) -> None:\n        return await super().after_consume(err)\n

This way, you can patch the incoming message body right before passing it to your consumer subscriber.

Also, if you have multiple filters for one subscriber, these methods will be called at once when the filtering is completed successfully.

","boost":10},{"location":"getting-started/middlewares/#message-publishing-wrapper","title":"Message Publishing Wrapper","text":"

Finally, using middlewares, you are able to patch outgoing messages too. For example, you can compress/encode outgoing messages at the application level.

In this, case you need to specify on_publish and after_publish methods:

from typing import Optional\n\nfrom faststream import BaseMiddleware:\nfrom faststream.types import SendableMessage\n\nclass MyMiddleware(BaseMiddleware):\n    async def on_publish(self, msg: SendableMessage) -> SendableMessage:\n        return await super().on_publish(msg)\n\n    async def after_publish(self, err: Optional[Exception]) -> None:\n        return await super().after_publish(err)\n
","boost":10},{"location":"getting-started/publishing/","title":"Publishing Basics","text":"

FastStream is broker-agnostic and easy to use, even as a client in non-FastStream applications.

It offers several use cases for publishing messages:

All of these variants have their own advantages and limitations, so you can choose what you want based on your requirements. Please visit the following pages for details.

","boost":10},{"location":"getting-started/publishing/#serialization","title":"Serialization","text":"

FastStream allows you to publish any JSON-serializable messages (Python types, Pydantic models, etc.) or raw bytes.

It automatically sets up all required headers, especially the correlation_id, which is used to trace message processing pipelines across all services.

The content-type is a meaningfull header for FastStream services. It helps the framework serialize messages faster, selecting the right serializer based on the header. This header is automatically set by FastStream too, but you should set it up manually using other libraries to interact with FastStream applications.

Content-Type can be:

By the way, you can use application/json for all of your messages if they are not raw bytes. You can even omit using any header at all, but it makes serialization slightly slower.

","boost":10},{"location":"getting-started/publishing/#publishing","title":"Publishing","text":"

FastStream can also be used as a Broker client to send messages in other applications. It is quite straightforward and similar to aiohttp or requests.

You just need to connect your broker, and you are ready to send a message. Additionally, you can use Broker as an async context manager to establish a connection and disconnect when leaving the scope.

To publish a message, simply set up the message content and a routing key:

KafkaRabbitMQNATSRedis
async with KafkaBroker() as br:\n    await br.publish(\"message\", \"topic\")\n
async with RabbitBroker() as br:\n    await br.publish(\"message\", \"queue\")\n
async with NatsBroker() as br:\n    await br.publish(\"message\", \"subject\")\n
async with RedisBroker() as br:\n    await br.publish(\"message\", \"channel\")\n
","boost":10},{"location":"getting-started/publishing/broker/","title":"Broker Publishing","text":"

The easiest way to publish a message is to use a Broker, which allows you to use it as a publisher client in any applications.

In the FastStream project, this call is not represented in the AsyncAPI scheme. You can use it to send rarely-publishing messages, such as startup or shutdown events.

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle():\n    await broker.publish(\"Hi!\", topic=\"another-topic\")\n\n\n@broker.subscriber(\"another-topic\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", topic=\"test-topic\")\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle():\n    await broker.publish(\"Hi!\", queue=\"another-queue\")\n\n\n@broker.subscriber(\"another-queue\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", queue=\"test-queue\")\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle():\n    await broker.publish(\"Hi!\", subject=\"another-subject\")\n\n\n@broker.subscriber(\"another-subject\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", subject=\"test-subject\")\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle():\n    await broker.publish(\"Hi!\", channel=\"another-channel\")\n\n\n@broker.subscriber(\"another-channel\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", channel=\"test-channel\")\n
","boost":10},{"location":"getting-started/publishing/decorator/","title":"Publisher Decorator","text":"

The second easiest way to publish messages is by using the Publisher Decorator. This method has an AsyncAPI representation and is suitable for quickly creating applications. However, it doesn't provide all testing features.

It creates a structured DataPipeline unit with an input and output. The order of Subscriber and Publisher decorators doesn't matter, but @broker.publisher(...) can be used only with functions already decorated by a @broker.subscriber(...).

Note

It uses the handler function's return type annotation to cast the function's return value before sending, so be accurate with it.

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\n@broker.publisher(\"another-topic\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-topic\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", topic=\"test-topic\")\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\n@broker.publisher(\"another-queue\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-queue\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", queue=\"test-queue\")\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\n@broker.publisher(\"another-subject\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-subject\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", subject=\"test-subject\")\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\n@broker.publisher(\"another-channel\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-channel\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", channel=\"test-channel\")\n
","boost":10},{"location":"getting-started/publishing/decorator/#message-broadcasting","title":"Message Broadcasting","text":"

The decorator can be used multiple times with one function to broadcast the function's return:

@broker.subscriber(\"in\")\n@broker.publisher(\"first-out\")\n@broker.publisher(\"second-out\")\nasync def handle(msg) -> str:\n    return \"Response\"\n

This way you will send a copy of your return to the all output topics.

Note

Also, if this subscriber consumes a message with RPC mode, it sends a reply not only to the RPC channel but also to all publishers as well.

","boost":10},{"location":"getting-started/publishing/decorator/#details","title":"Details","text":"

Additionally, @broker.publisher(...) automatically sends a message with the same correlation_id as the incoming message. This way, you get the same correlation_id for the entire message pipeline process across all services, allowing you to collect a trace.

","boost":10},{"location":"getting-started/publishing/direct/","title":"Publisher Direct Usage","text":"

The Publisher Object provides a full-featured way to publish messages. It has an AsyncAPI representation and includes testability features.

This method creates a reusable Publisher object that can be used directly to publish a message:

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-topic\")\n\n@broker.subscriber(\"test-topic\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n\n\n@broker.subscriber(\"another-topic\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-queue\")\n\n@broker.subscriber(\"test-queue\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n\n\n@broker.subscriber(\"another-queue\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-subject\")\n\n@broker.subscriber(\"test-subject\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n\n\n@broker.subscriber(\"another-subject\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-channel\")\n\n@broker.subscriber(\"test-channel\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n\n\n@broker.subscriber(\"another-channel\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n

It is something in the middle between broker publish and object decorator. It has an AsyncAPI representation and testability features (like the object decorator), but allows you to send different messages to different outputs (like the broker publish).

@broker.subscriber(\"in\")\nasync def handle(msg) -> str:\n    await publisher1.publish(\"Response-1\")\n    await publisher2.publish(\"Response-2\")\n

Note

When using this method, FastStream doesn't reuse the incoming correlation_id to mark outgoing messages with it. You should set it manually if it is required.

","boost":10},{"location":"getting-started/publishing/object/","title":"Publisher Object","text":"

The Publisher Object provides a full-featured way to publish messages. It has an AsyncAPI representation and includes testability features. This method creates a reusable Publisher object.

Additionally, this object can be used as a decorator. The order of Subscriber and Publisher decorators doesn't matter, but @publisher can be used only with functions already decorated by a @broker.subscriber(...).

Note

It uses the handler function's return type annotation to cast the function's return value before sending, so be accurate with it.

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-topic\")\n\n@publisher\n@broker.subscriber(\"test-topic\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-topic\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-queue\")\n\n@publisher\n@broker.subscriber(\"test-queue\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-queue\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-subject\")\n\n@publisher\n@broker.subscriber(\"test-subject\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-subject\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-channel\")\n\n@publisher\n@broker.subscriber(\"test-channel\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-channel\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
","boost":10},{"location":"getting-started/publishing/object/#message-broadcasting","title":"Message Broadcasting","text":"

The decorator can be used multiple times with one function to broadcast the function's return:

@publisher1\n@publisher2\n@broker.subscriber(\"in\")\nasync def handle(msg) -> str:\n    return \"Response\"\n

This way, you will send a copy of your return to all output topics.

Note

Also, if this subscriber consumes a message with RPC mode, it sends a reply not only to the RPC channel but also to all publishers as well.

","boost":10},{"location":"getting-started/publishing/object/#details","title":"Details","text":"

Additionally, @publisher automatically sends a message with the same correlation_id as the incoming message. This way, you get the same correlation_id for the entire message pipeline process across all services, allowing you to collect a trace.

","boost":10},{"location":"getting-started/publishing/test/","title":"Publisher Testing","text":"

If you are working with a Publisher object (either as a decorator or directly), you have several testing features available:

","boost":10},{"location":"getting-started/publishing/test/#base-application","title":"Base Application","text":"

Let's take a look at a simple application example with a publisher as a decorator or as a direct call:

DecoratorDirect KafkaRabbitMQNATSRedis
publisher = broker.publisher(\"another-topic\")\n\n@publisher\n@broker.subscriber(\"test-topic\")\nasync def handle() -> str:\n    return \"Hi!\"\n
publisher = broker.publisher(\"another-queue\")\n\n@publisher\n@broker.subscriber(\"test-queue\")\nasync def handle() -> str:\n    return \"Hi!\"\n
publisher = broker.publisher(\"another-subject\")\n\n@publisher\n@broker.subscriber(\"test-subject\")\nasync def handle() -> str:\n    return \"Hi!\"\n
publisher = broker.publisher(\"another-channel\")\n\n@publisher\n@broker.subscriber(\"test-channel\")\nasync def handle() -> str:\n    return \"Hi!\"\n
KafkaRabbitMQNATSRedis
publisher = broker.publisher(\"another-topic\")\n\n@broker.subscriber(\"test-topic\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n
publisher = broker.publisher(\"another-queue\")\n\n@broker.subscriber(\"test-queue\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n
publisher = broker.publisher(\"another-subject\")\n\n@broker.subscriber(\"test-subject\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n
publisher = broker.publisher(\"another-channel\")\n\n@broker.subscriber(\"test-channel\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n
","boost":10},{"location":"getting-started/publishing/test/#testing","title":"Testing","text":"

To test it, you just need to patch your broker with a special TestBroker.

KafkaRabbitMQNATSRedis
import pytest\n\nfrom faststream.kafka import TestKafkaBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestKafkaBroker(broker) as br:\n        await br.publish(\"\", topic=\"test-topic\")\n
import pytest\n\nfrom faststream.rabbit import TestRabbitBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRabbitBroker(broker) as br:\n        await br.publish(\"\", queue=\"test-queue\")\n
import pytest\n\nfrom faststream.nats import TestNatsBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestNatsBroker(broker) as br:\n        await br.publish(\"\", subject=\"test-subject\")\n
import pytest\n\nfrom faststream.redis import TestRedisBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRedisBroker(broker) as br:\n        await br.publish(\"\", channel=\"test-channel\")\n

By default, it patches you broker to run In-Memory, so you can use it without any external broker. It should be extremely usefull in your CI or local development environment.

Also, it allows you to check the outgoing message body in the same way as with a subscriber.

publisher.mock.assert_called_once_with(\"Hi!\")\n

Note

The Publisher mock contains not just a publish method input value. It sets up a virtual consumer for an outgoing topic, consumes a message, and stores this consumed one.

Additionally, TestBroker can be used with a real external broker to make your tests end-to-end suitable. For more information, please visit the subscriber testing page.

","boost":10},{"location":"getting-started/routers/","title":"Broker Router","text":"

Sometimes you want to:

For these reasons, FastStream has a special Broker Router.

","boost":10},{"location":"getting-started/routers/#router-usage","title":"Router Usage","text":"

First, you need to import the Broker Router from the same module from where you imported the broker.

When creating a Broker Router, you can specify a prefix that will be automatically applied to all subscribers and publishers of this router.

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaRouter\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\nrouter = KafkaRouter(prefix=\"prefix_\")\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker, RabbitRouter\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\nrouter = RabbitRouter(prefix=\"prefix_\")\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker, NatsRouter\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\nrouter = NatsRouter(prefix=\"prefix_\")\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker, RedisRouter\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\nrouter = RedisRouter(prefix=\"prefix_\")\n

Now you can use the created router to register handlers and publishers as if it were a regular broker

KafkaRabbitMQNATSRedis
@router.subscriber(\"test-topic\")\n@router.publisher(\"another-topic\")\nasync def handle(name: str, user_id: int) -> str:\n    assert name == \"John\"\n    assert user_id == 1\n    return \"Hi!\"\n\n\n@router.subscriber(\"another-topic\")\nasync def handle_response(msg: str):\n    assert msg == \"Hi!\"\n
@router.subscriber(\"test-queue\")\n@router.publisher(\"another-queue\")\nasync def handle(name: str, user_id: int) -> str:\n    assert name == \"John\"\n    assert user_id == 1\n    return \"Hi!\"\n\n\n@router.subscriber(\"another-queue\")\nasync def handle_response(msg: str):\n    assert msg == \"Hi!\"\n
@router.subscriber(\"test-subject\")\n@router.publisher(\"another-subject\")\nasync def handle(name: str, user_id: int) -> str:\n    assert name == \"John\"\n    assert user_id == 1\n    return \"Hi!\"\n\n\n@router.subscriber(\"another-subject\")\nasync def handle_response(msg: str):\n    assert msg == \"Hi!\"\n
@router.subscriber(\"test-channel\")\n@router.publisher(\"another-channel\")\nasync def handle(name: str, user_id: int) -> str:\n    assert name == \"John\"\n    assert user_id == 1\n    return \"Hi!\"\n\n\n@router.subscriber(\"another-channel\")\nasync def handle_response(msg: str):\n    assert msg == \"Hi!\"\n

Then you can simply include all the handlers declared using the router in your broker

broker.include_router(router)\n

Please note that when publishing a message, you now need to specify the same prefix that you used when creating the router

KafkaRabbitMQNATSRedis
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    topic=\"prefix_test-topic\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    queue=\"prefix_test-queue\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    subject=\"prefix_test-subject\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    channel=\"prefix_test-channel\",\n)\n

Tip

Also, when creating a Broker Router, you can specify middleware, dependencies, parser and decoder to apply them to all subscribers declared via this router.

","boost":10},{"location":"getting-started/routers/#delay-handler-registration","title":"Delay Handler Registration","text":"

If you want to separate your application's core logic from FastStream's routing logic, you can write some core functions and use them as Broker Router handlers later:

KafkaRabbitMQNATSRedis
from faststream.kafka import KafkaRoute, KafkaRouter\n\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\nrouter = KafkaRouter(\n    handlers=(\n        KafkaRoute(handle, \"test-topic\"),\n    )\n)\n
from faststream.rabbit import RabbitRoute, RabbitRouter\n\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\nrouter = RabbitRouter(\n    handlers=(\n        RabbitRoute(handle, \"test-queue\"),\n    )\n)\n
from faststream.nats import NatsRoute, NatsRouter\n\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\nrouter = NatsRouter(\n    handlers=(\n        NatsRoute(handle, \"test-subject\"),\n    )\n)\n
from faststream.redis import RedisRouter, RedisRoute\n\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\nrouter = RedisRouter(\n    handlers=(\n        RedisRoute(handle, \"test-channel\"),\n    )\n)\n

Warning

Be careful, this way you won't be able to test your handlers with a mock object.

","boost":10},{"location":"getting-started/serialization/","title":"Custom Serialization","text":"

By default, FastStream uses the JSON format to send and receive messages. However, if you need to handle messages in other formats or with additional serialization steps, such as gzip, lz4, Avro, Protobuf or Msgpack, you can easily modify the serialization logic.

","boost":10},{"location":"getting-started/serialization/#serialization-steps","title":"Serialization Steps","text":"

Before the message reaches your subscriber, FastStream applies two functions to it sequentially: parse_message and decode_message. You can modify one or both stages depending on your needs.

","boost":10},{"location":"getting-started/serialization/#message-parsing","title":"Message Parsing","text":"

At this stage, FastStream serializes an incoming message from the broker's framework into a general format called - StreamMessage. During this stage, the message body remains in the form of raw bytes.

This stage is closely related to the features of the broker used, and in most cases, redefining it is not necessary.

The parser declared at the broker level will be applied to all subscribers. The parser declared at the subscriber level is applied only to that specific subscriber and overrides the `broker' parser if specified.

","boost":10},{"location":"getting-started/serialization/#message-decoding","title":"Message Decoding","text":"

At this stage, the body of the StreamMessage is transformed into a format suitable for processing within your subscriber function. This is the stage you may need to redefine more often.

","boost":10},{"location":"getting-started/serialization/decoder/","title":"Custom Decoder","text":"

At this stage, the body of a StreamMessage is transformed into the format that it will take when it enters your handler function. This stage is the one you will need to redefine more often.

","boost":10},{"location":"getting-started/serialization/decoder/#signature","title":"Signature","text":"

The original decoder function has a relatively simple signature (this is a simplified version):

KafkaRabbitMQNATSRedis
from faststream.types import DecodedMessage\nfrom faststream.kafka import KafkaMessage\n\ndef decoder(msg: KafkaMessage) -> DecodedMessage:\n    ...\n
from faststream.types import DecodedMessage\nfrom faststream.rabbit import RabbitMessage\n\ndef decoder(msg: RabbitMessage) -> DecodedMessage:\n    ...\n
from faststream.types import DecodedMessage\nfrom faststream.nats import NatsMessage\n\ndef decoder(msg: NatsMessage) -> DecodedMessage:\n    ...\n
from faststream.types import DecodedMessage\nfrom faststream.redis import RedisMessage\n\ndef decoder(msg: RedisMessage) -> DecodedMessage:\n    ...\n

Alternatively, you can reuse the original decoder function with the following signature:

KafkaRabbitMQNATSRedis
from types import Callable, Awaitable\nfrom faststream.types import DecodedMessage\nfrom faststream.kafka import KafkaMessage\n\nasync def decoder(\n    msg: KafkaMessage,\n    original_decoder: Callable[[KafkaMessage], Awaitable[DecodedMessage]],\n) -> DecodedMessage:\n    return await original_decoder(msg)\n
from types import Callable, Awaitable\nfrom faststream.types import DecodedMessage\nfrom faststream.rabbit import RabbitMessage\n\nasync def decoder(\n    msg: RabbitMessage,\n    original_decoder: Callable[[RabbitMessage], Awaitable[DecodedMessage]],\n) -> DecodedMessage:\n    return await original_decoder(msg)\n
from types import Callable, Awaitable\nfrom faststream.types import DecodedMessage\nfrom faststream.nats import NatsMessage\n\nasync def decoder(\n    msg: NatsMessage,\n    original_decoder: Callable[[NatsMessage], Awaitable[DecodedMessage]],\n) -> DecodedMessage:\n    return await original_decoder(msg)\n
from types import Callable, Awaitable\nfrom faststream.types import DecodedMessage\nfrom faststream.redis import RedisMessage\n\nasync def decoder(\n    msg: RedisMessage,\n    original_decoder: Callable[[RedisMessage], Awaitable[DecodedMessage]],\n) -> DecodedMessage:\n    return await original_decoder(msg)\n

Note

The original decoder is always an asynchronous function, so your custom decoder should also be asynchronous.

Afterward, you can set this custom decoder at the broker or subscriber level.

","boost":10},{"location":"getting-started/serialization/decoder/#example","title":"Example","text":"

You can find examples of Protobuf, Msgpack and Avro serialization in the next article.

","boost":10},{"location":"getting-started/serialization/examples/","title":"Serialization examples","text":"","boost":10},{"location":"getting-started/serialization/examples/#protobuf","title":"Protobuf","text":"

In this section, we will explore an example using Protobuf. However, this approach is also applicable to other serialization methods.

Protobuf

Protobuf is an alternative message serialization method commonly used in GRPC. Its main advantage is that it results in much smaller message sizes1 compared to JSON, but it requires a message schema (.proto files) on both the client and server sides.

To begin, install the necessary dependencies:

pip install grpcio-tools\n

Next, let's define the schema for our message:

message.proto
syntax = \"proto3\";\n\nmessage Person {\n    string name = 1;\n    float age = 2;\n}\n

Now, generate a Python class to work with messages in Protobuf format:

python -m grpc_tools.protoc --python_out=. --pyi_out=. -I . message.proto\n

This generates two files: message_pb2.py and message_pb2.pyi. We can use the generated class to serialize our messages:

from message_pb2 import Person\n\nfrom faststream import FastStream, Logger, NoCast\nfrom faststream.rabbit import RabbitBroker, RabbitMessage\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\n\nasync def decode_message(msg: RabbitMessage) -> Person:\n    decoded = Person()\n    decoded.ParseFromString(msg.body)\n    return decoded\n\n\n@broker.subscriber(\"test\", decoder=decode_message)\nasync def consume(body: NoCast[Person], logger: Logger):\n    logger.info(body)\n\n\n@app.after_startup\nasync def publish():\n    body = Person(name=\"John\", age=25).SerializeToString()\n    await broker.publish(body, \"test\")\n

Note that we used the NoCast annotation to exclude the message from the pydantic representation of our handler.

async def consume(body: NoCast[Person], logger: Logger):\n
","boost":10},{"location":"getting-started/serialization/examples/#msgpack","title":"Msgpack","text":"

Msgpack is another alternative binary data format. Its main advantage is that it results in smaller message sizes2 compared to JSON, although slightly larger than Protobuf. The key advantage is that it doesn't require a message schema, making it easy to use in most cases.

To get started, install the necessary dependencies:

pip install msgpack\n

Since there is no need for a schema, you can easily write a Msgpack decoder:

import msgpack\n\nfrom faststream import FastStream, Logger\nfrom faststream.rabbit import RabbitBroker, RabbitMessage\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\n\nasync def decode_message(msg: RabbitMessage):\n    return msgpack.loads(msg.body)\n\n\n@broker.subscriber(\"test\", decoder=decode_message)\nasync def consume(name: str, age: int, logger: Logger):\n    logger.info(f\"{name}: {age}\")\n\n\n@app.after_startup\nasync def publish():\n    body = msgpack.dumps({\"name\": \"John\", \"age\": 25}, use_bin_type=True)\n    await broker.publish(body, \"test\")\n

Using Msgpack is much simpler than using Protobuf schemas. Therefore, if you don't have strict message size limitations, you can use Msgpack serialization in most cases.

","boost":10},{"location":"getting-started/serialization/examples/#avro","title":"Avro","text":"

In this section, let's explore how to use Avro encoding and decoding to encode/decode our messages as part of FastStream.

Avro

Apache Avro uses JSON to define data types and protocols and serializes data in a compact binary format. Avro utilizes a schema to structure the data that is being encoded. Schemas are composed of primitive types (null, boolean, int, long, float, double, bytes, and string) and complex types (record, enum, array, map, union, and fixed).

To get started, install the necessary dependencies:

pip install fastavro\n

Next, let's define the schema for our message. You can either define it in the Python file itself as:

person_schema = {\n    \"type\": \"record\",\n    \"namespace\": \"Person\",\n    \"name\": \"Person\",\n    \"fields\": [\n        {\"doc\": \"Name\", \"type\": \"string\", \"name\": \"name\"},\n        {\"doc\": \"Age\", \"type\": \"int\", \"name\": \"age\"},\n    ],\n}\n

Or you can load the schema from an avsc file as:

person_schema = fastavro.schema.load_schema(\"person.avsc\")\n

The contents of the person.avsc file are:

person.avsc
{\n    \"type\": \"record\",\n    \"namespace\": \"Person\",\n    \"name\": \"Person\",\n    \"fields\": [\n        {\"doc\": \"Name\", \"type\": \"string\", \"name\": \"name\"},\n        {\"doc\": \"Age\", \"type\": \"int\", \"name\": \"age\"}\n    ]\n}\n

Finally, let's use Avro's schemaless_reader and schemaless_writer to decode and encode messages in the FastStream app.

import io\n\nimport fastavro\n\nfrom faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker, KafkaMessage\n\nbroker = KafkaBroker()\napp = FastStream(broker)\n\n\n# person_schema = ...\nschema = fastavro.schema.parse_schema(person_schema)\n\nasync def decode_message(msg: KafkaMessage):\n    bytes_reader = io.BytesIO(msg.body)\n    msg_dict = fastavro.schemaless_reader(bytes_reader, schema)\n    return msg_dict\n\n\n@broker.subscriber(\"test\", decoder=decode_message)\nasync def consume(name: str, age: int, logger: Logger):\n    logger.info(f\"{name}: {age}\")\n\n\n@app.after_startup\nasync def publish():\n    msg = {\"name\": \"John\", \"age\": 25}\n\n    bytes_writer = io.BytesIO()\n    fastavro.schemaless_writer(bytes_writer, schema, msg)\n    raw_bytes = bytes_writer.getvalue()\n\n    await broker.publish(raw_bytes, \"test\")\n
","boost":10},{"location":"getting-started/serialization/examples/#tips","title":"Tips","text":"","boost":10},{"location":"getting-started/serialization/examples/#data-compression","title":"Data Compression","text":"

If you are dealing with very large messages, consider compressing them as well. You can explore libraries such as lz4 or zstd for compression algorithms.

Compression can significantly reduce message size, especially if there are repeated blocks. However, in the case of small message bodies, data compression may increase the message size. Therefore, you should assess the compression impact based on your specific application requirements.

","boost":10},{"location":"getting-started/serialization/examples/#broker-level-serialization","title":"Broker-Level Serialization","text":"

You can still set a custom decoder at the Broker or Router level. However, if you want to automatically encode publishing messages as well, you should explore Middleware for serialization implimentation.

  1. For example, a message like { \"name\": \"John\", \"age\": 25 } in JSON takes 27 bytes, while in Protobuf, it takes only 11 bytes. With lists and more complex structures, the savings can be even more significant (up to 20x times).\u00a0\u21a9

  2. A message with Msgpack serialization, such as { \"name\": \"John\", \"age\": 25 }, takes 16 bytes.\u00a0\u21a9

","boost":10},{"location":"getting-started/serialization/parser/","title":"Custom Parser","text":"

At this stage, FastStream serializes an incoming message from the broker's framework into a general format called StreamMessage. During this stage, the message body remains in the form of raw bytes.

StreamMessage is a general representation of a message within FastStream. It contains all the information required for message processing within FastStreams. It is even used to represent message batches, so the primary reason to customize it is to redefine the metadata associated with FastStream messages.

For example, you can specify your own header with the message_id semantic. This allows you to inform FastStream about this custom header through parser customization.

","boost":10},{"location":"getting-started/serialization/parser/#signature","title":"Signature","text":"

To create a custom message parser, you should write a regular Python function (synchronous or asynchronous) with the following signature:

KafkaRabbitMQNATSRedis
from aiokafka import ConsumerRecord\nfrom faststream.kafka import KafkaMessage\n\ndef parser(msg: ConsumerRecord) -> KafkaMessage:\n    ...\n
from aio_pika import IncomingMessage\nfrom faststream.rabbit import RabbitMessage\n\ndef parser(msg: IncomingMessage) -> RabbitMessage:\n    ...\n
from nats.aio.msg import Msg\nfrom faststream.nats import NatsMessage\n\ndef parser(msg: Msg) -> NatsMessage:\n    ...\n
from faststream.redis import RedisMessage\nfrom faststream.redis.message import PubSubMessage\n\ndef parser(msg: PubSubMessage) -> RedisMessage:\n    ...\n

Alternatively, you can reuse the original parser function with the following signature:

KafkaRabbitMQNATSRedis
from types import Callable, Awaitable\nfrom aiokafka import ConsumerRecord\nfrom faststream.kafka import KafkaMessage\n\nasync def parser(\n    msg: ConsumerRecord,\n    original_parser: Callable[[ConsumerRecord], Awaitable[KafkaMessage]],\n) -> KafkaMessage:\n    return await original_parser(msg)\n
from types import Callable, Awaitable\nfrom aio_pika import IncomingMessage\nfrom faststream.rabbit import RabbitMessage\n\nasync def parser(\n    msg: IncomingMessage,\n    original_parser: Callable[[IncomingMessage], Awaitable[RabbitMessage]],\n) -> RabbitMessage:\n    return await original_parser(msg)\n
from types import Callable, Awaitable\nfrom nats.aio.msg import Msg\nfrom faststream.nats import NatsMessage\n\nasync def parser(\n    msg: Msg,\n    original_parser: Callable[[Msg], Awaitable[NatsMessage]],\n) -> NatsMessage:\n    return await original_parser(msg)\n
from types import Callable, Awaitable\nfrom faststream.redis import RedisMessage\nfrom faststream.redis.message import PubSubMessage\n\nasync def parser(\n    msg: PubSubMessage,\n    original_parser: Callable[[PubSubMessage], Awaitable[RedisMessage]],\n) -> RedisMessage:\n    return await original_parser(msg)\n

The argument naming doesn't matter; the parser will always be placed as the second argument.

Note

The original parser is always an asynchronous function, so your custom parser should also be asynchronous.

Afterward, you can set this custom parser at the broker or subscriber level.

","boost":10},{"location":"getting-started/serialization/parser/#example","title":"Example","text":"

As an example, let's redefine message_id to a custom header:

KafkaRabbitMQNATSRedis
from typing import Awaitable, Callable\n\nfrom aiokafka import ConsumerRecord\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaMessage\n\n\nasync def custom_parser(\n    msg: ConsumerRecord,\n    original_parser: Callable[[ConsumerRecord], Awaitable[KafkaMessage]],\n) -> KafkaMessage:\n    parsed_msg = await original_parser(msg)\n    parsed_msg.message_id = parsed_msg.headers[\"custom_message_id\"]\n    return parsed_msg\n\n\nbroker = KafkaBroker(parser=custom_parser)\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def handle():\n    ...\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", \"test\", headers={\"custom_message_id\": \"1\"})\n
from typing import Awaitable, Callable\n\nfrom aio_pika import IncomingMessage\n\nfrom faststream import FastStream\nfrom faststream.rabbit import RabbitBroker, RabbitMessage\n\n\nasync def custom_parser(\n    msg: IncomingMessage,\n    original_parser: Callable[[IncomingMessage], Awaitable[RabbitMessage]],\n) -> RabbitMessage:\n    parsed_msg = await original_parser(msg)\n    parsed_msg.message_id = parsed_msg.headers[\"custom_message_id\"]\n    return parsed_msg\n\n\nbroker = RabbitBroker(parser=custom_parser)\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def handle():\n    ...\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", \"test\", headers={\"custom_message_id\": \"1\"})\n
from typing import Awaitable, Callable\n\nfrom nats.aio.msg import Msg\n\nfrom faststream import FastStream\nfrom faststream.nats import NatsBroker, NatsMessage\n\n\nasync def custom_parser(\n    msg: Msg,\n    original_parser: Callable[[Msg], Awaitable[NatsMessage]],\n) -> NatsMessage:\n    parsed_msg = await original_parser(msg)\n    parsed_msg.message_id = parsed_msg.headers[\"custom_message_id\"]\n    return parsed_msg\n\n\nbroker = NatsBroker(parser=custom_parser)\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def handle():\n    ...\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", \"test\", headers={\"custom_message_id\": \"1\"})\n
from typing import Awaitable, Callable\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker, RedisMessage\nfrom faststream.redis.message import PubSubMessage\n\n\nasync def custom_parser(\n    msg: PubSubMessage,\n    original_parser: Callable[[PubSubMessage], Awaitable[RedisMessage]],\n) -> RedisMessage:\n    parsed_msg = await original_parser(msg)\n    parsed_msg.message_id = parsed_msg.headers[\"custom_message_id\"]\n    return parsed_msg\n\n\nbroker = RedisBroker(parser=custom_parser)\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def handle():\n    ...\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", \"test\", headers={\"custom_message_id\": \"1\"})\n
","boost":10},{"location":"getting-started/subscription/","title":"Subscription Basics","text":"

FastStream provides a Message Broker agnostic way to subscribe to event streams.

You need not even know about topics/queues/subjects or any broker inner objects you use. The basic syntax is the same for all brokers:

KafkaRabbitMQNATSRedis
from faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker()\n\n@broker.subscriber(\"test\")  # topic name\nasync def handle_msg(msg_body):\n    ...\n
from faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker()\n\n@broker.subscriber(\"test\")  # queue name\nasync def handle_msg(msg_body):\n    ...\n
from faststream.nats import NatsBroker\n\nbroker = NatsBroker()\n\n@broker.subscriber(\"test\")  # subject name\nasync def handle_msg(msg_body):\n    ...\n
from faststream.redis import RedisBroker\n\nbroker = RedisBroker()\n\n@broker.subscriber(\"test\")  # channel name\nasync def handle_msg(msg_body):\n    ...\n

Tip

If you want to use Message Broker specific features, please visit the corresponding broker documentation section. In the Tutorial section, the general features are described.

Also, synchronous functions are supported as well:

KafkaRabbitMQNATSRedis
from faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker()\n\n@broker.subscriber(\"test\")  # topic name\ndef handle_msg(msg_body):\n    ...\n
from faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker()\n\n@broker.subscriber(\"test\")  # queue name\ndef handle_msg(msg_body):\n    ...\n
from faststream.nats import NatsBroker\n\nbroker = NatsBroker()\n\n@broker.subscriber(\"test\")  # subject name\ndef handle_msg(msg_body):\n    ...\n
from faststream.redis import RedisBroker\n\nbroker = RedisBroker()\n\n@broker.subscriber(\"test\")  # channel name\ndef handle_msg(msg_body):\n    ...\n
","boost":10},{"location":"getting-started/subscription/#message-body-serialization","title":"Message Body Serialization","text":"

Generally, FastStream uses your function type annotation to serialize incoming message body with Pydantic. This is similar to how FastAPI works (if you are familiar with it).

@broker.subscriber(\"test\")\nasync def handle_str(\n    msg_body: str,\n):\n    ...\n

You can also access some extra features through the function arguments, such as Depends and Context if required.

However, you can easily disable Pydantic validation by creating a broker with the following option Broker(apply_types=False) (this also disables Context and Depends features).

This way FastStream still consumes json.loads result, but without pydantic validation and casting.

KafkaRabbitMQNATSRedis
from faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(apply_types=False)\n\n@broker.subscriber(\"test\")\nasync def handle_msg(msg_body: str):  # just an annotation, has no real effect\n    ...\n
from faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(apply_types=False)\n\n@broker.subscriber(\"test\")\nasync def handle_msg(msg_body: str):  # just an annotation, has no real effect\n    ...\n
from faststream.nats import NatsBroker\n\nbroker = NatsBroker(apply_types=False)\n\n@broker.subscriber(\"test\")\nasync def handle_msg(msg_body: str):  # just an annotation, has no real effect\n    ...\n
from faststream.redis import RedisBroker\n\nbroker = RedisBroker(apply_types=False)\n\n@broker.subscriber(\"test\")\nasync def handle_msg(msg_body: str):  # just an annotation, has no real effect\n    ...\n
","boost":10},{"location":"getting-started/subscription/#multiple-subscriptions","title":"Multiple Subscriptions","text":"

You can also subscribe to multiple event streams at the same time with one function. Just wrap it with multiple @broker.subscriber(...) decorators (they have no effect on each other).

@broker.subscriber(\"first_sub\")\n@broker.subscriber(\"second_sub\")\nasync def handler(msg):\n    ...\n
","boost":10},{"location":"getting-started/subscription/annotation/","title":"Annotation Serialization","text":"","boost":10},{"location":"getting-started/subscription/annotation/#basic-usage","title":"Basic usage","text":"

As you already know, FastStream serializes your incoming message body according to the function type annotations using Pydantic.

So, there are some valid usecases:

@broker.subscriber(\"test\")\nasync def handle(\n    msg: str,\n):\n    ...\n\n@broker.subscriber(\"test\")\nasync def handle(\n    msg: bytes,\n):\n    ...\n\n@broker.subscriber(\"test\")\nasync def handle(\n    msg: int,\n):\n    ...\n

As with other Python primitive types as well (float, bool, datetime, etc)

Note

If the incoming message cannot be serialized by the described schema, FastStream raises a pydantic.ValidationError with a correct log message.

Also, thanks to Pydantic (again), FastStream is able to serialize (and validate) more complex types like pydantic.HttpUrl, pydantic.PostitiveInt, etc.

","boost":10},{"location":"getting-started/subscription/annotation/#json-basic-serialization","title":"JSON Basic Serialization","text":"

But how can we serialize more complex message, like { \"name\": \"John\", \"user_id\": 1 } ?

For sure, we can serialize it as a simple dict

from typing import Dict, Any\n\n@broker.subscriber(\"test\")\nasync def handle(\n    msg: dict[str, Any],\n):\n    ...\n

But it doesn't looks like a correct message validation, does it?

For this reason, FastStream supports per-argument message serialization: you can declare multiple arguments with various types and your message will unpack to them:

KafkaRabbitMQNATSRedis
@broker.subscriber(\"test-topic\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
@broker.subscriber(\"test-queue\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
@broker.subscriber(\"test-subject\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
@broker.subscriber(\"test-channel\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
","boost":10},{"location":"getting-started/subscription/filtering/","title":"Application-level Filtering","text":"

FastStream also allows you to specify the message processing way using message headers, body type or something else. The filter feature enables you to consume various messages with different schemas within a single event stream.

Tip

Message must be consumed at ONCE (crossing filters are not allowed)

As an example, let's create a subscriber for both JSON and non-JSON messages:

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    \"test-topic\",\n    filter=lambda msg: msg.content_type == \"application/json\",\n)\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\n\n@broker.subscriber(\"test-topic\")\nasync def default_handler(msg: str):\n    assert msg == \"Hello, FastStream!\"\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    \"test-queue\",\n    filter=lambda msg: msg.content_type == \"application/json\",\n)\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\n\n@broker.subscriber(\"test-queue\")\nasync def default_handler(msg: str):\n    assert msg == \"Hello, FastStream!\"\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    \"test-subject\",\n    filter=lambda msg: msg.content_type == \"application/json\",\n)\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\n\n@broker.subscriber(\"test-subject\")\nasync def default_handler(msg: str):\n    assert msg == \"Hello, FastStream!\"\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    \"test-channel\",\n    filter=lambda msg: msg.content_type == \"application/json\",\n)\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\n\n@broker.subscriber(\"test-channel\")\nasync def default_handler(msg: str):\n    assert msg == \"Hello, FastStream!\"\n

Note

A subscriber without a filter is a default subscriber. It consumes messages that have not been consumed yet.

For now, the following message will be delivered to the handle function

KafkaRabbitMQNATSRedis
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    topic=\"test-topic\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    queue=\"test-queue\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    subject=\"test-subject\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    channel=\"test-channel\",\n)\n

And this one will be delivered to the default_handler

KafkaRabbitMQNATSRedis
await broker.publish(\n    \"Hello, FastStream!\",\n    topic=\"test-topic\",\n)\n
await broker.publish(\n    \"Hello, FastStream!\",\n    queue=\"test-queue\",\n)\n
await broker.publish(\n    \"Hello, FastStream!\",\n    subject=\"test-subject\",\n)\n
await broker.publish(\n    \"Hello, FastStream!\",\n    channel=\"test-channel\",\n)\n
","boost":10},{"location":"getting-started/subscription/pydantic/","title":"Pydantic Serialization","text":"","boost":10},{"location":"getting-started/subscription/pydantic/#pydanticfield","title":"pydantic.Field","text":"

Besides, FastStream uses your handlers' annotations to collect information about the application schema and generate AsyncAPI schema.

You can access this information with extra details using pydantic.Field (such as title, description and examples). Additionally, Fields usage allows you to add extra validations to your message schema.

Just use pydantic.Field as a function default argument:

KafkaRabbitMQNATSRedis
from pydantic import Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    ),\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    ),\n):\n    assert name == \"John\"\n    assert user_id == 1\n
from pydantic import Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    ),\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    ),\n):\n    assert name == \"John\"\n    assert user_id == 1\n
from pydantic import Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    ),\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    ),\n):\n    assert name == \"John\"\n    assert user_id == 1\n
from pydantic import Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    ),\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    ),\n):\n    assert name == \"John\"\n    assert user_id == 1\n

Tip

Also you can use typing.Annotated (python 3.9+) or typing_extensions.Annotated to declare your handler fields

name: Annotated[\n    str,\n    Field(..., examples=[\"John\"], description=\"Registered user name\")\n],\nuser_id: Annotated[\n    NonNegativeInt,\n    Field(..., examples=[1], description=\"Registered user id\"),\n]\n
","boost":10},{"location":"getting-started/subscription/pydantic/#pydanticbasemodel","title":"pydantic.BaseModel","text":"

To make your message schema reusable between different subscribers and publishers, you can decalre it as a pydantic.BaseModel and use it as a single message annotation:

KafkaRabbitMQNATSRedis
from pydantic import BaseModel, Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\nclass UserInfo(BaseModel):\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    )\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    )\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    user: UserInfo,\n):\n    assert user.name == \"John\"\n    assert user.user_id == 1\n
from pydantic import BaseModel, Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\nclass UserInfo(BaseModel):\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    )\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    )\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    user: UserInfo,\n):\n    assert user.name == \"John\"\n    assert user.user_id == 1\n
from pydantic import BaseModel, Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\nclass UserInfo(BaseModel):\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    )\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    )\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    user: UserInfo,\n):\n    assert user.name == \"John\"\n    assert user.user_id == 1\n
from pydantic import BaseModel, Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\nclass UserInfo(BaseModel):\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    )\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    )\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    user: UserInfo,\n):\n    assert user.name == \"John\"\n    assert user.user_id == 1\n
","boost":10},{"location":"getting-started/subscription/test/","title":"Subscriber Testing","text":"

Testability is a crucial part of any application, and FastStream provides you with the tools to test your code easily.

","boost":10},{"location":"getting-started/subscription/test/#original-application","title":"Original Application","text":"

Let's take a look at the original application to test

KafkaRabbitMQNATSRedis annotation_kafka.py
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
annotation_rabbit.py
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
annotation_nats.py
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
annotation_redis.py
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n

It consumes JSON messages like { \"name\": \"username\", \"user_id\": 1 }

You can test your consume function like a regular one, for sure:

@pytest.mark.asyncio\nasync def test_handler():\n    await handle(\"John\", 1)\n

But if you want to test your function closer to your real runtime, you should use the special FastStream test client.

","boost":10},{"location":"getting-started/subscription/test/#in-memory-testing","title":"In-Memory Testing","text":"

Deploying a whole service with a Message Broker is a bit too much just for testing purposes, especially in your CI environment. Not to mention the possible loss of messages due to network failures when working with real brokers.

For this reason, FastStream has a special TestClient to make your broker work in InMemory mode.

Just use it like a regular async context manager - all published messages will be routed in-memory (without any external dependencies) and consumed by the correct handler.

KafkaRabbitMQNATSRedis
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.kafka import TestKafkaBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestKafkaBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, topic=\"test-topic\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.rabbit import TestRabbitBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRabbitBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, queue=\"test-queue\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.nats import TestNatsBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestNatsBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, subject=\"test-subject\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.redis import TestRedisBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRedisBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, channel=\"test-channel\")\n
","boost":10},{"location":"getting-started/subscription/test/#catching-exceptions","title":"Catching Exceptions","text":"

This way you can catch any exceptions that occur inside your handler:

KafkaRabbitMQNATSRedis
@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestKafkaBroker(broker) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", topic=\"test-topic\")\n
@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestRabbitBroker(broker) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", queue=\"test-queue\")\n
@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestNatsBroker(broker) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", subject=\"test-subject\")\n
@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestRedisBroker(broker) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", channel=\"test-channel\")\n
","boost":10},{"location":"getting-started/subscription/test/#validates-input","title":"Validates Input","text":"

Also, your handler has a mock object to validate your input or call counts.

KafkaRabbitMQNATSRedis
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestKafkaBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, topic=\"test-topic\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRabbitBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, queue=\"test-queue\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestNatsBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, subject=\"test-subject\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRedisBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, channel=\"test-channel\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n

Note

The Handler mock has a not-serialized JSON message body. This way you can validate the incoming message view, not python arguments.

Thus our example checks not mock.assert_called_with(name=\"John\", user_id=1), but mock.assert_called_with({ \"name\": \"John\", \"user_id\": 1 }).

You should be careful with this feature: all mock objects will be cleared when the context manager exits.

KafkaRabbitMQNATSRedis
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestKafkaBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, topic=\"test-topic\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRabbitBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, queue=\"test-queue\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestNatsBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, subject=\"test-subject\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRedisBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, channel=\"test-channel\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n
","boost":10},{"location":"getting-started/subscription/test/#real-broker-testing","title":"Real Broker Testing","text":"

If you want to test your application in a real environment, you shouldn't have to rewrite all your tests: just pass with_real optional parameter to your TestClient context manager. This way, TestClient supports all the testing features but uses an unpatched broker to send and consume messages.

KafkaRabbitMQNATSRedis
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.kafka import TestKafkaBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestKafkaBroker(broker, with_real=True) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, topic=\"test-topic\")\n        await handle.wait_call(timeout=3)\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n\n@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestKafkaBroker(broker, with_real=True) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", topic=\"test-topic\")\n            await handle.wait_call(timeout=3)\n\n        handle.mock.assert_called_once_with(\"wrong message\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.rabbit import TestRabbitBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRabbitBroker(broker, with_real=True) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, queue=\"test-queue\")\n        await handle.wait_call(timeout=3)\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n\n@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestRabbitBroker(broker, with_real=True) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", queue=\"test-queue\")\n            await handle.wait_call(timeout=3)\n\n        handle.mock.assert_called_once_with(\"wrong message\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.nats import TestNatsBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestNatsBroker(broker, with_real=True) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, subject=\"test-subject\")\n        await handle.wait_call(timeout=3)\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n\n@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestNatsBroker(broker, with_real=True) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", subject=\"test-subject\")\n            await handle.wait_call(timeout=3)\n\n        handle.mock.assert_called_once_with(\"wrong message\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.redis import TestRedisBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRedisBroker(broker, with_real=True) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, channel=\"test-channel\")\n        await handle.wait_call(timeout=3)\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n\n@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestRedisBroker(broker, with_real=True) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", channel=\"test-channel\")\n            await handle.wait_call(timeout=3)\n\n        handle.mock.assert_called_once_with(\"wrong message\")\n

Tip

When you're using a patched broker to test your consumers, the publish method is called synchronously with a consumer one, so you need not wait until your message is consumed. But in the real broker's case, it doesn't.

For this reason, you have to wait for message consumption manually with the special handler.wait_call(timeout) method. Also, inner handler exceptions will be raised in this function, not broker.publish(...).

","boost":10},{"location":"getting-started/subscription/test/#a-little-tip","title":"A Little Tip","text":"

It can be very helpful to set the with_real flag using an environment variable. This way, you will be able to choose the testing mode right from the command line:

WITH_REAL=True/False pytest ...\n

To learn more about managing your application configiruation visit this page.

","boost":10},{"location":"getting-started/template/","title":"Using Cookiecutter FastStream Template","text":"

Cookiecutter FastStream is a versatile repository that provides a solid foundation for your Python projects. It comes with a basic application, testing infrastructure, linting scripts, and various development tools to kickstart your development process. Whether you're building a new application from scratch or want to enhance an existing one, this template will save you time and help you maintain high code quality.

","boost":5},{"location":"getting-started/template/#features","title":"Features","text":"","boost":5},{"location":"getting-started/template/#getting-started","title":"Getting Started","text":"

To set up your development environment, follow these steps:

  1. Install the cookiecutter package using the following command:

    pip install cookiecutter\n

  2. Run the provided cookiecutter command and fill out the relevant details to generate a new FastStream project:

    cookiecutter https://github.com/airtai/cookiecutter-faststream.git\n
    The following screenshot illustrates the process of creating a new FastStream app with Kafka using the above command:

  3. Change the working directory to the newly created directory:

    cd <directory-name>\n

    NOTE: Replace <directory-name> with the name of your directory.

  4. Install all development requirements using pip:

    pip install -e \".[dev]\"\n

  5. Create a new repository for our FastStream app on GitHub.

  6. Add all the files, commit and push using the following commands:

    git init\ngit add .\ngit commit -m \"first commit\"\ngit branch -M main\ngit remote add origin git@github.com:<username>/<repo-name>.git\ngit push -u origin main\n

    NOTE: Replace <username> with your GitHub username and <repo-name> with the name of your repository in the above commands.

","boost":5},{"location":"getting-started/template/#development","title":"Development","text":"

The application code is located in the app/ directory. You can add new features or fix bugs in this directory. However, remember that code changes must be accompanied by corresponding updates to the tests located in the tests/ directory.

","boost":5},{"location":"getting-started/template/#running-tests","title":"Running Tests","text":"

Once you have updated tests, you can execute the tests using pytest:

pytest\n
","boost":5},{"location":"getting-started/template/#running-faststream-application-locally","title":"Running FastStream Application Locally","text":"

To run the FastStream application locally, follow these steps:

  1. Start the Kafka Docker container locally using the provided script:

    ./scripts/start_kafka_broker_locally.sh\n

  2. Start the FastStream application with the following command:

    faststream run <directory-name>.application:app --workers 1\n

    NOTE: Replace <directory-name> with the directory that is automatically generated from the project slug name and contains the app.py file.

  3. You can now send messages to the Kafka topic and can test the application. Optionally, if you want to view messages in a topic, you can subscribe to it using the provided script:

    ./scripts/subscribe_to_kafka_broker_locally.sh <topic_name>\n

  4. To stop the FastStream application, press Ctrl+C.

  5. Finally, stop the Kafka Docker container by running the script:

    ./scripts/stop_kafka_broker_locally.sh\n

","boost":5},{"location":"getting-started/template/#building-and-testing-docker-image-locally","title":"Building and Testing Docker Image Locally","text":"

If you'd like to build and test the Docker image locally, follow these steps:

  1. Run the provided script to build the Docker image locally. Use the following command:

    ./scripts/build_docker.sh <username> <repo-name>\n
    This script will build the Docker image locally with the same name as the one built in CI.

  2. Before starting the Docker container, ensure that a Kafka Docker container is running locally. You can start it using the provided script:

    ./scripts/start_kafka_broker_locally.sh\n

  3. Once Kafka is up and running, you can start the local Docker container using the following command:

    docker run --rm --name faststream-app --net=host ghcr.io/<username>/<repo-name>:latest\n
    --rm: This flag removes the container once it stops running, ensuring that it doesn't clutter your system with unused containers. --name faststream-app: Assigns a name to the running container, in this case, \"faststream-app\". --net=host: This flag allows the Docker container to share the host's network namespace.

  4. To stop the local Docker container, simply press Ctrl+C in your terminal.

  5. Finally, stop the Kafka Docker container by running the provided script:

    ./scripts/stop_kafka_broker_locally.sh\n

NOTE: Replace <username> with your GitHub username and <repo-name> with the name of your repository in the above commands.

","boost":5},{"location":"getting-started/template/#code-linting","title":"Code Linting","text":"

After making changes to the code, it's essential to ensure it adheres to coding standards. We provide a script to help you with code formatting and linting. Run the following script to automatically fix linting issues:

./scripts/lint.sh\n
","boost":5},{"location":"getting-started/template/#static-analysis","title":"Static Analysis","text":"

Static analysis tools mypy and bandit can help identify potential issues in your code. To run static analysis, use the following script:

./scripts/static-analysis.sh\n

If there are any static analysis errors, resolve them in your code and rerun the script until it passes successfully.

","boost":5},{"location":"getting-started/template/#viewing-asyncapi-documentation","title":"Viewing AsyncAPI Documentation","text":"

FastStream framework supports AsyncAPI documentation. To ensure that your changes are reflected in the AsyncAPI documentation, follow these steps:

  1. Run the following command to view the AsyncAPI documentation:

    faststream docs serve <directory-name>.application:app\n
    This command builds the AsyncAPI specification file, generates AsyncAPI documentation based on the specification, and serves it at localhost:8000.

    NOTE: Replace <directory-name> with the directory that is automatically generated from the project slug name and contains the app.py file.

  2. Open your web browser and navigate to http://localhost:8000 to view the AsyncAPI documentation reflecting your changes.

  3. To stop the AsyncAPI documentation server, press Ctrl+C.

","boost":5},{"location":"getting-started/template/#contributing","title":"Contributing","text":"

Once you have successfully completed all the above steps, you are ready to contribute your changes:

  1. Add and commit your changes:

    git add .\ngit commit -m \"Your commit message\"\n

  2. Push your changes to GitHub:

    git push origin your-branch\n

  3. Create a merge request on GitHub.

","boost":5},{"location":"getting-started/template/#continuous-integration-ci","title":"Continuous Integration (CI)","text":"

This repository is equipped with GitHub Actions that automate static analysis and pytest in the CI pipeline. Even if you forget to perform any of the required steps, CI will catch any issues before merging your changes.

This repository has three workflows, each triggered when code is pushed:

  1. Tests Workflow: This workflow is named \"Tests\" and consists of two jobs. The first job runs static analysis tools mypy and bandit to identify potential issues in the codebase. The second job runs tests using pytest to ensure the functionality of the application. Both jobs run simultaneously to expedite the CI process.

  2. Build Docker Image Workflow: This workflow is named \"Build Docker Image\" and has one job. In this job, a Docker image is built based on the provided Dockerfile. The built image is then pushed to the GitHub Container Registry, making it available for deployment or other purposes.

  3. Deploy FastStream AsyncAPI Docs Workflow: The final workflow is named \"Deploy FastStream AsyncAPI Docs\" and also consists of a single job. In this job, the AsyncAPI documentation is built from the specification, and the resulting documentation is deployed to GitHub Pages. This allows for easy access and sharing of the AsyncAPI documentation with the project's stakeholders.

","boost":5},{"location":"getting-started/template/#viewing-asyncapi-documentation-hosted-at-github-pages","title":"Viewing AsyncAPI Documentation Hosted at GitHub Pages","text":"

After the Deploy FastStream AsyncAPI Docs workflow in CI has been successfully completed, the AsyncAPI documentation is automatically deployed to GitHub Pages. This provides a convenient way to access and share the documentation with project stakeholders.

To view the deployed AsyncAPI documentation, open your web browser and navigate to the following URL:

https://<username>.github.io/<repo-name>/\n

NOTE: Replace <username> with your GitHub username and <repo-name> with the name of your repository.

You will be directed to the GitHub Pages site where your AsyncAPI documentation is hosted. This hosted documentation allows you to easily share your AsyncAPI specifications with others and provides a centralized location for reviewing the AsyncAPI documentation.

","boost":5},{"location":"getting-started/template/#deploying-docker-container","title":"Deploying Docker Container","text":"

Once the Build Docker Image workflow in CI has successfully completed, the built Docker image is pushed to the GitHub Container Registry. You can then deploy this image on your server by following these steps:

  1. Pull the Docker image from the GitHub Container Registry to your server using the following command:

    docker pull ghcr.io/<username>/<repo-name>:latest\n

    NOTE: Replace <username> with your GitHub username and <repo-name> with the name of your repository.

  2. After successfully pulling the image, start the Docker container using the following command:

    docker run --rm --name faststream-app --env-file /path/to/env-file ghcr.io/<username>/<repo-name>:latest\n
    --rm: This flag removes the container once it stops running, ensuring that it doesn't clutter your system with unused containers. --name faststream-app: Assigns a name to the running container, in this case, \"faststream-app\". --env-file /path/to/env-file: Specifies the path to an environment file (commonly a .env file) that contains environment variables required by your FastStream application. Storing secrets and configuration in an environment file is a secure and best practice for handling sensitive information such as Kafka host, port, and authentication details.

By following these steps, you can easily deploy your FastStream application as a Docker container on your server. Remember to customize the env-file and other environment variables as needed to suit your specific application requirements.

","boost":5},{"location":"kafka/","title":"Kafka Routing","text":"","boost":10},{"location":"kafka/#kafka-overview","title":"Kafka Overview","text":"","boost":10},{"location":"kafka/#what-is-kafka","title":"What is Kafka?","text":"

Kafka is an open-source distributed streaming platform developed by the Apache Software Foundation. It is designed to handle high-throughput, fault-tolerant, real-time data streaming. Kafka is widely used for building real-time data pipelines and streaming applications.

","boost":10},{"location":"kafka/#key-kafka-concepts","title":"Key Kafka Concepts","text":"","boost":10},{"location":"kafka/#1-publish-subscribe-model","title":"1. Publish-Subscribe Model","text":"

Kafka is built around the publish-subscribe messaging model. In this model, data is published to topics, and multiple consumers can subscribe to these topics to receive the data. This decouples the producers of data from the consumers, allowing for flexibility and scalability.

","boost":10},{"location":"kafka/#2-topics","title":"2. Topics","text":"

A topic in Kafka is a logical channel or category to which messages are published by producers and from which messages are consumed by consumers. Topics are used to organize and categorize data streams. Each topic can have multiple partitions, which enable Kafka to distribute data and provide parallelism for both producers and consumers.

","boost":10},{"location":"kafka/#kafka-topics","title":"Kafka Topics","text":"","boost":10},{"location":"kafka/#understanding-kafka-topics","title":"Understanding Kafka Topics","text":"

Topics are fundamental to Kafka and serve as the central point of data distribution. Here are some key points about topics:

","boost":10},{"location":"kafka/#faststream-kafkabroker","title":"FastStream KafkaBroker","text":"

The FastStream KafkaBroker is a key component of the FastStream framework that enables seamless integration with Apache Kafka. With the KafkaBroker, developers can easily connect to Kafka brokers, produce messages to Kafka topics, and consume messages from Kafka topics within their FastStream applications.

","boost":10},{"location":"kafka/#establishing-a-connection","title":"Establishing a Connection","text":"

To connect to Kafka using the FastStream KafkaBroker module, follow these steps:

  1. Initialize the KafkaBroker instance: Start by initializing a KafkaBroker instance with the necessary configuration, including Kafka broker address.

  2. Create your processing logic: Write a function that will consume the incoming messages in the defined format and produce a response to the defined topic

  3. Decorate your processing function: To connect your processing function to the desired Kafka topics you need to decorate it with @broker.subscriber(...) and @broker.publisher(...) decorators. Now, after you start your application, your processing function will be called whenever a new message in the subscribed topic is available and produce the function return value to the topic defined in the publisher decorator.

Here's a simplified code example demonstrating how to establish a connection to Kafka using FastStream's KafkaBroker module:

from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-topic\")\n@broker.publisher(\"out-topic\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n

This minimal example illustrates how FastStream simplifies the process of connecting to Kafka and performing basic message processing from the in_topic to the out-topic. Depending on your specific use case and requirements, you can further customize your Kafka integration with FastStream to build robust and efficient streaming applications.

For more advanced configuration options and detailed usage instructions, please refer to the FastStream Kafka documentation and the offical Kafka documentation.

","boost":10},{"location":"kafka/ack/","title":"Consuming Acknowledgements","text":"

As you may know, Kafka consumer should commit a topic offset when consuming a message.

The default behaviour, also implemented as such in the FastStream, automatically commits (acks) topic offset on message consumption. This is the at most once consuming strategy.

However, if you wish to use at least once strategy, you should commit offset AFTER the message is processed correctly. To accomplish that, set a consumer group and disable auto_commit option like this:

@broker.subscriber(\n    \"test\", group_id=\"group\", auto_commit=False\n)\nasync def base_handler(body: str):\n    ...\n

This way, upon successful return of the processing function, the message processed will be acknowledged. In the case of an exception being raised, the message will not be acknowledged.

However, there are situations where you might want to use a different acknowledgement logic.

","boost":10},{"location":"kafka/ack/#manual-acknowledgement","title":"Manual Acknowledgement","text":"

If you want to acknowledge a message manually, you can get direct access to the message object via the Context and acknowledge the message by calling the ack method:

from faststream.kafka.annotations import KafkaMessage\n\n\n@broker.subscriber(\n    \"test\", group_id=\"group\", auto_commit=False\n)\nasync def base_handler(body: str, msg: KafkaMessage):\n    await msg.ack()\n    # or\n    await msg.nack()\n

Tip

You can use the nack method to prevent offset commit and the message can be consumed by another consumer within the same group.

FastStream will see that the message was already acknowledged and will do nothing at the end of the process.

","boost":10},{"location":"kafka/ack/#interrupt-process","title":"Interrupt Process","text":"

If you wish to interrupt the processing of a message at any call stack level and acknowledge the message, you can achieve that by raising the faststream.exceptions.AckMessage.

from faststream import FastStream\nfrom faststream.exceptions import AckMessage\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    \"test-topic\", group_id=\"test-group\", auto_commit=False\n)\nasync def handle(body):\n    smth_processing(body)\n\n\ndef smth_processing(body):\n    if True:\n        raise AckMessage()\n\n\n@app.after_startup\nasync def test_publishing():\n    await broker.publish(\"Hello!\", \"test-topic\")\n

This way, FastStream interrupts the current message processing and acknowledges it immediately. Similarly, you can raise NackMessage as well to prevent the message from being committed.

Tip

If you want to disable FastStream Acknowledgement logic at all, you can use @broker.subscriber(..., no_ack=True) option. This way you should always process a message (ack/nack/terminate/etc) by yourself.

","boost":10},{"location":"kafka/message/","title":"Access to Message Information","text":"

As you may know, FastStream serializes a message body and provides you access to it through function arguments. However, there are times when you need to access additional message attributes such as offsets, headers, or other metadata.

","boost":10},{"location":"kafka/message/#message-access","title":"Message Access","text":"

You can easily access this information by referring to the message object in the Context

This object serves as a unified FastStream wrapper around the native broker library message (for example, aiokafka.ConsumerRecord in the case of Kafka). It contains most of the required information, including:

For example, if you would like to access the headers of an incoming message, you would do so like this:

from faststream.kafka import KafkaMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    msg: KafkaMessage,\n):\n    print(msg.headers)\n
","boost":10},{"location":"kafka/message/#message-fields-access","title":"Message Fields Access","text":"

In most cases, you don't need all message fields; you need to know just a part of them. You can use Context Fields access feature for this.

For example, you can get access to the headers like this:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    headers: str = Context(\"message.headers\"),\n):\n    print(headers)\n
","boost":10},{"location":"kafka/message/#headers-access","title":"Headers Access","text":"

Sure, you can get access to a raw message and get the headers dict itself, but more often you just need a single header field. So, you can easily access it using the Context:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Context(\"message.headers.user\"),\n):\n    ...\n

Using the special Header class is more convenient, as it also validates the header value using Pydantic. It works the same way as Context, but it is just a shorcut to Context with a default setup. So, you already know how to use it:

from faststream import Header\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Header(),\n):\n    ...\n
","boost":10},{"location":"kafka/security/","title":"FastStream Kafka Security","text":"

This chapter discusses the security options available in FastStream and how to use them.

","boost":10},{"location":"kafka/security/#security-objects","title":"Security Objects","text":"

FastStream allows you to enhance the security of applications by using security objects when creating brokers. These security objects encapsulate security-related configurations and mechanisms. Security objects supported in FastStream are (More are planned in the future such as SASL OAuth):

","boost":10},{"location":"kafka/security/#1-basesecurity-object","title":"1. BaseSecurity Object","text":"

Purpose: The BaseSecurity object wraps ssl.SSLContext object and is used to enable SSL/TLS encryption for secure communication between FastStream services and external components such as message brokers.

Usage:

import ssl\n\nfrom faststream.kafka import KafkaBroker\nfrom faststream.security import BaseSecurity\n\nssl_context = ssl.create_default_context()\nsecurity = BaseSecurity(ssl_context=ssl_context)\n\nbroker = KafkaBroker(\"localhost:9092\", security=security)\n
","boost":10},{"location":"kafka/security/#2-saslplaintext-object-with-ssltls","title":"2. SASLPlaintext Object with SSL/TLS","text":"

Purpose: The SASLPlaintext object is used for authentication in SASL (Simple Authentication and Security Layer) plaintext mode. It allows you to provide a username and password for authentication.

Usage:

import ssl\n\nfrom faststream.kafka import KafkaBroker\nfrom faststream.security import SASLPlaintext\n\nssl_context = ssl.create_default_context()\nsecurity = SASLPlaintext(\n    ssl_context=ssl_context,\n    username=\"admin\",\n    password=\"password\", \n)\n\nbroker = KafkaBroker(\"localhost:9092\", security=security)\n

Using any SASL authentication without SSL:

The following example will log a RuntimeWarning:

SASLPlaintext(username=\"admin\", password=\"password\")\n

If the user does not want to use SSL encryption without the waringning getting logged, they must explicitly set the use_ssl parameter to False when creating a SASL object.

SASLPlaintext(username=\"admin\", password=\"password\", use_ssl=False) \n
","boost":10},{"location":"kafka/security/#3-saslscram256512-object-with-ssltls","title":"3. SASLScram256/512 Object with SSL/TLS","text":"

Purpose: The SASLScram256 and SASLScram512 objects are used for authentication using the Salted Challenge Response Authentication Mechanism (SCRAM).

Usage:

SCRAM256SCRAM512
import ssl\n\nfrom faststream.kafka import KafkaBroker\nfrom faststream.security import SASLScram256\n\nssl_context = ssl.create_default_context()\nsecurity = SASLScram256(\n    ssl_context=ssl_context,\n    username=\"admin\",\n    password=\"password\", \n)\n\nbroker = KafkaBroker(\"localhost:9092\", security=security)\n
import ssl\n\nfrom faststream.kafka import KafkaBroker\nfrom faststream.security import SASLScram512\n\nssl_context = ssl.create_default_context()\nsecurity = SASLScram512(\n    ssl_context=ssl_context,\n    username=\"admin\",\n    password=\"password\", \n)\n\nbroker = KafkaBroker(\"localhost:9092\", security=security)\n
","boost":10},{"location":"kafka/Publisher/","title":"Publishing","text":"

The FastStream KafkaBroker supports all regular publishing use cases, and you can use them without any changes.

However, if you wish to further customize the publishing logic, you should take a closer look at specific KafkaBroker parameters.

","boost":10},{"location":"kafka/Publisher/#basic-kafka-publishing","title":"Basic Kafka Publishing","text":"

The KafkaBroker uses the unified publish method (from a producer object) to send messages.

In this case, you can use Python primitives and pydantic.BaseModel to define the content of the message you want to publish to the Kafka broker.

You can specify the topic to send by its name.

  1. Create your KafkaBroker instance

    broker = KafkaBroker(\"localhost:9092\")\n
  2. Publish a message using the publish method

    msg = Data(data=0.5)\n\nawait broker.publish(\n    model_to_json(msg),\n    \"input_data\",\n    headers={\"content-type\": \"application/json\"},\n)\n

This is the most basic way of using the KafkaBroker to publish a message.

","boost":10},{"location":"kafka/Publisher/#creating-a-publisher-object","title":"Creating a publisher object","text":"

The simplest way to use a KafkaBroker for publishing has a significant limitation: your publishers won't be documented in the AsyncAPI documentation. This might be acceptable for sending occasional one-off messages. However, if you're building a comprehensive service, it's recommended to create publisher objects. These objects can then be parsed and documented in your service's AsyncAPI documentation. Let's go ahead and create those publisher objects!

  1. Create your KafkaBroker instance

    broker = KafkaBroker(\"localhost:9092\")\n
  2. Create a publisher instance

    prepared_publisher = broker.publisher(\"input_data\")\n
  3. Publish a message using the publish method of the prepared publisher

    msg = Data(data=0.5)\n\nawait prepared_publisher.publish(\n    model_to_json(msg),\n    headers={\"content-type\": \"application/json\"},\n)\n

Now, when you wrap your broker into a FastStream object, the publisher will be exported to the AsyncAPI documentation.

","boost":10},{"location":"kafka/Publisher/#decorating-your-publishing-functions","title":"Decorating your publishing functions","text":"

To publish messages effectively in the Kafka context, consider utilizing the Publisher Decorator. This approach offers an AsyncAPI representation and is ideal for rapidly developing applications.

The Publisher Decorator creates a structured DataPipeline unit with both input and output components. The sequence in which you apply Subscriber and Publisher decorators does not affect their functionality. However, note that these decorators can only be applied to functions decorated by a Subscriber as well.

This method relies on the return type annotation of the handler function to properly interpret the function's return value before sending it. Hence, it's important to ensure accuracy in defining the return type.

Let's start by examining the entire application that utilizes the Publisher Decorator and then proceed to walk through it step by step.

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\nto_output_data = broker.publisher(\"output_data\")\n\n\n@to_output_data\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
  1. Initialize the KafkaBroker instance: Start by initializing a KafkaBroker instance with the necessary configuration, including Kafka broker address.

    broker = KafkaBroker(\"localhost:9092\")\n
  2. Prepare your publisher object to use later as a decorator:

    to_output_data = broker.publisher(\"output_data\")\n
  3. Create your processing logic: Write a function that will consume the incoming messages in the defined format and produce a response to the defined topic

    async def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
  4. Decorate your processing function: To connect your processing function to the desired Kafka topics you need to decorate it with @broker.subscriber(...) and @broker.publisher(...) decorators. Now, after you start your application, your processing function will be called whenever a new message in the subscribed topic is available and produce the function return value to the topic defined in the publisher decorator.

    @to_output_data\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
","boost":10},{"location":"kafka/Publisher/batch_publisher/","title":"Publishing in Batches","text":"","boost":10},{"location":"kafka/Publisher/batch_publisher/#general-overview","title":"General Overview","text":"

If you need to send your data in batches, the @broker.publisher(...) decorator offers a convenient way to achieve this. To enable batch production, you need to perform two crucial steps:

  1. When creating your publisher, set the batch argument to True. This configuration tells the publisher that you intend to send messages in batches.

  2. In your producer function, return a tuple containing the messages you want to send as a batch. This action triggers the producer to gather the messages and transmit them as a batch to a Kafka broker.

Let's delve into a detailed example illustrating how to produce messages in batches to the \"output_data\" topic while consuming from the \"input_data_1\" topic.

","boost":10},{"location":"kafka/Publisher/batch_publisher/#code-example","title":"Code Example","text":"

First, let's take a look at the whole app creation and then dive deep into the steps for producing in batches. Here is the application code:

from typing import Tuple\n\nfrom pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\ndecrease_and_increase = broker.publisher(\"output_data\", batch=True)\n\n\n@decrease_and_increase\n@broker.subscriber(\"input_data_1\")\nasync def on_input_data_1(msg: Data, logger: Logger) -> Tuple[Data, Data]:\n    logger.info(msg)\n    return Data(data=(msg.data * 0.5)), Data(data=(msg.data * 2.0))\n\n\n@broker.subscriber(\"input_data_2\")\nasync def on_input_data_2(msg: Data, logger: Logger) -> None:\n    logger.info(msg)\n    await decrease_and_increase.publish(\n        Data(data=(msg.data * 0.5)), Data(data=(msg.data * 2.0))\n    )\n

Below, we have highlighted key lines of code that demonstrate the steps involved in creating and using a batch publisher:

Step 1: Creation of the Publisher

decrease_and_increase = broker.publisher(\"output_data\", batch=True)\n

Step 2: Publishing an Actual Batch of Messages

You can publish a batch by directly calling the publisher with a batch of messages you want to publish, as shown here:

await decrease_and_increase.publish(\n    Data(data=(msg.data * 0.5)), Data(data=(msg.data * 2.0))\n)\n

Or you can decorate your processing function and return a batch of messages, as shown here:

@decrease_and_increase\n@broker.subscriber(\"input_data_1\")\nasync def on_input_data_1(msg: Data, logger: Logger) -> Tuple[Data, Data]:\n    logger.info(msg)\n    return Data(data=(msg.data * 0.5)), Data(data=(msg.data * 2.0))\n

The application in the example imelements both of these ways, so feel free to use whichever option fits your needs better.

Note

Also, you can publishes messages in batches right from a broker object: just call broker.publish_batch(\"msg2\", \"msg2\", topic=\"output_data\")

","boost":10},{"location":"kafka/Publisher/batch_publisher/#why-publish-in-batches","title":"Why Publish in Batches?","text":"

In the above example, we've explored how to leverage the @broker.publisher(...) decorator to efficiently publish messages in batches using FastStream and Kafka. By following the two key steps outlined in the previous sections, you can significantly enhance the performance and reliability of your Kafka-based applications.

Publishing messages in batches offers several advantages when working with Kafka:

  1. Improved Throughput: Batch publishing allows you to send multiple messages in a single transmission, reducing the overhead associated with individual message delivery. This leads to improved throughput and lower latency in your Kafka applications.

  2. Reduced Network and Broker Load: Sending messages in batches reduces the number of network calls and broker interactions. This optimization minimizes the load on the Kafka brokers and network resources, making your Kafka cluster more efficient.

  3. Atomicity: Batches ensure that a group of related messages is processed together or not at all. This atomicity can be crucial in scenarios where message processing needs to maintain data consistency and integrity.

  4. Enhanced Scalability: With batch publishing, you can efficiently scale your Kafka applications to handle high message volumes. By sending messages in larger chunks, you can make the most of Kafka's parallelism and partitioning capabilities.

","boost":10},{"location":"kafka/Publisher/using_a_key/","title":"Using a Partition Key","text":"

Partition keys are a crucial concept in Apache Kafka, enabling you to determine the appropriate partition for a message. This ensures that related messages are kept together in the same partition, which can be invaluable for maintaining order or grouping related messages for efficient processing. Additionally, Kafka utilizes partitioning to distribute load across multiple brokers and scale horizontally, while replicating data across brokers provides fault tolerance.

You can specify your partition keys when utilizing the @KafkaBroker.publisher(...) decorator in FastStream. This guide will walk you through the process of using partition keys effectively.

","boost":10},{"location":"kafka/Publisher/using_a_key/#publishing-with-a-partition-key","title":"Publishing with a Partition Key","text":"

To publish a message to a Kafka topic using a partition key, follow these steps:

","boost":10},{"location":"kafka/Publisher/using_a_key/#step-1-define-the-publisher","title":"Step 1: Define the Publisher","text":"

In your FastStream application, define the publisher using the @KafkaBroker.publisher(...) decorator. This decorator allows you to configure various aspects of message publishing, including the partition key.

to_output_data = broker.publisher(\"output_data\")\n
","boost":10},{"location":"kafka/Publisher/using_a_key/#step-2-pass-the-key","title":"Step 2: Pass the Key","text":"

When you're ready to publish a message with a specific key, simply include the key parameter in the publish function call. This key parameter is used to determine the appropriate partition for the message.

await to_output_data.publish(Data(data=msg.data + 1.0), key=b\"key\")\n
","boost":10},{"location":"kafka/Publisher/using_a_key/#example-application","title":"Example Application","text":"

Let's examine a complete application example that consumes messages from the \"input_data\" topic and publishes them with a specified key to the \"output_data\" topic. This example will illustrate how to incorporate partition keys into your Kafka-based applications:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import Context, FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\nto_output_data = broker.publisher(\"output_data\")\n\n\n@broker.subscriber(\"input_data\")\nasync def on_input_data(\n    msg: Data, logger: Logger, key: bytes = Context(\"message.raw_message.key\")\n) -> None:\n    logger.info(f\"on_input_data({msg=})\")\n    await to_output_data.publish(Data(data=msg.data + 1.0), key=b\"key\")\n

As you can see, the primary difference from standard publishing is the inclusion of the key parameter in the publish call. This key parameter is essential for controlling how Kafka partitions and processes your messages.

In summary, using partition keys in Apache Kafka is a fundamental practice for optimizing message distribution, maintaining order, and achieving efficient processing. It is a key technique for ensuring that your Kafka-based applications scale gracefully and handle large volumes of data effectively.

","boost":10},{"location":"kafka/Subscriber/","title":"Basic Subscriber","text":"

To start consuming from a Kafka topic, simply decorate your consuming function with a @broker.subscriber(...) decorator, passing a string as a topic key.

In the folowing example, we will create a simple FastStream app that will consume HelloWorld messages from a \"hello_world\" topic.

The full app code looks like this:

from pydantic import BaseModel, Field\n\nfrom faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n\n\nclass HelloWorld(BaseModel):\n    msg: str = Field(\n        ...,\n        examples=[\"Hello\"],\n        description=\"Demo hello world message\",\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"hello_world\")\nasync def on_hello_world(msg: HelloWorld, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"kafka/Subscriber/#import-faststream-and-kafkabroker","title":"Import FastStream and KafkaBroker","text":"

To use the @broker.subscriber(...) decorator, first, we need to import the base FastStream app KafkaBroker to create our broker.

from faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n
","boost":10},{"location":"kafka/Subscriber/#define-the-helloworld-message-structure","title":"Define the HelloWorld Message Structure","text":"

Next, you need to define the structure of the messages you want to consume from the topic using Pydantic. For the guide, we\u2019ll stick to something basic, but you are free to define any complex message structure you wish in your project.

class HelloWorld(BaseModel):\n    msg: str = Field(\n        ...,\n        examples=[\"Hello\"],\n        description=\"Demo hello world message\",\n    )\n
","boost":10},{"location":"kafka/Subscriber/#create-a-kafkabroker","title":"Create a KafkaBroker","text":"

Next, we will create a KafkaBroker object and wrap it into the FastStream object so that we can start our app using CLI later.

broker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n
","boost":10},{"location":"kafka/Subscriber/#create-a-function-that-will-consume-messages-from-a-kafka-hello-world-topic","title":"Create a Function that will Consume Messages from a Kafka hello-world Topic","text":"

Let\u2019s create a consumer function that will consume HelloWorld messages from \"hello_world\" topic and log them.

@broker.subscriber(\"hello_world\")\nasync def on_hello_world(msg: HelloWorld, logger: Logger):\n    logger.info(msg)\n

The function decorated with the @broker.subscriber(...) decorator will be called when a message is produced to Kafka.

The message will then be injected into the typed msg argument of the function, and its type will be used to parse the message.

In this example case, when the message is sent to a \"hello_world\" topic, it will be parsed into a HelloWorld class, and the on_hello_world function will be called with the parsed class as the msg argument value.

","boost":10},{"location":"kafka/Subscriber/batch_subscriber/","title":"Batch Subscriber","text":"

If you want to consume data in batches, the @broker.subscriber(...) decorator makes it possible. By defining your consumed msg object as a list of messages and setting the batch parameter to True, the subscriber will call your consuming function with a batch of messages consumed from a single partition. Let's walk through how to achieve this.

","boost":10},{"location":"kafka/Subscriber/batch_subscriber/#using-the-subscriber-with-batching","title":"Using the Subscriber with Batching","text":"

To consume messages in batches, follow these steps:

","boost":10},{"location":"kafka/Subscriber/batch_subscriber/#step-1-define-your-subscriber","title":"Step 1: Define Your Subscriber","text":"

In your FastStream application, define the subscriber using the @broker.subscriber(...) decorator. Ensure that you configure the msg object as a list and set the batch parameter to True. This configuration tells the subscriber to handle message consumption in batches.

@broker.subscriber(\"test_batch\", batch=True)\n
","boost":10},{"location":"kafka/Subscriber/batch_subscriber/#step-2-implement-your-consuming-function","title":"Step 2: Implement Your Consuming Function","text":"

Create a consuming function that accepts the list of messages. The @broker.subscriber(...) decorator will take care of collecting and grouping messages into batches based on the partition.

@broker.subscriber(\"test_batch\", batch=True)\nasync def handle_batch(msg: List[HelloWorld], logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"kafka/Subscriber/batch_subscriber/#example-of-consuming-in-batches","title":"Example of Consuming in Batches","text":"

Let's illustrate how to consume messages in batches from the \"test_batch\" topic with a practical example:

from typing import List\n\nfrom pydantic import BaseModel, Field\n\nfrom faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\nclass HelloWorld(BaseModel):\n    msg: str = Field(\n        ...,\n        examples=[\"Hello\"],\n        description=\"Demo hello world message\",\n    )\n\n\n@broker.subscriber(\"test_batch\", batch=True)\nasync def handle_batch(msg: List[HelloWorld], logger: Logger):\n    logger.info(msg)\n

In this example, the subscriber is configured to process messages in batches, and the consuming function is designed to handle these batches efficiently.

Consuming messages in batches is a valuable technique when you need to optimize the processing of high volumes of data in your Kafka-based applications. It allows for more efficient resource utilization and can enhance the overall performance of your data pipelines.

","boost":10},{"location":"nats/","title":"NATS","text":"

FastStream NATS support is implemented on top of nats-py. You can always get access to objects of it if you need to use some low-level methods not represented in FastStream.

","boost":10},{"location":"nats/#advantages-and-disadvantages","title":"Advantages and Disadvantages","text":"

NATS is an easy-to-use, high-performance message broker written in Golang. If your application does not require complex routing logic, can cope with high loads, scales, and does not require large hardware costs, NATS will be an excellent choice for you.

Also NATS has a zero-cost new entities creation (to be honest, all subjects are just routing fields), so it can be used as a RPC over MQ tool.

Note

More information about NATS can be found on the official website.

However, NATS has disadvantages that you should be aware of:

","boost":10},{"location":"nats/#nats-jetstream","title":"NATS JetStream","text":"

These shortcomings are corrected by using the persistent level - JetStream. If you need strict guarantees for the delivery and processing of messages at the small detriment of speed and resources consumed, you can use NatsJS.

Also, NatsJS supports some high-level features like Key-Value and Object storages (with subscription to changes on it) and provides you with rich abilities to build your logic on top of it.

","boost":10},{"location":"nats/#routing-rules","title":"Routing Rules","text":"

NATS does not have the ability to configure complex routing rules. The only entity in NATS is subject, which can be subscribed to either directly by name or by a regular expression pattern.

Both examples are discussed a little further.

In order to support the ability to scale consumers horizontally, NATS supports the queue group functionality: a message sent to subject will be processed by a random consumer from the queue group subscribed to this subject. This approach allows you to increase the processing speed of subject by N times when starting N consumers with one group.

","boost":10},{"location":"nats/message/","title":"Access to Message Information","text":"

As you know, FastStream serializes a message body and provides you access to it through function arguments. But sometimes you need to access message_id, headers, or other meta-information.

","boost":10},{"location":"nats/message/#message-access","title":"Message Access","text":"

You can get it in a simple way: just acces the message object in the Context.

It contains the required information such as:

It is a FastStream wrapper around a native broker library message (nats.aio.msg.Msg in the NATS' case) that you can access with raw_message.

from faststream.nats import NatsMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    msg: NatsMessage,\n):\n    print(msg.correlation_id)\n

Also, if you can't find the information you require, you can get access directly to the wrapped nats.aio.msg.Msg, which contains complete message information.

from nats.aio.msg import Msg\nfrom faststream.nats import NatsMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(body: str, msg: NatsMessage):\n    raw: Msg = msg.raw_message\n    print(raw)\n
","boost":10},{"location":"nats/message/#message-fields-access","title":"Message Fields Access","text":"

But in most cases, you don't need all message fields; you need to access some of them. You can use Context Fields access feature for this reason.

For example, you can access the correlation_id like this:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: str = Context(\"message.correlation_id\"),\n):\n    print(cor_id)\n

Or even directly from the raw message:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: str = Context(\"message.raw_message.correlation_id\"),\n):\n    print(cor_id)\n

But this code is too long to reuse everywhere. In this case, you can use a Python Annotated feature:

python 3.9+python 3.6+
from types import Annotated\nfrom faststream import Context\n\nCorrelationId = Annotated[str, Context(\"message.correlation_id\")]\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: CorrelationId,\n):\n    print(cor_id)\n
from typing_extensions import Annotated\nfrom faststream import Context\n\nCorrelationId = Annotated[str, Context(\"message.correlation_id\")]\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: CorrelationId,\n):\n    print(cor_id)\n
","boost":10},{"location":"nats/message/#headers-access","title":"Headers Access","text":"

Sure, you can get access to a raw message and get the headers dict itself, but more often you just need a single header field. So, you can easily access it using the Context:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Context(\"message.headers.user\"),\n):\n    ...\n

Using the special Header class is more convenient, as it also validates the header value using Pydantic. It works the same way as Context, but it is just a shorcut to Context with a default setup. So, you already know how to use it:

from faststream import Header\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Header(),\n):\n    ...\n
","boost":10},{"location":"nats/message/#subject-pattern-access","title":"Subject Pattern Access","text":"

As you know, NATS allows you to use a pattern like this \"logs.*\" to subscriber to subjects. Getting access to the real * value is an often-used scenario, and FastStream provide it to you with the Path object (which is a shortcut to Context(\"message.path.*\")).

To use it, you just need to replace your * with {variable-name} and use Path as a regular Context object:

from faststream import Path\n\n@broker.subscriber(\"logs.{level}\")\nasync def base_handler(\n    body: str,\n    level: str = Path(),\n):\n    ...\n
","boost":10},{"location":"nats/rpc/","title":"RPC over NATS","text":"

Because NATS has zero cost for creating new subjects, we can easily set up a new subject consumer just for the one response message. This way, your request message will be published to one topic, and the response message will be consumed from another one (temporary subject), which allows you to use regular FastStream RPC syntax in the NATS case too.

Tip

FastStream RPC over NATS works in both the NATS-Core and NATS-JS cases as well, but in the NATS-JS case, you have to specify the expected stream as a publish argument.

","boost":10},{"location":"nats/rpc/#blocking-request","title":"Blocking Request","text":"

FastStream provides you with the ability to send a blocking RPC request over NATS in a very simple way.

Just send a message like a regular one and get a response synchronously.

It is very close to the common requests syntax:

msg = await broker.publish(\n    \"Hi!\",\n    subject=\"test\",\n    rpc=True,\n)\n

Also, you have two extra options to control this behavior:

","boost":10},{"location":"nats/rpc/#reply-to","title":"Reply-To","text":"

Also, if you want to create a permanent request-reply data flow, probably, you should create a permanent subject to consume responses.

So, if you have such one, you can specify it with the reply_to argument. This way, FastStream will send a response to this subject automatically.

@broker.subscriber(\"response-subject\")\nasync def consume_responses(msg):\n    ...\n\nmsg = await broker.publish(\n    \"Hi!\",\n    subject=\"test\",\n    reply_to=\"response-subject\",\n)\n
","boost":10},{"location":"nats/examples/direct/","title":"Direct","text":"

The Direct Subject is the basic way to route messages in NATS. Its essence is very simple: a subject sends messages to all consumers subscribed to it.

","boost":10},{"location":"nats/examples/direct/#scaling","title":"Scaling","text":"

If one subject is being listened to by several consumers with the same queue group, the message will go to a random consumer each time.

Thus, NATS can independently balance the load on queue consumers. You can increase the processing speed of the message flow from the queue by simply launching additional instances of the consumer service. You don't need to make changes to the current infrastructure configuration: NATS will take care of how to distribute messages between your services.

","boost":10},{"location":"nats/examples/direct/#example","title":"Example","text":"

The Direct Subject is the type used in FastStream by default: you can simply declare it as follows

@broker.handler(\"test_subject\")\nasync def handler():\n...\n

Full example:

from faststream import FastStream, Logger\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n@broker.subscriber(\"test-subj-1\", \"workers\")\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n@broker.subscriber(\"test-subj-1\", \"workers\")\nasync def base_handler2(logger: Logger):  \n    logger.info(\"base_handler2\")\n\n@broker.subscriber(\"test-subj-2\", \"workers\")\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(\"\", \"test-subj-1\")  # handlers: 1 or 2\n    await broker.publish(\"\", \"test-subj-1\")  # handlers: 1 or 2\n    await broker.publish(\"\", \"test-subj-2\")  # handlers: 3\n
","boost":10},{"location":"nats/examples/direct/#consumer-announcement","title":"Consumer Announcement","text":"

To begin with, we have declared several consumers for two subjects: \"test-subj-1\" and \"test-subj-2\":

@broker.subscriber(\"test-subj-1\", \"workers\")\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n@broker.subscriber(\"test-subj-1\", \"workers\")\nasync def base_handler2(logger: Logger):  \n    logger.info(\"base_handler2\")\n\n@broker.subscriber(\"test-subj-2\", \"workers\")\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n

Note

Note that all consumers are subscribed using the same queue_group. Within the same service, this does not make sense, since messages will come to these handlers in turn. Here, we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"nats/examples/direct/#message-distribution","title":"Message Distribution","text":"

Now the distribution of messages between these consumers will look like this:

await broker.publish(\"\", \"test-subj-1\")  # handlers: 1 or 2\n

The message 1 will be sent to handler1 or handler2 because they are listening to one \"test-subj-1\" subject within one queue group.

await broker.publish(\"\", \"test-subj-1\")  # handlers: 1 or 2\n

Message 2 will be sent similarly to message 1.

await broker.publish(\"\", \"test-subj-2\")  # handlers: 3\n

The message 3 will be sent to handler3 because it is the only one listening to \"test-subj-2\".

","boost":10},{"location":"nats/examples/pattern/","title":"Pattern","text":"

Pattern Subject is a powerful NATS routing engine. This type of subject routes messages to consumers based on the pattern specified when they connect to the subject and a message key.

","boost":10},{"location":"nats/examples/pattern/#scaling","title":"Scaling","text":"

If one subject is being listened to by several consumers with the same queue group, the message will go to a random consumer each time.

Thus, NATS can independently balance the load on queue consumers. You can increase the processing speed of the message flow from the queue by simply launching additional instances of the consumer service. You don't need to make changes to the current infrastructure configuration: NATS will take care of how to distribute messages between your services.

","boost":10},{"location":"nats/examples/pattern/#example","title":"Example","text":"
from faststream import FastStream, Logger\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n@broker.subscriber(\"*.info\", \"workers\")\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n@broker.subscriber(\"*.info\", \"workers\")\nasync def base_handler2(logger: Logger):  \n    logger.info(\"base_handler2\")\n\n@broker.subscriber(\"*.error\", \"workers\")\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(\"\", \"logs.info\")  # handlers: 1 or 2\n    await broker.publish(\"\", \"logs.info\")  # handlers: 1 or 2\n    await broker.publish(\"\", \"logs.error\") # handlers: 3\n
","boost":10},{"location":"nats/examples/pattern/#consumer-announcement","title":"Consumer Announcement","text":"

To begin with, we have announced several consumers for two subjects: \"*.info\" and \"*.error\":

@broker.subscriber(\"*.info\", \"workers\")\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n@broker.subscriber(\"*.info\", \"workers\")\nasync def base_handler2(logger: Logger):  \n    logger.info(\"base_handler2\")\n\n@broker.subscriber(\"*.error\", \"workers\")\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n

At the same time, in the subject of our consumers, we specify the pattern that will be processed by these consumers.

Note

Note that all consumers are subscribed using the same queue_group. Within the same service, this does not make sense, since messages will come to these handlers in turn. Here, we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"nats/examples/pattern/#message-distribution","title":"Message Distribution","text":"

Now the distribution of messages between these consumers will look like this:

await broker.publish(\"\", \"logs.info\")  # handlers: 1 or 2\n

The message 1 will be sent to handler1 or handler2 because they listen to the same subject template within the same queue group.

await broker.publish(\"\", \"logs.info\")  # handlers: 1 or 2\n

Message 2 will be sent similarly to message 1.

await broker.publish(\"\", \"logs.error\") # handlers: 3\n

The message 3 will be sent to handler3 because it is the only one listening to the pattern \"*.error\".

","boost":10},{"location":"nats/jetstream/","title":"NATS JetStream","text":"

The default NATS usage is suitable for scenarios where:

If you need stricter restrictions, like:

You should use the NATS JetStream extension.

In fact, the JetStream extension is the same as NATS, with the addition of a persistent layer above the file system. Therefore, all interfaces for publishing and consuming messages are similar to regular NATS usage.

However, the JetStream layer has many possibilities for configuration, from the policy of deleting old messages to the maximum stored messages number limit. You can find out more about all JetStream features in the official documentation.

If you have worked with other message brokers, then you should know that the logic of JS is closer to Kafka than to RabbitMQ: messages, after confirmation, are not deleted from the queue but remain there until the queue is full, and it will start deleting old messages (or in accordance with other logic that you can configure yourself).

When connecting a consumer (and, especially, when reconnecting), you must determine for yourself according to what logic it will consume messages: from the subject beginning, starting with some message, starting from some time, only new ones, etc. Don't be surprised if a connection is restored, and your consumer starts to process all messages received earlier again - you haven't defined the rule.

Also, NATS JetStream has built-in key-value (similar to Redis) and object (similar to Minio) storages, which, in addition to the interface for put/get, have the ability to subscribe to events, which can be extremely useful in various scenarios.

FastStream does not provide access to this functionality directly, but it is covered by the nats-py library used. You can access the JS object from the application context:

from faststream import FastStream, Logger\nfrom faststream.nats import JStream, NatsBroker\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\nstream = JStream(name=\"stream\")\n\n@broker.subscriber(\n    \"js-subject\",\n    stream=stream,\n    deliver_policy=\"new\",\n)\nasync def handler(msg: str, logger: Logger):\n    logger.info(msg)\n\n@app.after_startup\nasync def test_send():\n    await broker.publish(\"Hi!\", \"js-subject\")\n    # publish with stream verification\n    await broker.publish(\"Hi!\", \"js-subject\", stream=\"stream\")\n

Tip

Using JStream object FastStream is trying to create/update stream with the object settings. To prevent this behavior and just get already created stream, please use JStream(..., declare=False) option.

","boost":10},{"location":"nats/jetstream/ack/","title":"Consuming Acknowledgements","text":"

As you may know, Nats employs a rather extensive Acknowledgement policy.

In most cases, FastStream automatically acknowledges (acks) messages on your behalf. When your function executes correctly, including sending all responses, a message will be acknowledged (and rejected in case of an exception).

However, there are situations where you might want to use different acknowledgement logic.

","boost":10},{"location":"nats/jetstream/ack/#retries","title":"Retries","text":"

If you prefer to use a nack instead of a reject when there's an error in message processing, you can specify the retry flag in the @broker.subscriber(...) method, which is responsible for error handling logic.

By default, this flag is set to False, indicating that if an error occurs during message processing, the message can still be retrieved from the queue:

@broker.subscriber(\"test\", retry=False) # don't handle exceptions\nasync def base_handler(body: str):\n    ...\n

If this flag is set to True, the message will be nacked and placed back in the queue each time an error occurs. In this scenario, the message can be processed by another consumer (if there are several of them) or by the same one:

@broker.subscriber(\"test\", retry=True)  # try again indefinitely\nasync def base_handler(body: str):\n    ...\n

Tip

For more complex error handling cases, you can use tenacity

","boost":10},{"location":"nats/jetstream/ack/#manual-acknowledgement","title":"Manual Acknowledgement","text":"

If you want to acknowledge a message manually, you can get access directy to the message object via the Context and call the method.

from faststream.nats.annotations import NatsMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(body: str, msg: NatsMessage):\n    await msg.ack()\n    # or\n    await msg.nack()\n    # or\n    await msg.reject()\n

FastStream will see that the message was already acknowledged and will do nothing at the end of the process.

","boost":10},{"location":"nats/jetstream/ack/#interrupt-process","title":"Interrupt Process","text":"

If you want to interrupt message processing at any call stack, you can raise faststream.exceptions.AckMessage

from faststream import FastStream\nfrom faststream.exceptions import AckMessage\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\", stream=\"test-stream\")\nasync def handle(body):\n    smth_processing(body)\n\n\ndef smth_processing(body):\n    if True:\n        raise AckMessage()\n\n\n@app.after_startup\nasync def test_publishing():\n    await broker.publish(\"Hello!\", \"test-subject\")\n

This way, FastStream interrupts the current message proccessing and acknowledges it immediately. Also, you can raise NackMessage and RejectMessage too.

Tip

If you want to disable FastStream Acknowledgement logic at all, you can use @broker.subscriber(..., no_ack=True) option. This way you should always process a message (ack/nack/terminate/etc) by yourself.

","boost":10},{"location":"nats/jetstream/key-value/","title":"Key-Value Storage","text":"","boost":10},{"location":"nats/jetstream/key-value/#overview","title":"Overview","text":"

Key-Value storage is just a high-level interface on top of NatsJS.

It is a regular JetStream, where the KV key is a subject.

Put/Update an object to KV by key - it's like publishing a new message to the corresponding subject in the stream.

Thus, the Get command returns not only the current key value but the latest one with an offset of it. Additionally, you can ask for a specific value based on its offset in the KV stream.

This interface provides you with rich abilities to use it like a regular KV storage (ignoring offset) + subscribe to KV key changes + ask for an old KV value revision. So you can use this feature in your application in a really different way. You can find some examples on the NATS developers' official YouTube channel

","boost":10},{"location":"nats/jetstream/key-value/#faststream-details","title":"FastStream Details","text":"

FastStream has no native interfaces to this NatsJS functionality (yet), but it allows you to get access into the inner JetStream object to create it manually.

First of all, you need to create a Key-Value storage object and pass it into the context:

from faststream import Context, FastStream, Logger\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import ContextRepo\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n@app.on_startup\nasync def setup_broker(context: ContextRepo):\n    await broker.connect()\n\n    kv = await broker.stream.create_key_value(bucket=\"bucket\")\n    context.set_global(\"kv\", kv)\n

Tip

We placed this code in @app.on_startup hook because @app.after_startup will be triggered AFTER your handlers start consuming messages. So, if you need to have access to any custom context objects, you should set them up in the @app.on_startup hook.

Also, we call await broker.connect() method manually to establish the connection to be able to create a storage.

Next, we are ready to use this object right in our handlers.

Let's create an annotated object to shorten context object access:

from nats.js.kv import KeyValue as KV\nfrom typing_extensions import Annotated\n\nKeyValue = Annotated[KV, Context(\"kv\")]\n

And just use it in a handler:

from faststream import Logger\n\n@broker.subscriber(\"subject\")\nasync def handler(msg: str, kv: KeyValue, logger: Logger):\n    logger.info(msg)\n    kv_data = await kv.get(\"key\")\n    assert kv_data.value == b\"Hello!\"\n

Finally, let's test our code behavior by putting something into the KV storage and sending a message:

@app.after_startup\nasync def test_send(kv: KeyValue):\n    await kv.put(\"key\", b\"Hello!\")\n    await broker.publish(\"Hi!\", \"subject\")\n
Full listing
from nats.js.kv import KeyValue as KV\nfrom typing_extensions import Annotated\n\nfrom faststream import Logger\nfrom faststream import Context, FastStream, Logger\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import ContextRepo\n\nKeyValue = Annotated[KV, Context(\"kv\")]\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\"subject\")\nasync def handler(msg: str, kv: KeyValue, logger: Logger):\n    logger.info(msg)\n    kv_data = await kv.get(\"key\")\n    assert kv_data.value == b\"Hello!\"\n\n\n@app.on_startup\nasync def setup_broker(context: ContextRepo):\n    await broker.connect()\n\n    kv = await broker.stream.create_key_value(bucket=\"bucket\")\n    context.set_global(\"kv\", kv)\n\n\n@app.after_startup\nasync def test_send(kv: KeyValue):\n    await kv.put(\"key\", b\"Hello!\")\n    await broker.publish(\"Hi!\", \"subject\")\n
","boost":10},{"location":"nats/jetstream/object/","title":"Object Storage","text":"

Object storage is almost identical to the Key-Value stroge concept, so you can reuse the guide.

","boost":10},{"location":"nats/jetstream/object/#overview","title":"Overview","text":"

Object Storage is just a high-level interface on top of NatsJS.

It is a regular JetStream, where the Object key is a subject.

The main difference between KV and Object storages is that in the Object storage, you can store files greater than 1MB (a limitation of KV). It has no limit on the maximum object size and stores it in chunks (each message is an object chunk), so you can literally stream huge objects through NATS.

","boost":10},{"location":"nats/jetstream/object/#faststream-details","title":"FastStream Details","text":"

FastStream has no native interfaces to this NatsJS functionality (yet), but it allows you to access the inner JetStream object to create in manually.

First of all, you need to create an Object storage object and pass in to the context:

from faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import ContextRepo\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n@app.on_startup\nasync def setup_broker(context: ContextRepo):\n    await broker.connect()\n\n    os = await broker.stream.create_object_store(\"bucket\")\n    context.set_global(\"OS\", os)\n

Tip

We placed this code in the @app.on_startup hook because @app.after_startup will be triggered AFTER your handlers start consuming messages. So, if you need to have access to any custom context objects, you should set them up in the @app.on_startup hook.

Also, we call await broker.connect() method manually to establish the connection to be able to create a storage.

Next, we are ready to use this object right in the our handlers.

Let's create an Annotated object to shorten Context object access:

from nats.js.object_store import ObjectStore as OS\nfrom typing_extensions import Annotated\n\nObjectStorage = Annotated[OS, Context(\"OS\")]\n

And just use it in a handler:

from io import BytesIO\n\nfrom faststream import Logger\n\n@broker.subscriber(\"subject\")\nasync def handler(msg: str, os: ObjectStorage, logger: Logger):\n    logger.info(msg)\n    obj = await os.get(\"file\")\n    assert obj.data == b\"File mock\"\n

Finally, let's test our code behavior by putting something into the Object storage and sending a message:

@app.after_startup\nasync def test_send(os: ObjectStorage):\n    await os.put(\"file\", BytesIO(b\"File mock\"))\n    await broker.publish(\"Hi!\", \"subject\")\n

Tip

BytesIO - is a Readable object used to emulate a file opened for reading.

Full listing
from io import BytesIO\n\nfrom nats.js.object_store import ObjectStore as OS\nfrom typing_extensions import Annotated\n\nfrom faststream import Logger\nfrom faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import ContextRepo\n\nObjectStorage = Annotated[OS, Context(\"OS\")]\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\"subject\")\nasync def handler(msg: str, os: ObjectStorage, logger: Logger):\n    logger.info(msg)\n    obj = await os.get(\"file\")\n    assert obj.data == b\"File mock\"\n\n\n@app.on_startup\nasync def setup_broker(context: ContextRepo):\n    await broker.connect()\n\n    os = await broker.stream.create_object_store(\"bucket\")\n    context.set_global(\"OS\", os)\n\n\n@app.after_startup\nasync def test_send(os: ObjectStorage):\n    await os.put(\"file\", BytesIO(b\"File mock\"))\n    await broker.publish(\"Hi!\", \"subject\")\n
","boost":10},{"location":"nats/jetstream/pull/","title":"Pull Subscriber","text":"","boost":10},{"location":"nats/jetstream/pull/#overview","title":"Overview","text":"

NATS JetStream supports two various way to consume messages: Push and Pull consumers.

The Push consumer is used by default to consume messages with the FastStream. It means that the NATS server delivers messages to your consumer as far as possible by itself. However, it also means that NATS should control all current consumer connections and increase server load.

Thus, the Pull consumer is the recommended way to consume JetStream messages by the NATS TEAM. Using it, you simply ask NATS for new messages at some interval. It may sound a little less convenient than automatic message delivery, but it provides several advantages, such as:

So, if you want to consume a large flow of messages without strict time limitations, the Pull consumer is the right choice for you.

","boost":10},{"location":"nats/jetstream/pull/#faststream-details","title":"FastStream Details","text":"

The Pull consumer is just a regular Stream consumer, but with the pull_sub argument, which controls consuming messages with batch size and block interval.

from faststream import FastStream, Logger\nfrom faststream.nats import NatsBroker, PullSub\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    subject=\"test\",\n    stream=\"stream\",\n    pull_sub=PullSub(batch_size=10),\n)\nasync def handle(msg, logger: Logger):\n    logger.info(msg)\n

The batch size doesn't mean that your msg argument is a list of messages, but it means that you consume up to 10 messages for one request to NATS and call your handler for each message in an asyncio.gather pool.

Tip

If you want to consume list of messages, just set the batch=True in PullSub class.

So, your subject will be processed much faster, without blocking for each message processing. However, if your subject has fewer than 10 messages, your request to NATS will be blocked for timeout (5 seconds by default) while trying to collect the required number of messages. Therefor, you should choose batch_size and timeout accurately to optimize your consumer efficiency.

","boost":10},{"location":"nats/publishing/","title":"Publishing","text":"

FastStream NatsBroker supports all regular publishing usecases. You can use them without any changes.

However, if you wish to further customize the publishing logic, you should take a deeper look at specific NatsBroker parameters.

","boost":10},{"location":"nats/publishing/#nats-publishing","title":"NATS Publishing","text":"

NatsBroker also uses the unified publish method (from a publisher object) to send messages.

import asyncio\nfrom faststream.nats import NatsBroker\n\nasync def pub():\n    async with NatsBroker() as broker:\n        await broker.publish(\n            \"Hi!\",\n            subject=\"test\",\n        )\n\nasyncio.run(pub())\n
","boost":10},{"location":"nats/publishing/#basic-arguments","title":"Basic Arguments","text":"

The publish method accepts the following arguments:

","boost":10},{"location":"nats/publishing/#message-parameters","title":"Message Parameters","text":"","boost":10},{"location":"nats/publishing/#natsjs-parameters","title":"NatsJS Parameters","text":"","boost":10},{"location":"rabbit/","title":"Rabbit Routing","text":"

FastStream RabbitMQ support is implemented on top of aio-pika. You can always get access to objects of it, if you need to use some low-level methods, not represented in FastStream.

","boost":10},{"location":"rabbit/#advantages","title":"Advantages","text":"

The advantage of RabbitMQ is the ability to configure flexible and complex message routing scenarios.

RabbitMQ covers the whole range of routing: from one queue - one consumer, to a queue retrieved from several sources, including message prioritization.

Note

For more information about RabbitMQ, please visit the official documentation

It supports the ability to successfully process messages, mark them as processed with an error, remove them from the queue (it is also impossible to re-receive processed messages, unlike Kafka), lock it for the processing duration, and monitor its current status.

Having to keep track of the current status of all messages is a cause of the RabbitMQ performance issues. With really large message volumes, RabbitMQ starts to degrade. However, if this was a \"one-time influx\", then consumers will free the queue of messages and the \"health\" of RabbitMQ will be stable.

If your scenario is not based on processing millions of messages and also requires building complex routing logic, RabbitMQ will be the right choice.

","boost":10},{"location":"rabbit/#basic-concepts","title":"Basic Concepts","text":"

If you want to totally understand how RabbitMQ works, you should visit their official website. There you will find top-level comments about the basic concepts and usage examples.

","boost":10},{"location":"rabbit/#entities","title":"Entities","text":"

RabbitMQ works with three main entities:

","boost":10},{"location":"rabbit/#routing-rules","title":"Routing Rules","text":"

The rules for delivering messages to consumers depend on the type of exchange and binding parameters. All the main options will be discussed at examples.

In general, the message path looks so:

  1. Publisher sends a message to exchange, specify its routing_key and headers according to which routing will take place.
  2. Exchange, depending on the message parameters, determines which of the subscribed bindings to send the message to.
  3. Binding delivers the message to queue or another exchange (in this case it will send it further by its own rules).
  4. Queue, after receiving a message, sends it to one of subscribed consumers (PUSH API).

Tip

By default, all queues have a binding to the default exchange (Direct type) with a routing key corresponding to their name. In FastStream, queues are connected to this exchange, and messages are sent by default unless another exchange is explicitly specified.

Connecting the queue to any other exchange will still leave it subscribed to the `default exchange'. Be careful with this.

At this stage, the message gets into your application - and you start processing it.

","boost":10},{"location":"rabbit/#message-statuses","title":"Message Statuses","text":"

RabbitMQ requires confirmation of message processing: only after that, it will be removed from the queue.

Confirmation can be either positive (Acknowledgment - ack) if the message was successfully processed or negative (Negative Acknowledgment - nack) if the message was processed with an error.

At the same time, in case of an error, the message can also be extracted from the queue (reject); otherwise, after a negative confirmation, it will be requeued for processing again.

In most cases, FastStream performs all the necessary actions by itself. However, if you want to manage the message lifecycle directly, you can access the message object itself and call the appropriate methods directly. This can be useful if you want to implement an \"at most once\" policy and you need to confirm the consuming of the message before it is actually processed.

","boost":10},{"location":"rabbit/#faststream-specific","title":"FastStream Specific","text":"

FastStream omits the ability to create bindings directly, since in most cases, you do not need to subscribe one queue to several exchanges or subscribe exchanges to each other. On the contrary, this practice leads to over-complication of the message routing scheme, which makes it difficult to maintain and further develop the entire infrastructure of services.

FastStream suggests you adhere to the scheme exchange:queue as 1:N, which will greatly simplify the scheme of interaction between your services. It is better to create an additional queue for a new exchange than to subscribe to an existing one.

However, if you want to reduce the number of entities in your RabbitMQ, and thereby optimize its performance (or you know exactly what you are doing), FastStream leaves you the option to create bindings directly. In other cases, the connection parameters are an integral part of the entities RabbitQueue and RabbitExchange in FastStream.

","boost":10},{"location":"rabbit/ack/","title":"Consuming Acknowledgements","text":"

As you may know, RabbitMQ employs a rather extensive Acknowledgement policy.

In most cases, FastStream automatically acknowledges (acks) messages on your behalf. When your function executes correctly, including sending all responses, a message will be acknowledged (and rejected in case of an exception).

However, there are situations where you might want to use a different acknowledgement logic.

","boost":10},{"location":"rabbit/ack/#retries","title":"Retries","text":"

If you prefer to use a nack instead of a reject when there's an error in message processing, you can specify the retry flag in the @broker.subscriber(...) method, which is responsible for error handling logic.

By default, this flag is set to False, indicating that if an error occurs during message processing, the message can still be retrieved from the queue:

@broker.subscriber(\"test\", retry=False) # don't handle exceptions\nasync def base_handler(body: str):\n    ...\n

If this flag is set to True, the message will be nacked and placed back in the queue each time an error occurs. In this scenario, the message can be processed by another consumer (if there are several of them) or by the same one:

@broker.subscriber(\"test\", retry=True)  # try again indefinitely\nasync def base_handler(body: str):\n    ...\n

If the retry flag is set to an int, the message will be placed back in the queue, and the number of retries will be limited to this number:

@broker.subscriber(\"test\", retry=3)     # make up to 3 attempts\nasync def base_handler(body: str):\n    ...\n

Bug

At the moment, attempts are counted only by the current consumer. If the message goes to another consumer, it will have its own counter. Subsequently, this logic will be reworked.

Tip

For more complex error handling cases, you can use tenacity

","boost":10},{"location":"rabbit/ack/#manual-acknowledgement","title":"Manual acknowledgement","text":"

If you want to acknowledge a message manually, you can get access directy to the message object via the Context and call the method.

from faststream.rabbit.annotations import RabbitMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(body: str, msg: RabbitMessage):\n    await msg.ack()\n    # or\n    await msg.nack()\n    # or\n    await msg.reject()\n

FastStream will see that the message was already acknowledged and will do nothing at process end.

","boost":10},{"location":"rabbit/ack/#interrupt-process","title":"Interrupt Process","text":"

If you want to interrupt message processing at any call stack, you can raise faststream.exceptions.AckMessage

from faststream import FastStream\nfrom faststream.exceptions import AckMessage\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(body):\n    smth_processing(body)\n\n\ndef smth_processing(body):\n    if True:\n        raise AckMessage()\n\n\n@app.after_startup\nasync def test_publishing():\n    await broker.publish(\"Hello!\", \"test-queue\")\n

This way, FastStream interrupts the current message proccessing and acknowledges it immediately. Also, you can raise NackMessage and RejectMessage too.

Tip

If you want to disable FastStream Acknowledgement logic at all, you can use @broker.subscriber(..., no_ack=True) option. This way you should always process a message (ack/nack/terminate/etc) by yourself.

","boost":10},{"location":"rabbit/declare/","title":"RabbitMQ Queue/Exchange Declaration","text":"

FastStream declares and validates all exchanges and queues using publishers and subscribers RabbitMQ objects, but sometimes you need to declare them manually.

RabbitBroker provides a way to achieve this easily.

from faststream import FastStream\nfrom faststream.rabbit import (\n    ExchangeType,\n    RabbitBroker,\n    RabbitExchange,\n    RabbitQueue,\n)\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\n\n@app.after_startup\nasync def declare_smth():\n    await broker.declare_exchange(\n        RabbitExchange(\n            name=\"some-exchange\",\n            type=ExchangeType.FANOUT,\n        )\n    )\n\n    await broker.declare_queue(\n        RabbitQueue(\n            name=\"some-queue\",\n            durable=True,\n        )\n    )\n

These methods require just one argument (RabbitQueue/RabbitExchange) containing information about your RabbitMQ required objects. They declare/validate RabbitMQ objects and return low-level aio-pika robust objects to interact with.

Tip

Also, these methods are idempotent, so you can call them with the same arguments multiple times, but the objects will be created once; next time the method will return an already stored object. This way you can get access to any queue/exchange created automatically.

","boost":10},{"location":"rabbit/message/","title":"Access to Message Information","text":"

As you know, FastStream serializes a message body and provides you access to it through function arguments. But sometimes you need access to a message_id, headers, or other meta-information.

","boost":10},{"location":"rabbit/message/#message-access","title":"Message Access","text":"

You can get it in a simple way: just acces the message object in the Context.

This message contains the required information such as:

Also, it is a FastStream wrapper around a native broker library message (aio_pika.IncomingMessage in the RabbitMQ case) that you can access with raw_message.

from faststream.rabbit import RabbitMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    msg: RabbitMessage,\n):\n    print(msg.correlation_id)\n

Also, if you can't find the information you require, you can get access directly to the wrapped aio_pika.IncomingMessage, which contains complete message information.

from aio_pika import IncomingMessage\nfrom faststream.rabbit import RabbitMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(body: str, msg: RabbitMessage):\n    raw: IncomingMessage = msg.raw_message\n    print(raw)\n
","boost":10},{"location":"rabbit/message/#message-fields-access","title":"Message Fields Access","text":"

But in most cases, you don't need all message fields; you need to access some of them. You can use Context Fields access feature for this reason.

For example, you can access the correlation_id like this:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: str = Context(\"message.correlation_id\"),\n):\n    print(cor_id)\n

Or even directly from the raw message:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: str = Context(\"message.raw_message.correlation_id\"),\n):\n    print(cor_id)\n

But this code is too long to be reused everywhere. In this case, you can use a Python Annotated feature:

python 3.9+python 3.6+
from types import Annotated\nfrom faststream import Context\n\nCorrelationId = Annotated[str, Context(\"message.correlation_id\")]\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: CorrelationId,\n):\n    print(cor_id)\n
from typing_extensions import Annotated\nfrom faststream import Context\n\nCorrelationId = Annotated[str, Context(\"message.correlation_id\")]\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: CorrelationId,\n):\n    print(cor_id)\n
","boost":10},{"location":"rabbit/message/#headers-access","title":"Headers Access","text":"

Sure, you can get access to a raw message and get the headers dict itself, but more often you just need a single header field. So, you can easily access it using the Context:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Context(\"message.headers.user\"),\n):\n    ...\n

Using the special Header class is more convenient, as it also validates the header value using Pydantic. It works the same way as Context, but it is just a shorcut to Context with a default setup. So, you already know how to use it:

from faststream import Header\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Header(),\n):\n    ...\n
","boost":10},{"location":"rabbit/message/#topic-pattern-access","title":"Topic Pattern Access","text":"

As you know, Rabbit allows you to use a pattern like this \"logs.*\" with a Topic exchange. Getting access to the real * value is an often-used scenario and FastStream provide it to you with the Path object (which is a shortcut to Context(\"message.path.*\")).

To use it, you just need to replace your * with {variable-name} and use Path as a regular Context object:

from faststream import Path\nfrom faststream import RabbitQueue, RabbitExchane, ExchangeType\n\n@broker.subscriber(\n    RabbitQueue(\n        \"test-queue\",\n        routing_key=\"logs.{level}\",\n    ),\n    RabbitExchange(\n        \"test-exchange\",\n        type=ExchangeType.TOPIC,\n    )\n)\nasync def base_handler(\n    body: str,\n    level: str = Path(),\n):\n    ...\n
","boost":10},{"location":"rabbit/publishing/","title":"Publishing","text":"

FastStream RabbitBroker supports all regular publishing usecases. you can use them without any changes.

However, if you wish to further customize the publishing logic further, you should take a more deep-dive look at specific RabbitBroker parameters.

","boost":10},{"location":"rabbit/publishing/#rabbit-publishing","title":"Rabbit Publishing","text":"

RabbitBroker also uses the unified publish method (from a publisher object) to send messages.

However, in this case, an object of the aio_pika.Message class (if necessary) can be used as a message (in addition to python primitives and pydantic.BaseModel).

You can specify queue (used as a routing_key) and exchange (optionally) to send by their name.

import asyncio\nfrom faststream.rabbit import RabbitBroker\n\nasync def pub():\n    async with RabbitBroker() as broker:\n        await broker.publish(\n            \"Hi!\",\n            queue=\"test\",\n            exchange=\"test\"\n        )\n\nasyncio.run(pub())\n

If you don't specify any exchange, the message will be send to the default one.

Also, you are able to use special RabbitQueue and RabbitExchange objects as queue and exchange arguments:

from faststream.rabbit import RabbitExchange, RabbitQueue\n\nawait broker.publish(\n    \"Hi!\",\n    queue=RabbitQueue(\"test\"),\n    exchange=RabbitExchange(\"test\")\n)\n

If you specify exchange that doesn't exist, RabbitBroker will create a required one and then publish a message to it.

Tip

Be accurate with it: if you have already created an Exchange with specific parameters and try to send a message by exchange name to it, the broker will try to create it. So, Exchange parameters conflict will occur.

If you are trying to send a message to a specific Exchange, sending it with a defined RabbitExchange object is the preffered way.

","boost":10},{"location":"rabbit/publishing/#basic-arguments","title":"Basic Arguments","text":"

The publish method takes the following arguments:

","boost":10},{"location":"rabbit/publishing/#message-parameters","title":"Message Parameters","text":"

You can read more about all the available flags in the RabbitMQ documentation

","boost":10},{"location":"rabbit/publishing/#send-flags","title":"Send Flags","text":"

Arguments for sending a message:

","boost":10},{"location":"rabbit/rpc/","title":"RPC over RMQ","text":"","boost":10},{"location":"rabbit/rpc/#blocking-request","title":"Blocking Request","text":"

FastStream provides you with the ability to send a blocking RPC request over RabbitMQ in a very simple way.

It uses the Direct Reply-To RabbitMQ feature, so you don't need to create any queues to consume a response.

Just send a message like a regular one and get a response synchronously.

It is very close to common requests syntax:

msg = await broker.publish(\n    \"Hi!\",\n    queue=\"test\",\n    rpc=True,\n)\n

Also, you have two extra options to control this behavior:

","boost":10},{"location":"rabbit/rpc/#reply-to","title":"Reply-To","text":"

Also, if you want to create a permanent request-reply data flow, probably, you should create a permanent queue to consume responses.

So, if you have such one, you can specify it with the reply_to argument. This way, FastStream will send a response to this queue automatically.

@broker.subscriber(\"response-queue\")\nasync def consume_responses(msg):\n    ...\n\nmsg = await broker.publish(\n    \"Hi!\",\n    queue=\"test\",\n    reply_to=\"response-queue\",\n)\n
","boost":10},{"location":"rabbit/security/","title":"FastStream RabbitMQ Security","text":"

This chapter discusses the security options available in FastStream and how to use them.

","boost":10},{"location":"rabbit/security/#security-objects","title":"Security Objects","text":"

FastStream allows you to enhance the security of applications by using security objects when creating brokers. These security objects encapsulate security-related configurations and mechanisms. Security objects supported in FastStream for RabbitMQ are:

","boost":10},{"location":"rabbit/security/#1-basesecurity-object","title":"1. BaseSecurity Object","text":"

Purpose: The BaseSecurity object wraps ssl.SSLContext object and is used to enable SSL/TLS encryption for secure communication between FastStream services and external components such as message brokers.

Usage:

import ssl\n\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.security import BaseSecurity\n\nssl_context = ssl.create_default_context()\nsecurity = BaseSecurity(ssl_context=ssl_context)\n\nbroker = RabbitBroker(security=security)\n
","boost":10},{"location":"rabbit/security/#2-saslplaintext-object-with-ssltls","title":"2. SASLPlaintext Object with SSL/TLS","text":"

Purpose: The SASLPlaintext object is used for authentication in SASL (Simple Authentication and Security Layer) plaintext mode. It allows you to provide a username and password for authentication.

Usage:

import ssl\n\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.security import SASLPlaintext\n\nssl_context = ssl.create_default_context()\nsecurity = SASLPlaintext(\n    ssl_context=ssl_context,\n    username=\"admin\",\n    password=\"password\", \n)\n\nbroker = RabbitBroker(security=security)\n
","boost":10},{"location":"rabbit/examples/","title":"Basic Subscriber","text":"

If you know nothing about RabbitMQ and how it works, you will still able to use FastStream RabbitBroker.

Just use the @broker.subscriber(...) method with a string as a routing key.

from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\"routing_key\")  # handle messages by routing key\nasync def handle(msg):\n    print(msg)\n\n\n@app.after_startup\nasync def test_publish():\n    await broker.publish(\n        \"message\",\n        \"routing_key\",  # publish message with routing key\n    )\n

This is the principle all FastStream brokers work by: you don't need to learn them in-depth if you want to just send a message.

","boost":10},{"location":"rabbit/examples/#rabbitmq-details","title":"RabbitMQ Details","text":"

If you are already familiar with RabbitMQ logic, you should also be acquainted with the inner workings of the example mentioned above.

In this case, FastStream either creates or validates a queue with a specified routing_key and binds it to the default RabbitMQ exchange.

If you want to specify a queue-exchange pair with additional arguments, FastStream provides you with the ability to do so. You can use special RabbitQueue and RabbitExchange objects to configure RabbitMQ queues, exchanges, and binding properties. For examples of using various types of exchanges, please refer to the following articles.

","boost":10},{"location":"rabbit/examples/direct/","title":"Direct Exchange","text":"

The Direct Exchange is the basic way to route messages in RabbitMQ. Its core is very simple: the exchange sends messages to those queues whose routing_key matches the routing_key of the message being sent.

Note

The Default Exchange, to which all queues in RabbitMQ are subscribed, has the Direct type by default.

","boost":10},{"location":"rabbit/examples/direct/#scaling","title":"Scaling","text":"

If several consumers are listening to the same queue, messages will be distributed to one of them (round-robin). This behavior is common for all types of exchange because it refers to the queue itself. The type of exchange affects which queues the message gets into.

Thus, RabbitMQ can independently balance the load on queue consumers. You can increase the processing speed of the message flow from the queue by launching additional instances of a consumer service. You don't need to make changes to the current infrastructure configuration: RabbitMQ will take care of how to distribute messages between your services.

","boost":10},{"location":"rabbit/examples/direct/#example","title":"Example","text":"

Tip

The Direct Exchange is the type used in FastStream by default. You can simply declare it as follows:

@broker.subscriber(\"test_queue\", \"test_exchange\")\nasync def handler():\n    ...\n

The argument auto_delete=True in this and subsequent examples is used only to clear the state of RabbitMQ after example runs.

from faststream import FastStream, Logger\nfrom faststream.rabbit import RabbitBroker, RabbitExchange, RabbitQueue\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\nexch = RabbitExchange(\"exchange\", auto_delete=True)\n\nqueue_1 = RabbitQueue(\"test-q-1\", auto_delete=True)\nqueue_2 = RabbitQueue(\"test-q-2\", auto_delete=True)\n\n\n@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 1\n    await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 2\n    await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 1\n    await broker.publish(queue=\"test-q-2\", exchange=exch)  # handlers: 3\n
","boost":10},{"location":"rabbit/examples/direct/#consumer-announcement","title":"Consumer Announcement","text":"

First, we announce our Direct exchange and several queues that will listen to it:

exch = RabbitExchange(\"exchange\", auto_delete=True)\n\nqueue_1 = RabbitQueue(\"test-q-1\", auto_delete=True)\nqueue_2 = RabbitQueue(\"test-q-2\", auto_delete=True)\n

Then we sign up several consumers using the advertised queues to the exchange we created:

@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n

Note

handler1 and handler2 are subscribed to the same exchange using the same queue: within a single service, this does not make sense, since messages will come to these handlers in turn. Here we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"rabbit/examples/direct/#message-distribution","title":"Message Distribution","text":"

Now, the distribution of messages between these consumers will look like this:

await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 1\n

Message 1 will be sent to handler1 because it listens to the \"exchange\" using a queue with the routing key \"test-q-1\".

await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 2\n

Message 2 will be sent to handler2 because it listens to the \"exchange\" using the same queue, but handler1 is busy.

await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 1\n

Message 3 will be sent to handler1 again because it is currently free.

await broker.publish(queue=\"test-q-2\", exchange=exch)  # handlers: 3\n

Message 4 will be sent to handler3 because it is the only one listening to the \"exchange\" using a queue with the routing key \"test-q-2\".

","boost":10},{"location":"rabbit/examples/fanout/","title":"Fanout Exchange","text":"

The Fanout Exchange is an even simpler, but slightly less popular way of routing in RabbitMQ. This type of exchange sends messages to all queues subscribed to it, ignoring any arguments of the message.

At the same time, if the queue listens to several consumers, messages will also be distributed among them.

","boost":10},{"location":"rabbit/examples/fanout/#example","title":"Example","text":"
from faststream import FastStream, Logger\nfrom faststream.rabbit import ExchangeType, RabbitBroker, RabbitExchange, RabbitQueue\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\nexch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.FANOUT)\n\nqueue_1 = RabbitQueue(\"test-q-1\", auto_delete=True)\nqueue_2 = RabbitQueue(\"test-q-2\", auto_delete=True)\n\n\n@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(exchange=exch)  # handlers: 1, 2, 3\n    await broker.publish(exchange=exch)  # handlers: 1, 2, 3\n    await broker.publish(exchange=exch)  # handlers: 1, 2, 3\n    await broker.publish(exchange=exch)  # handlers: 1, 2, 3\n
","boost":10},{"location":"rabbit/examples/fanout/#consumer-announcement","title":"Consumer Announcement","text":"

To begin with, we announced our Fanout exchange and several queues that will listen to it:

exch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.FANOUT)\n\nqueue_1 = RabbitQueue(\"test-q-1\", auto_delete=True)\nqueue_2 = RabbitQueue(\"test-q-2\", auto_delete=True)\n

Then we signed up several consumers using the advertised queues to the exchange we created:

@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n

Note

handler1 and handler2 are subscribed to the same exchange using the same queue: within a single service, this does not make sense, since messages will come to these handlers in turn. Here we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"rabbit/examples/fanout/#message-distribution","title":"Message Distribution","text":"

Now the all messages will be send to all subscribers due they are binded to the same FANOUT exchange:

await broker.publish(exchange=exch)  # handlers: 1, 2, 3\nawait broker.publish(exchange=exch)  # handlers: 1, 2, 3\nawait broker.publish(exchange=exch)  # handlers: 1, 2, 3\nawait broker.publish(exchange=exch)  # handlers: 1, 2, 3\n

Note

When sending messages to Fanout exchange, it makes no sense to specify the arguments queue or routing_key, because they will be ignored.

","boost":10},{"location":"rabbit/examples/headers/","title":"Header Exchange","text":"

The Header Exchange is the most complex and flexible way to route messages in RabbitMQ. This exchange type sends messages to queues according by matching the queue binding arguments with message headers.

At the same time, if several consumers are subscribed to the queue, messages will also be distributed among them.

","boost":10},{"location":"rabbit/examples/headers/#example","title":"Example","text":"
from faststream import FastStream, Logger\nfrom faststream.rabbit import ExchangeType, RabbitBroker, RabbitExchange, RabbitQueue\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\nexch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.HEADERS)\n\nqueue_1 = RabbitQueue(\n    \"test-queue-1\",\n    auto_delete=True,\n    bind_arguments={\"key\": 1},\n)\nqueue_2 = RabbitQueue(\n    \"test-queue-2\",\n    auto_delete=True,\n    bind_arguments={\"key\": 2, \"key2\": 2, \"x-match\": \"any\"},\n)\nqueue_3 = RabbitQueue(\n    \"test-queue-3\",\n    auto_delete=True,\n    bind_arguments={\"key\": 2, \"key2\": 2, \"x-match\": \"all\"},\n)\n\n\n@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n\n@broker.subscriber(queue_3, exch)\nasync def base_handler4(logger: Logger):\n    logger.info(\"base_handler4\")\n\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 1\n    await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 2\n    await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 1\n    await broker.publish(exchange=exch, headers={\"key\": 2})  # handlers: 3\n    await broker.publish(exchange=exch, headers={\"key2\": 2})  # handlers: 3\n    await broker.publish(\n        exchange=exch, headers={\"key\": 2, \"key2\": 2.0}\n    )  # handlers: 3, 4\n
","boost":10},{"location":"rabbit/examples/headers/#consumer-announcement","title":"Consumer Announcement","text":"

First, we announce our Header exchange and several queues that will listen to it:

exch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.HEADERS)\n\nqueue_1 = RabbitQueue(\n    \"test-queue-1\",\n    auto_delete=True,\n    bind_arguments={\"key\": 1},\n)\nqueue_2 = RabbitQueue(\n    \"test-queue-2\",\n    auto_delete=True,\n    bind_arguments={\"key\": 2, \"key2\": 2, \"x-match\": \"any\"},\n)\nqueue_3 = RabbitQueue(\n    \"test-queue-3\",\n    auto_delete=True,\n    bind_arguments={\"key\": 2, \"key2\": 2, \"x-match\": \"all\"},\n)\n

The x-match argument indicates whether the arguments should match the message headers in whole or in part.

Then we signed up several consumers using the advertised queues to the exchange we created:

@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n\n@broker.subscriber(queue_3, exch)\nasync def base_handler4(logger: Logger):\n    logger.info(\"base_handler4\")\n

Note

handler1 and handler2 are subscribed to the same exchange using the same queue: within a single service, this does not make sense, since messages will come to these handlers in turn. Here we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"rabbit/examples/headers/#message-distribution","title":"Message Distribution","text":"

Now the distribution of messages between these consumers will look like this:

await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 1\n

Message 1 will be sent to handler1 because it listens to a queue whose \"key\" header matches the \"key\" header of the message.

await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 2\n

Message 2 will be sent to handler2 because it listens to exchange using the same queue, but handler1 is busy.

await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 1\n

Message 3 will be sent to handler1 again because it is currently free.

await broker.publish(exchange=exch, headers={\"key\": 2})  # handlers: 3\n

Message 4 will be sent to handler3 because it listens to a queue whose \"key\" header coincided with the \"key\" header of the message.

await broker.publish(exchange=exch, headers={\"key2\": 2})  # handlers: 3\n

Message 5 will be sent to handler3 because it listens to a queue whose header \"key2\" coincided with the header \"key2\" of the message.

await broker.publish(\n    exchange=exch, headers={\"key\": 2, \"key2\": 2.0}\n)  # handlers: 3, 4\n

Message 6 will be sent to handler3 and handler4 because the message headers completely match the queue keys.

Note

When sending messages to Header exchange, it makes no sense to specify the arguments queue or routing_key, because they will be ignored

Warning

For incredibly complex routes, you can use the option to bind an exchange to another exchange. In this case, all the same rules apply as for queues subscribed to exchange. The only difference is that the signed exchange can further distribute messages according to its own rules.

So, for example, you can combine Topic and Header exchange types.

","boost":10},{"location":"rabbit/examples/stream/","title":"RabbitMQ Streams","text":"

RabbitMQ has a Streams feature, which is closely related to Kafka topics.

The main difference from regular RabbitMQ queues is that the messages are not deleted after consuming.

And FastStream supports this feature as well!

from faststream import FastStream, Logger\nfrom faststream.rabbit import RabbitBroker, RabbitQueue\n\nbroker = RabbitBroker(max_consumers=10)\napp = FastStream(broker)\n\nqueue = RabbitQueue(\n    name=\"test-stream\",\n    durable=True,\n    arguments={\n        \"x-queue-type\": \"stream\",\n    },\n)\n\n\n@broker.subscriber(\n    queue,\n    consume_args={\"x-stream-offset\": \"first\"},\n)\nasync def handle(msg, logger: Logger):\n    logger.info(msg)\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"Hi!\", queue)\n
","boost":10},{"location":"rabbit/examples/topic/","title":"Topic Exchange","text":"

The Topic Exchange is a powerful RabbitMQ routing tool. This type of exchange sends messages to the queue in accordance with the pattern specified when they are connected to exchange and the routing_key of the message itself.

At the same time, if several consumers are subscribed to the queue, messages will be distributed among them.

","boost":10},{"location":"rabbit/examples/topic/#example","title":"Example","text":"
from faststream import FastStream, Logger\nfrom faststream.rabbit import ExchangeType, RabbitBroker, RabbitExchange, RabbitQueue\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\nexch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.TOPIC)\n\nqueue_1 = RabbitQueue(\"test-queue-1\", auto_delete=True, routing_key=\"*.info\")\nqueue_2 = RabbitQueue(\"test-queue-2\", auto_delete=True, routing_key=\"*.debug\")\n\n\n@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 1\n    await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 2\n    await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 1\n    await broker.publish(routing_key=\"logs.debug\", exchange=exch)  # handlers: 3\n
","boost":10},{"location":"rabbit/examples/topic/#consumer-announcement","title":"Consumer Announcement","text":"

First, we announce our Topic exchange and several queues that will listen to it:

exch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.TOPIC)\n\nqueue_1 = RabbitQueue(\"test-queue-1\", auto_delete=True, routing_key=\"*.info\")\nqueue_2 = RabbitQueue(\"test-queue-2\", auto_delete=True, routing_key=\"*.debug\")\n

At the same time, in the routing_key of our queues, we specify the pattern of routing keys that will be processed by this queue.

Then we sign up several consumers using the advertised queues to the exchange we created:

@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n

Note

handler1 and handler2 are subscribed to the same exchange using the same queue: within a single service, this does not make sense, since messages will come to these handlers in turn. Here we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"rabbit/examples/topic/#message-distribution","title":"Message Distribution","text":"

Now the distribution of messages between these consumers will look like this:

await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 1\n

Message 1 will be sent to handler1 because it listens to \"exchange\" using a queue with the routing key \"*.info\".

await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 2\n

Message 2 will be sent to handler2 because it listens to \"exchange\" using the same queue, but handler1 is busy.

await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 1\n

Message 3 will be sent to handler1 again because it is currently free.

await broker.publish(routing_key=\"logs.debug\", exchange=exch)  # handlers: 3\n

Message 4 will be sent to handler3 because it is the only one listening to \"exchange\" using a queue with the routing key \"*.debug\".

","boost":10},{"location":"redis/","title":"Redis Broker","text":"","boost":10},{"location":"redis/#redis-overview","title":"Redis Overview","text":"","boost":10},{"location":"redis/#what-is-redis","title":"What is Redis?","text":"

Redis is an open-source, in-memory data structure store, used as a database, cache, and message broker. It supports various data structures such as strings, hashes, lists, sets, sorted sets, bitmaps, hyperloglogs, and geospatial indexes with radius queries. Redis has built-in replication, Lua scripting, LRU eviction, transactions, and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.

","boost":10},{"location":"redis/#key-redis-concepts","title":"Key Redis Concepts","text":"

Redis is not just a key-value store; it is a data structures server, supporting different kinds of values. This makes Redis flexible and suitable for a wide range of problems. It offers versatile approaches for message handling through Pub/Sub, List, and Stream structures.

","boost":10},{"location":"redis/#1-pubsub","title":"1. Pub/Sub","text":"

Redis Pub/Sub implements the Publish/Subscribe messaging paradigm where senders (publishers) are not programmed to send their messages to specific receivers (subscribers). Instead, published messages are characterized into channels, without knowledge of what (if any) subscribers there may be.

","boost":10},{"location":"redis/#2-list","title":"2. List","text":"

In contrast, Redis List capitalizes on a straightforward list data structure. Messages, pushed by producers, form a first-in, first-out (FIFO) queue. Consumers, in turn, retrieve messages from this ordered list, providing a simplified mechanism for sequential message processing.

","boost":10},{"location":"redis/#3-streams","title":"3. Streams","text":"

Redis Streams introduce a more advanced concept, embracing an append-only log-like structure. Messages, organized as entries, allow for nuanced features like consumer groups, enabling parallel processing, and acknowledgment for precise message handling. Streams excel in scenarios demanding scalability, persistence, and ordered message processing.

Ultimately, the choice between Pub/Sub, List, or Streams hinges on the specific needs of the application. Redis Pub/Sub suits real-time communication, List offers simplicity in ordered processing, while Streams cater to complex, scalable, and ordered message handling, each providing tailored solutions based on distinct use case requirements.

","boost":10},{"location":"redis/#redis-in-faststream","title":"Redis in FastStream","text":"","boost":10},{"location":"redis/#faststream-redisbroker","title":"FastStream RedisBroker","text":"

The FastStream RedisBroker is a key component of the FastStream framework that enables seamless integration with Redis. With the RedisBroker, developers can easily connect to Redis instances, publish messages to Redis channels, and subscribe to Redis channels within their FastStream applications.

","boost":10},{"location":"redis/#establishing-a-connection","title":"Establishing a Connection","text":"

To connect to Redis using the FastStream RedisBroker module, follow these steps:

  1. Initialize the RedisBroker instance: Start by initializing a RedisBroker instance with the necessary configuration, including Redis server address and port.

  2. Create your processing logic: Write a function that will consume the incoming messages from the subscribed channel and optionally publish a response to another channel.

  3. Decorate your processing function: To connect your processing function to the desired Redis channels, you need to decorate it with @broker.subscriber(...) and @broker.publisher(...) decorators. Now, after you start your application, your processing function will be called whenever a new message in the subscribed channel is available and produce the function return value to the channel defined in the publisher decorator.

Here's a simplified code example demonstrating how to establish a connection to Redis using FastStream's RedisBroker module:

from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-channel\")\n@broker.publisher(\"out-channel\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n

This minimal example illustrates how FastStream simplifies the process of connecting to Redis and performing basic message processing from the in-channel to the out-channel. Depending on your specific use case and requirements, you can further customize your Redis integration with FastStream to build efficient and responsive applications.

For more advanced configuration options and detailed usage instructions, please refer to the FastStream Redis documentation and the official Redis documentation.

","boost":10},{"location":"redis/message/","title":"Accessing Redis Message Information with FastStream","text":"

In FastStream, messages passed through a Redis broker are serialized and can be interacted with just like function parameters. However, you might occasionally need to access more than just the message content, such as metadata and other attributes.

","boost":10},{"location":"redis/message/#redis-message-access","title":"Redis Message Access","text":"

When dealing with Redis broker in FastStream, you can easily access message details by using the RedisMessage object which wraps the underlying message with additional context information. This object is specifically tailored for Redis and contains relevant message attributes:

For instance, if you need to retrieve headers from an incoming Redis message, here\u2019s how you might do it:

from faststream.redis import RedisMessage\n\n@broker.subscriber(\"test-stream\")\nasync def stream_handler(msg: str, message: RedisMessage):\n    print(message.headers)\n
","boost":10},{"location":"redis/message/#targeted-message-fields-access","title":"Targeted Message Fields Access","text":"

It's common to require only specific elements of the message rather than the entire data structure. For this purpose, FastStream allows you to access individual message fields by specifying the field you are interested in as an argument in your handler function.

For example, if you want to access the headers directly, you might do it as follows:

from faststream import Context\n\n@broker.subscriber(\"test-stream\")\nasync def stream_handler(\n    msg: str,\n    headers: AnyDict = Context(\"message.headers\"),\n):\n    print(headers)\n

The Context object lets you reference message attributes directly, making your handler functions neater and reducing the amount of boilerplate code needed.

","boost":10},{"location":"redis/rpc/","title":"Redis RPC with FastStream","text":"

FastStream RedisBroker provides the powerful capability to perform Remote Procedure Calls (RPC) using Redis. This feature enables you to send a message and await a response, effectively creating a synchronous request-response pattern over the inherently asynchronous Redis messaging system. Below is the guide to set up and utilize the Redis RPC publishing feature with FastStream.

Note

The RPC feature is implemented over Redis Pub/Sub indepenently of the original subscriber type.

","boost":10},{"location":"redis/rpc/#rpc-with-redis-overview","title":"RPC with Redis Overview","text":"

In a traditional publish/subscribe setup, the publishing party sends messages without expecting any direct response from the subscribers. However, with RPC, the publisher sends a message and waits for a response from the subscriber, which can then be used for subsequent operations or processing.

FastStream allows you to define RPC-style communication channels, lists, or streams by using the RedisBroker's publishing function with the rpc flag set to True.

","boost":10},{"location":"redis/rpc/#implementing-redis-rpc-in-faststream","title":"Implementing Redis RPC in FastStream","text":"

To implement Redis RPC with RedisBroker in FastStream, follow the steps below:

  1. Initiate your FastStream application with RedisBroker

    broker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n
  2. Define subscriber handlers for various Redis data types (e.g., channel, list, stream) that can process incoming messages and return responses.

    @broker.subscriber(channel=\"test-channel\")\nasync def handle_channel(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n\n\n@broker.subscriber(list=\"test-list\")\nasync def handle_list(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n\n\n@broker.subscriber(stream=\"test-stream\")\nasync def handle_stream(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n
  3. Send RPC messages through RedisBroker and await responses on the correct data type.

    After your application has started and the subscribers are ready to receive messages, you can publish messages with the rpc option enabled. Additionally, you can set an rpc_timeout to decide how long the publisher should wait for a response before timing out.

    @app.after_startup\nasync def t():\n    msg = \"Hi!\"\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        channel=\"test-channel\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        list=\"test-list\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        stream=\"test-stream\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n

In this example, we assert that the msg sent is the same as the response received from the subscriber, demonstrating an operational RPC pattern over three different Redis data types.

","boost":10},{"location":"redis/rpc/#full-example-of-redis-rpc-with-faststream","title":"Full Example of Redis RPC with FastStream","text":"

Combining all the code snippets above, here is the complete example of how to set up Redis RPC with FastStream RedisBroker:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(channel=\"test-channel\")\nasync def handle_channel(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n\n\n@broker.subscriber(list=\"test-list\")\nasync def handle_list(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n\n\n@broker.subscriber(stream=\"test-stream\")\nasync def handle_stream(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n\n\n@app.after_startup\nasync def t():\n    msg = \"Hi!\"\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        channel=\"test-channel\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        list=\"test-list\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        stream=\"test-stream\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n

By embracing Redis RPC with FastStream, you can build sophisticated message-based architectures that require direct feedback from message processors. This feature is particularly suitable for cases where immediate processing is necessary or calling functions across different services is essential.

","boost":10},{"location":"redis/security/","title":"FastStream Redis Security","text":"

This chapter discusses the security options available in FastStream and how to use them.

","boost":10},{"location":"redis/security/#security-objects","title":"Security Objects","text":"

FastStream allows you to enhance the security of applications by using security objects when creating brokers. These security objects encapsulate security-related configurations and mechanisms. Security objects supported in FastStream for Redis are:

","boost":10},{"location":"redis/security/#1-basesecurity-object","title":"1. BaseSecurity Object","text":"

Purpose: The BaseSecurity object wraps ssl.SSLContext object and is used to enable SSL/TLS encryption for secure communication between FastStream services and external components such as message brokers.

Usage:

import ssl\n\nfrom faststream.redis import RedisBroker\nfrom faststream.security import BaseSecurity\n\nssl_context = ssl.create_default_context()\nsecurity = BaseSecurity(ssl_context=ssl_context)\n\nbroker = RedisBroker(security=security)\n
","boost":10},{"location":"redis/security/#2-saslplaintext-object-with-ssltls","title":"2. SASLPlaintext Object with SSL/TLS","text":"

Purpose: The SASLPlaintext object is used for authentication in SASL (Simple Authentication and Security Layer) plaintext mode. It allows you to provide a username and password for authentication.

Usage:

import ssl\n\nfrom faststream.redis import RedisBroker\nfrom faststream.security import SASLPlaintext\n\nssl_context = ssl.create_default_context()\nsecurity = SASLPlaintext(\n    ssl_context=ssl_context,\n    username=\"admin\",\n    password=\"password\", \n)\n\nbroker = RedisBroker(security=security)\n
","boost":10},{"location":"redis/list/","title":"Redis Lists","text":"

Redis Lists are a simple and flexible data structure that function as ordered collections of strings. They are similar to lists in programming languages, and Redis provides commands to perform a variety of operations such as adding, retrieving, and removing elements from either end of the list.

Redis Lists are particularly useful for scenarios such as implementing queues, effectively using the list as a FIFO (First-In-First-Out) structure.

","boost":10},{"location":"redis/list/batch/","title":"Redis List Batch Subscriber","text":"

If you want to consume data in batches from a Redis list, the @broker.subscriber(...) decorator makes it possible. By defining your consumed msg object as a list of messages and setting the batch parameter to True within the ListSub object, the subscriber will call your consuming function with a batch of messages. Let's walk through how to achieve this with the FastStream library.

","boost":10},{"location":"redis/list/batch/#using-the-subscriber-with-batching","title":"Using the Subscriber with Batching","text":"

To consume messages in batches from a Redis list, follow these steps:

","boost":10},{"location":"redis/list/batch/#step-1-define-your-subscriber","title":"Step 1: Define Your Subscriber","text":"

In your FastStream application, define the subscriber using the @broker.subscriber(...) decorator. Ensure that you pass a ListSub object with the batch parameter set to True. This configuration tells the subscriber to handle message consumption in batches from the specified Redis list.

@broker.subscriber(list=ListSub(\"test-list\", batch=True))\n
","boost":10},{"location":"redis/list/batch/#step-2-implement-your-consuming-function","title":"Step 2: Implement Your Consuming Function","text":"

Create a consuming function that accepts the list of messages. The @broker.subscriber(...) decorator will take care of collecting and grouping messages into batches.

@broker.subscriber(list=ListSub(\"test-list\", batch=True))\nasync def handle(msg: list[str], logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/list/batch/#example-of-consuming-in-batches","title":"Example of Consuming in Batches","text":"

Let's illustrate how to consume messages in batches from the \"test-list\" Redis list with a practical example:

from faststream import FastStream, Logger\nfrom faststream.redis import ListSub, RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(list=ListSub(\"test-list\", batch=True))\nasync def handle(msg: list[str], logger: Logger):\n    logger.info(msg)\n

In this example, the subscriber is configured to process messages in batches from the Redis list, and the consuming function is designed to handle these batches efficiently.

Consuming messages in batches is a valuable technique when you need to optimize the processing of high volumes of data in your Redis-based applications. It allows for more efficient resource utilization and can enhance the overall performance of your data processing tasks.

","boost":10},{"location":"redis/list/batch/#batch-publishing","title":"Batch publishing","text":"

Also, Redis List is the only data structure supporting publishing in batches with FastStream. To send multiple messages in a single request, you just need to:

","boost":10},{"location":"redis/list/publishing/","title":"Redis List Publishing with FastStream","text":"

Utilizing the FastStream library, you can effectively publish data to Redis lists, which act as queues in Redis-based messaging systems.

","boost":10},{"location":"redis/list/publishing/#understanding-redis-list-publishing","title":"Understanding Redis List Publishing","text":"

Just like with Redis streams, messages can be published to Redis lists. FastStream utilizes the @broker.publisher(...) decorator, along with a list's name, to push messages onto the list.

  1. Instantiate your RedisBroker

    broker = RedisBroker(\"localhost:6379\")\n
  2. Create your FastStream application with the instantiated RedisBroker

    app = FastStream(broker)\n
  3. Define a Pydantic model for your data

    class Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n
  4. Implement a data processing function for publishing to Redis lists

    Use the @broker.publisher(list=\"...\") decorator alongside the @broker.subscriber(list=\"...\") decorator to create a function that processes incoming messages and pushes the results to an output list in Redis.

    @broker.subscriber(list=\"input-list\")\n@broker.publisher(list=\"output-list\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n

In this pattern, the function stands as a subscriber to the \"input-list\" and publishes the processed data as a new message to the \"output-list\". By using decorators, you establish a pipeline that reads messages from one Redis list, applies some logic, and then pushes outputs to another list.

","boost":10},{"location":"redis/list/publishing/#full-example-of-redis-list-publishing","title":"Full Example of Redis List Publishing","text":"

Here's an example that demonstrates Redis list publishing in action using decorators with FastStream:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = RedisBroker(\"localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(list=\"input-list\")\n@broker.publisher(list=\"output-list\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n

The provided example illustrates the ease of setting up publishing mechanisms to interact with Redis lists. In this environment, messages are dequeued from the input list, processed, and enqueued onto the output list seamlessly, empowering developers to leverage Redis lists as messaging queues.

By following these simple steps, you can perform list-based publish/subscribe operations in a Redis environment using the FastStream library, capitalizing on Redis' fast, in-memory data structure store capabilities.

","boost":10},{"location":"redis/list/subscription/","title":"Redis List Basic Subscriber","text":"

To start consuming from a Redis list, simply decorate your consuming function with the @broker.subscriber(...) decorator, passing a string as the list key.

In the following example, we will create a simple FastStream app that will consume messages from a \"test-list\" Redis list.

The full app code looks like this:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(list=\"test-list\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/list/subscription/#import-faststream-and-redisbroker","title":"Import FastStream and RedisBroker","text":"

To use the @broker.subscriber(...) decorator, first, we need to import the base FastStream app and RedisBroker to create our broker.

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n
","boost":10},{"location":"redis/list/subscription/#create-a-redisbroker","title":"Create a RedisBroker","text":"

Next, we will create a RedisBroker object and wrap it into the FastStream object so that we can start our app using CLI later.

broker = RedisBroker()\napp = FastStream(broker)\n
","boost":10},{"location":"redis/list/subscription/#create-a-function-that-will-consume-messages-from-a-redis-list","title":"Create a Function that will Consume Messages from a Redis list","text":"

Let\u2019s create a consumer function that will consume messages from \"test-list\" Redis list and log them.

@broker.subscriber(list=\"test-list\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n

The function decorated with the @broker.subscriber(...) decorator will be called when a message is pushed to the Redis list.

The message will then be injected into the typed msg argument of the function, and its type will be used to parse the message.

In this example case, when the message is pushed to a \"test-list\" list, it will be received by the handle function, and the logger will log the message content.

","boost":10},{"location":"redis/pubsub/","title":"Redis Channels","text":"

Redis Pub/Sub Channels are a feature of Redis that enables messaging between clients through a publish/subscribe (pub/sub) pattern. A Redis channel is essentially a medium through which messages are transmitted. Different clients can subscribe to these channels to listen for messages, while other clients can publish messages to these channels.

When a message is published to a Redis channel, all subscribers to that channel receive the message instantly. This makes Redis channels suitable for a variety of real-time applications such as chat rooms, notifications, live updates, and many more use cases where messages must be broadcast promptly to multiple clients.

","boost":10},{"location":"redis/pubsub/#limitations","title":"Limitations","text":"

Redis Pub/Sub Channels, while powerful for real-time communication in scenarios like chat rooms and live updates, have certain limitations when compared to Redis List and Redis Streams.

In summary, while Redis Pub/Sub excels in simplicity and real-time broadcast scenarios, Redis List and Redis Streams provide additional features such as message persistence, ordered processing, and scalability, making them better suited for certain use cases with specific requirements. The choice between these Redis features depends on the nature of the application and its messaging needs.

","boost":10},{"location":"redis/pubsub/publishing/","title":"Publishing","text":"

The FastStream RedisBroker supports all standard publishing use cases similar to the KafkaBroker, allowing you to publish messages to Redis channels with ease.

Below you will find guidance on how to utilize the RedisBroker for publishing messages, including creating publisher objects and using decorators for streamlined publishing workflows.

","boost":10},{"location":"redis/pubsub/publishing/#basic-redis-channel-publishing","title":"Basic Redis Channel Publishing","text":"

The RedisBroker allows you to publish messages directly to Redis channels. You can use Python primitives and pydantic.BaseModel to define the content of the message.

To publish a message to a Redis channel, follow these steps:

  1. Create your RedisBroker instance

    broker = RedisBroker(\"redis://localhost:6379\")\n
  2. Publish a message using the publish method

    await broker.publish(msg, \"input_data\")\n

This is the most straightforward way to use the RedisBroker to publish messages to Redis channels.

","boost":10},{"location":"redis/pubsub/publishing/#creating-a-publisher-object","title":"Creating a publisher object","text":"

For a more structured approach and to include your publishers in the AsyncAPI documentation, it's recommended to create publisher objects. Here's how to do it:

  1. Create your RedisBroker instance

    broker = RedisBroker(\"redis://localhost:6379\")\n
  2. Create a publisher instance for a specific channel

    prepared_publisher = broker.publisher(\"input_data\")\n
  3. Publish a message using the publish method of the prepared publisher

    await prepared_publisher.publish(msg)\n

When you encapsulate your broker within a FastStream object, the publisher will be documented in your service's AsyncAPI documentation.

","boost":10},{"location":"redis/pubsub/publishing/#decorating-your-publishing-functions","title":"Decorating your publishing functions","text":"

Decorators in FastStream provide a convenient way to define the data flow within your application. The RedisBroker allows you to use decorators to publish messages to Redis channels, similar to the KafkaBroker.

By decorating a function with both @broker.subscriber(...) and @broker.publisher(...), you create a DataPipeline unit that processes incoming messages and publishes the results to another channel. The order of decorators does not matter, but they must be applied to a function that has already been decorated by a @broker.subscriber(...).

The decorated function should have a return type annotation to ensure the correct interpretation of the return value before it's published.

Here's an example of using decorators with RedisBroker:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\nto_output_data = broker.publisher(\"output_data\")\n\n\n@to_output_data\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
  1. Initialize the RedisBroker instance: Start by creating a RedisBroker instance.

    broker = RedisBroker(\"redis://localhost:6379\")\n
  2. Prepare your publisher object to be used as a decorator:

    to_output_data = broker.publisher(\"output_data\")\n
  3. Create your processing logic: Implement a function that will process incoming messages and produce a response to be published to another Redis channel.

    async def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
  4. Decorate your processing function: Apply the @broker.subscriber(...) and @broker.publisher(...) decorators to your function to define the input channel and the output channel, respectively. Once your application is running, this decorated function will be triggered whenever a new message arrives on the \"input_data\" channel, and it will publish the result to the \"output_data\" channel.

    @to_output_data\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
","boost":10},{"location":"redis/pubsub/subscription/","title":"Channel Subscription","text":"","boost":10},{"location":"redis/pubsub/subscription/#basic-channel-subscription","title":"Basic Channel Subscription","text":"

Redis Pub/Sub is the default subscriber type in FastStream, so you can simply create a regular @broker.subscriber(\"channel_name\") with a channel name and it creates a subscriber using Redis Pub/Sub.

In this example, we will build a FastStream application that listens to messages from the Redis channel named \"test\".

The complete application code is presented below:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/pubsub/subscription/#import-faststream-and-redisbroker","title":"Import FastStream and RedisBroker","text":"

To utilize the @broker.subscriber(...) decorator for Redis channel subscription, you must first import FastStream and RedisBroker.

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n
","boost":10},{"location":"redis/pubsub/subscription/#create-a-redisbroker-instance","title":"Create a RedisBroker Instance","text":"

Create a RedisBroker object and pass it to the FastStream object. This setup prepares the application for launch using the FastStream CLI.

broker = RedisBroker()\napp = FastStream(broker)\n
","boost":10},{"location":"redis/pubsub/subscription/#define-the-message-handler-function","title":"Define the Message Handler Function","text":"

Construct a function that will act as the consumer of messages from the \"test\" channel and use the logger to output the message content.

@broker.subscriber(\"test\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n

When a message is published to the Redis channel \"test\", it will trigger the invocation of the decorated function. The message will be passed to the function's msg parameter, while the logger will be available for logging purposes.

","boost":10},{"location":"redis/pubsub/subscription/#pattern-channel-subscription","title":"Pattern Channel Subscription","text":"

For subscribing to multiple Redis channels matching a pattern, use the @broker.subscriber(channel=PubSub(\"pattern\", pattern=True)) decorator, where the channel argument receives a PubSub object with the pattern and pattern flag set to True.

Here's how to create a FastStream application that subscribes to all channels matching the \"test.*\" pattern:

from faststream import FastStream, Logger\nfrom faststream.redis import PubSub, RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(channel=PubSub(\"test.*\", pattern=True))\nasync def handle_test(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/pubsub/subscription/#use-pubsub-for-pattern-matching","title":"Use PubSub for Pattern Matching","text":"

Import the PubSub class from faststream.redis along with other necessary modules.

from faststream import FastStream, Logger\nfrom faststream.redis import PubSub, RedisBroker\n
","boost":10},{"location":"redis/pubsub/subscription/#specify-the-pattern-for-channel-subscription","title":"Specify the Pattern for Channel Subscription","text":"

To define the pattern subscription, create a PubSub object with the desired pattern (\"test.*\" in this case) and indicate that it's a pattern subscription by setting pattern=True.

@broker.subscriber(channel=PubSub(\"test.*\", pattern=True))\n
","boost":10},{"location":"redis/pubsub/subscription/#create-the-pattern-message-handler-function","title":"Create the Pattern Message Handler Function","text":"

Decide on a function that will act as the subscriber of messages from channels matching the specified pattern. Logging the messages is handled similarly as with basic channel subscription.

@broker.subscriber(channel=PubSub(\"test.*\", pattern=True))\nasync def handle_test(msg: str, logger: Logger):\n    logger.info(msg)\n

With pattern channel subscription, when a message is published to a channel that matches the specified pattern (\"test.*\"), our handler function will be invoked. The message is delivered to the msg argument of the function, similar to how it works in basic channel subscriptions.

","boost":10},{"location":"redis/pubsub/subscription/#pattern-data-access","title":"Pattern data access","text":"

You can also use the Redis Pub/Sub pattern feature to encode some data directly in the channel name. With FastStream you can easily access this data using the following code:

from faststream import FastStream, Logger, Path\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test.{data}\")\nasync def handle_test(\n    msg: str,\n    logger: Logger,\n    data: str = Path(),\n):\n    logger.info(f\"Channel `{data=}`, body `{msg=}`\")\n
","boost":10},{"location":"redis/streams/","title":"Redis Streams","text":"

Redis Streams are a data structure introduced in Redis 5.0 that offer a reliable and highly scalable way to handle streams of data. They are similar to logging systems like Apache Kafka, where data is stored in a log structure and can be consumed by multiple clients. Streams provide a sequence of ordered messages, and they are designed to handle a high volume of data by allowing partitioning and multiple consumers.

A Redis Stream is a collection of entries, each having an ID (which includes a timestamp) and a set of key-value pairs representing the message data. Clients can add to a stream by generating a new entry and can read from a stream to consume its messages.

Streams have unique features such as:

","boost":10},{"location":"redis/streams/ack/","title":"Stream Acknowledgement","text":"

When working with Redis streams in the FastStream library, it's important to manage message acknowledgements carefully to ensure that messages are not lost and that they have been processed as intended.

By default, when using the FastStream with a Redis stream, the library will automatically acknowledge (ack) that a message has been processed. This follows the at most once processing guarantee.

","boost":10},{"location":"redis/streams/ack/#manual-acknowledgement","title":"Manual Acknowledgement","text":"

In cases where you want explicit control over when a message is acknowledged, you can manually acknowledge a message by accessing the ack and nack methods provided:

from faststream.redis.annotations import RedisMessage, Redis\n\n# Setup broker and faststream app\n...\n\n@broker.subscriber(StreamSub(\"test-stream\", group=\"test-group\", consumer=\"1\"))\nasync def base_handler(body: dict, msg: RedisMessage, redis: Redis):\n    # Process the message\n    ...\n\n    # Manually acknowledge the message\n    await msg.ack(redis)\n    # or, if processing fails and you want to reprocess later\n    await msg.nack()\n

Using ack will mark the message as processed in the stream, while nack is useful for situations where you might need to reprocess a message due to a handling failure.

","boost":10},{"location":"redis/streams/ack/#interrupt-process","title":"Interrupt Process","text":"

If the need arises to instantly interrupt message processing at any point in the call stack and acknowledge the message, you can achieve this by raising the faststream.exceptions.AckMessage exception:

from faststream import FastStream\nfrom faststream.exceptions import AckMessage\nfrom faststream.redis import RedisBroker, StreamSub\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(stream=StreamSub(\"test-stream\", group=\"test-group\", consumer=\"1\"))\nasync def handle(body):\n    processing_logic(body)\n\n\ndef processing_logic(body):\n    if True:\n        raise AckMessage()\n\n\n@app.after_startup\nasync def test_publishing():\n    await broker.publish(\"Hello World!\", stream=\"test-stream\")\n

By raising AckMessage, FastStream will halt the current message processing routine and immediately acknowledge it. Analogously, raising NackMessage would prevent the message from being acknowledged and could lead to its subsequent reprocessing by the same or a different consumer.

Tip

If you want to disable FastStream Acknowledgement logic at all, you can use @broker.subscriber(..., no_ack=True) option. This way you should always process a message (ack/nack/terminate/etc) by yourself.

","boost":10},{"location":"redis/streams/batch/","title":"Redis Stream Batch Subscriber","text":"

If you want to consume data in batches from a Redis stream, the @broker.subscriber(...) decorator makes it possible. By defining your consumed msg object as a list of messages and setting the batch parameter to True within the StreamSub object, the subscriber will call your consuming function with a batch of messages. Let's walk through how to achieve this with the FastStream library.

","boost":10},{"location":"redis/streams/batch/#using-the-subscriber-with-batching","title":"Using the Subscriber with Batching","text":"

To consume messages in batches from a Redis stream, follow these steps:

","boost":10},{"location":"redis/streams/batch/#step-1-define-your-subscriber","title":"Step 1: Define Your Subscriber","text":"

In your FastStream application, define the subscriber using the @broker.subscriber(...) decorator. Ensure that you pass a StreamSub object with the batch parameter set to True. This configuration tells the subscriber to handle message consumption in batches from the specified Redis stream.

@broker.subscriber(stream=StreamSub(\"test-stream\", batch=True))\n
","boost":10},{"location":"redis/streams/batch/#step-2-implement-your-consuming-function","title":"Step 2: Implement Your Consuming Function","text":"

Create a consuming function that accepts the list of messages. The @broker.subscriber(...) decorator will take care of collecting and grouping messages into batches.

@broker.subscriber(stream=StreamSub(\"test-stream\", batch=True))\nasync def handle(msg: list[str], logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/streams/batch/#example-of-consuming-in-batches","title":"Example of Consuming in Batches","text":"

Let's illustrate how to consume messages in batches from the \"test-stream\" Redis stream with a practical example:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker, StreamSub\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(stream=StreamSub(\"test-stream\", batch=True))\nasync def handle(msg: list[str], logger: Logger):\n    logger.info(msg)\n

In this example, the subscriber is configured to process messages in batches from the Redis stream, and the consuming function is designed to handle these batches efficiently.

Consuming messages in batches is a valuable technique when you need to optimize the processing of high volumes of data in your Redis-based applications. It allows for more efficient resource utilization and can enhance the overall performance of your data processing tasks.

","boost":10},{"location":"redis/streams/groups/","title":"Redis Stream Consumer Groups","text":"

Consuming messages from a Redis stream can be accomplished by using a Consumer Group. This allows multiple consumers to divide the workload of processing messages in a stream and provides a form of message acknowledgment, ensuring that messages are not processed repeatedly.

Consumer Groups in Redis enable a group of clients to cooperatively consume different portions of the same stream of messages. When using group=\"...\" (which internally uses XREADGROUP), messages are distributed among different consumers in a group and are not delivered to any other consumer in that group again, unless they are not acknowledged (i.e., the client fails to process and does not call msg.ack() or XACK). This is in contrast to a normal consumer (also known as XREAD), where every consumer sees all the messages. XREAD is useful for broadcasting to multiple consumers, while XREADGROUP is better suited for workload distribution.

In the following example, we will create a simple FastStream app that utilizes a Redis stream with a Consumer Group. It will consume messages sent to the \"test-stream\" as part of the \"test-group\" consumer group.

The full app code is as follows:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker, StreamSub\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(stream=StreamSub(\"test-stream\", group=\"test-group\", consumer=\"1\"))\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n\n\n@app.after_startup\nasync def t():\n    await broker.publish(\"Hi!\", stream=\"test-stream\")\n
","boost":10},{"location":"redis/streams/groups/#import-faststream-and-redisbroker","title":"Import FastStream and RedisBroker","text":"

First, import the FastStream class and the RedisBroker from the faststream.redis module to define our broker.

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker, StreamSub\n
","boost":10},{"location":"redis/streams/groups/#create-a-redisbroker","title":"Create a RedisBroker","text":"

To establish a connection to Redis, instantiate a RedisBroker object and pass it to the FastStream app.

broker = RedisBroker()\napp = FastStream(broker)\n
","boost":10},{"location":"redis/streams/groups/#define-a-consumer-group-subscription","title":"Define a Consumer Group Subscription","text":"

Define a subscription to a Redis stream with a specific Consumer Group using the StreamSub object and the @broker.subscriber(...) decorator. Then, define a function that will be triggered when new messages are sent to the \"test-stream\" Redis stream. This function is decorated with @broker.subscriber(...) and will process the messages as part of the \"test-group\" consumer group.

@broker.subscriber(stream=StreamSub(\"test-stream\", group=\"test-group\", consumer=\"1\"))\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/streams/groups/#publishing-a-message","title":"Publishing a message","text":"

Publishing a message is the same as what's defined on Stream Publishing.

await broker.publish(\"Hi!\", stream=\"test-stream\")\n

By following the steps and code examples provided above, you can create a FastStream application that consumes messages from a Redis stream using a Consumer Group for distributed message processing.

","boost":10},{"location":"redis/streams/publishing/","title":"Redis Stream Publishing with FastStream","text":"","boost":10},{"location":"redis/streams/publishing/#publishing-data-to-redis-stream","title":"Publishing Data to Redis Stream","text":"

To publish messages to a Redis Stream, you implement a function that processes the incoming data and applies the @broker.publisher(...) decorator along with the Redis stream name to it. The function will then publish its return value to the specified stream.

  1. Create your RedisBroker instance

    broker = RedisBroker(\"redis://localhost:6379\")\n
  2. Initiate your FastStream application with the RedisBroker

    app = FastStream(broker)\n
  3. Define your data model

    class Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n
  4. Set up the function for data processing and publishing

    Using the @broker.publisher(...) decorator in conjunction with the @broker.subscriber(...) decorator allows seamless message processing and republishing to a different stream.

    @broker.subscriber(stream=\"input-stream\")\n@broker.publisher(stream=\"output-stream\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n

    By decorating a function with @broker.publisher(...), we tell FastStream to publish the function's returned data to the designated \"output stream\". The defined function also serves as a subscriber to the \"input-stream\", thereby setting up a straightforward data pipeline within Redis streams.

Here's the complete example that showcases the use of decorators for both subscribing and publishing to Redis streams:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(stream=\"input-stream\")\n@broker.publisher(stream=\"output-stream\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
","boost":10},{"location":"redis/streams/subscription/","title":"Redis Stream Basic Subscriber","text":"

To start consuming from a Redis stream, simply decorate your consuming function with the @broker.subscriber(...) decorator, passing a string as the stream key.

In the following example, we will create a simple FastStream app that will consume messages from a \"test-stream\" Redis stream.

The full app code looks like this:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(stream=\"test-stream\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/streams/subscription/#import-faststream-and-redisbroker","title":"Import FastStream and RedisBroker","text":"

To use the @broker.subscriber(...) decorator, first, we need to import the base FastStream app and RedisBroker to create our broker.

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n
","boost":10},{"location":"redis/streams/subscription/#create-a-redisbroker","title":"Create a RedisBroker","text":"

Next, we will create a RedisBroker object and wrap it into the FastStream object so that we can start our app using CLI later.

broker = RedisBroker()\napp = FastStream(broker)\n
","boost":10},{"location":"redis/streams/subscription/#create-a-function-that-will-consume-messages-from-a-redis-stream","title":"Create a Function that will Consume Messages from a Redis stream","text":"

Let\u2019s create a consumer function that will consume messages from \"test-stream\" Redis stream and log them.

@broker.subscriber(stream=\"test-stream\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n

The function decorated with the @broker.subscriber(...) decorator will be called when a message is produced to the Redis stream.

The message will then be injected into the typed msg argument of the function, and its type will be used to parse the message.

In this example case, when the message is sent to a \"test-stream\" stream, it will be received by the handle function, and the logger will log the message content.

","boost":10}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-,:!=\\[\\]()\"`/]+|\\.(?!\\d)|&[lg]t;|(?!\\b)(?=[A-Z][a-z])","pipeline":["stopWordFilter"]},"docs":[{"location":"release/","title":"Release Notes","text":"","boost":2},{"location":"release/#039","title":"0.3.9","text":"","boost":2},{"location":"release/#whats-changed","title":"What's Changed","text":"","boost":2},{"location":"release/#bug-fixes","title":"Bug fixes:","text":"","boost":2},{"location":"release/#chore","title":"Chore:","text":"

Full Changelog: #0.3.8...0.3.9

","boost":2},{"location":"release/#038","title":"0.3.8","text":"","boost":2},{"location":"release/#whats-changed_1","title":"What's Changed","text":"

Full Changelog: #0.3.7...0.3.8

","boost":2},{"location":"release/#037","title":"0.3.7","text":"","boost":2},{"location":"release/#whats-changed_2","title":"What's Changed","text":"

Support regular FastStream Context with FastAPI plugin

from fastapi import FastAPI\nfrom faststream.redis.fastapi import RedisRouter, Logger\n\nrouter = RedisRouter()\n\n@router.subscriber(\"test\")\nasync def handler(msg, logger: Logger):\n    logger.info(msg)\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n

Full Changelog: #0.3.6...0.3.7

","boost":2},{"location":"release/#036","title":"0.3.6","text":"","boost":2},{"location":"release/#whats-changed_3","title":"What's Changed","text":"

Full Changelog: #0.3.5...0.3.6

","boost":2},{"location":"release/#035","title":"0.3.5","text":"","boost":2},{"location":"release/#whats-changed_4","title":"What's Changed","text":"

A large update by @Lancetnik in #1048

Provides with the ability to setup graceful_timeout to wait for consumed messages processed correctly before apllication shutdown - Broker(graceful_timeout=30.0) (waits up to 30 seconds)

Full Changelog: #0.3.4...0.3.5

","boost":2},{"location":"release/#034","title":"0.3.4","text":"","boost":2},{"location":"release/#whats-changed_5","title":"What's Changed","text":"","boost":2},{"location":"release/#features","title":"Features:","text":"","boost":2},{"location":"release/#documentation","title":"Documentation","text":"","boost":2},{"location":"release/#chore_1","title":"Chore","text":"

Full Changelog: #0.3.3...0.3.4

","boost":2},{"location":"release/#033","title":"0.3.3","text":"","boost":2},{"location":"release/#whats-changed_6","title":"What's Changed","text":"

Features:

Chores:

Full Changelog: #0.3.2...0.3.3

","boost":2},{"location":"release/#032","title":"0.3.2","text":"","boost":2},{"location":"release/#whats-changed_7","title":"What's Changed","text":"","boost":2},{"location":"release/#new-features","title":"New features:","text":"","boost":2},{"location":"release/#chore_2","title":"Chore:","text":"

Full Changelog: #0.3.1...0.3.2

","boost":2},{"location":"release/#031","title":"0.3.1","text":"","boost":2},{"location":"release/#whats-changed_8","title":"What's Changed","text":"

Features:

Bug fixes:

Documentation:

","boost":2},{"location":"release/#new-contributors","title":"New Contributors","text":"

Full Changelog: #0.3.0...0.3.1

","boost":2},{"location":"release/#030","title":"0.3.0","text":"","boost":2},{"location":"release/#whats-changed_9","title":"What's Changed","text":"

The main feature of the 0.3.0 release is added Redis support by @Lancetnik in #1003

You can install it by the following command:

pip install \"faststream[redis]\"\n

Here is a little code example

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n@broker.subscriber(\n    channel=\"test\",  # or\n    # list=\"test\",     or\n    # stream=\"test\",\n)\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":2},{"location":"release/#other-features","title":"Other features","text":"","boost":2},{"location":"release/#testing","title":"Testing","text":"","boost":2},{"location":"release/#documentation_1","title":"Documentation","text":"","boost":2},{"location":"release/#chore_3","title":"Chore","text":"","boost":2},{"location":"release/#new-contributors_1","title":"New Contributors","text":"

Full Changelog: #0.2.15...0.3.0

","boost":2},{"location":"release/#030rc0","title":"0.3.0rc0","text":"","boost":2},{"location":"release/#whats-changed_10","title":"What's Changed","text":"

The main feature of the 0.3.x release is added Redis support by @Lancetnik in #1003

You can install it manually:

pip install faststream==0.3.0rc0 && pip install \"faststream[redis]\"\n
","boost":2},{"location":"release/#other-features_1","title":"Other features","text":"","boost":2},{"location":"release/#testing_1","title":"Testing","text":"","boost":2},{"location":"release/#documentation_2","title":"Documentation","text":"","boost":2},{"location":"release/#chore_4","title":"Chore","text":"","boost":2},{"location":"release/#new-contributors_2","title":"New Contributors","text":"

Full Changelog: #0.2.15...0.3.0rc0

","boost":2},{"location":"release/#0215","title":"0.2.15","text":"","boost":2},{"location":"release/#whats-changed_11","title":"What's Changed","text":"","boost":2},{"location":"release/#bug-fixes_1","title":"Bug fixes","text":"","boost":2},{"location":"release/#documentation_3","title":"Documentation","text":"","boost":2},{"location":"release/#misc","title":"Misc","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.14...0.2.15

","boost":2},{"location":"release/#0214","title":"0.2.14","text":"","boost":2},{"location":"release/#whats-changed_12","title":"What's Changed","text":"","boost":2},{"location":"release/#bug-fixes_2","title":"Bug fixes","text":"","boost":2},{"location":"release/#documentation_4","title":"Documentation","text":"","boost":2},{"location":"release/#misc_1","title":"Misc","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.13...0.2.14

","boost":2},{"location":"release/#0213","title":"0.2.13","text":"","boost":2},{"location":"release/#whats-changed_13","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.12...0.2.13

","boost":2},{"location":"release/#0212","title":"0.2.12","text":"","boost":2},{"location":"release/#whats-changed_14","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.11...0.2.12

","boost":2},{"location":"release/#0211","title":"0.2.11","text":"","boost":2},{"location":"release/#whats-changed_15","title":"What's Changed","text":"","boost":2},{"location":"release/#bug-fixes_3","title":"Bug fixes","text":"","boost":2},{"location":"release/#documentation_5","title":"Documentation","text":"","boost":2},{"location":"release/#new-contributors_3","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.10...0.2.11

","boost":2},{"location":"release/#documentation_6","title":"Documentation","text":"","boost":2},{"location":"release/#new-contributors_4","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.10...0.2.11

","boost":2},{"location":"release/#0210","title":"0.2.10","text":"","boost":2},{"location":"release/#whats-changed_16","title":"What's Changed","text":"

Now, you can hide your connection secrets in the AsyncAPI schema by manually setting up the server URL:

broker = RabbitBroker(\n    \"amqp://guest:guest@localhost:5672/\",  # Connection URL\n    asyncapi_url=\"amqp://****:****@localhost:5672/\",  # Public schema URL\n)\n

Additionally, the RabbitMQ AsyncAPI schema has been improved, adding support for faststream.security, and the connection scheme is now defined automatically.

RabbitMQ connection parameters are now merged, allowing you to define the main connection data as a URL string and customize it using kwargs:

broker = RabbitBroker(\n    \"amqp://guest:guest@localhost:5672/\",\n    host=\"127.0.0.1\",\n)\n\n# amqp://guest:guest@127.0.0.1:5672/ - The final URL\n
* A more suitable faststream.security import instead of faststream.broker.security * chore: add release notes for 0.2.9 by @kumaranvpl in https://github.com/airtai/faststream/pull/894 * chore: upgrade packages by @davorrunje in https://github.com/airtai/faststream/pull/901 * chore: use js redirect and redirect to version by @kumaranvpl in https://github.com/airtai/faststream/pull/902 * feat: add asyncapi_url broker arg by @Lancetnik in https://github.com/airtai/faststream/pull/903

Full Changelog: https://github.com/airtai/faststream/compare/0.2.9...0.2.10

","boost":2},{"location":"release/#029","title":"0.2.9","text":"","boost":2},{"location":"release/#whats-changed_17","title":"What's Changed","text":"","boost":2},{"location":"release/#new-contributors_5","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.8...0.2.9

","boost":2},{"location":"release/#028","title":"0.2.8","text":"","boost":2},{"location":"release/#whats-changed_18","title":"What's Changed","text":"","boost":2},{"location":"release/#new-contributors_6","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.7...0.2.8

","boost":2},{"location":"release/#027","title":"0.2.7","text":"","boost":2},{"location":"release/#whats-changed_19","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.6...0.2.7

","boost":2},{"location":"release/#026","title":"0.2.6","text":"","boost":2},{"location":"release/#whats-changed_20","title":"What's Changed","text":"","boost":2},{"location":"release/#new-contributors_7","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.5...0.2.6

","boost":2},{"location":"release/#025","title":"0.2.5","text":"","boost":2},{"location":"release/#whats-changed_21","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.4...0.2.5

","boost":2},{"location":"release/#024","title":"0.2.4","text":"","boost":2},{"location":"release/#new-functionalities","title":"New Functionalities","text":"

Now, Context provides access to inner dict keys too:

# headers is a `dict`\nasync def handler(\n  user_id: int = Context(\"message.headers.user_id\", cast=True),\n): ...\n

Added Header object as a shortcut to Context(\"message.headers.\") inner fields (NATS example):

# the same with the previous example\nasync def handler(\n  user_id: int = Header(),\n  u_id: int = Header(\"user_id\"),  # with custom name\n): ...\n

Added Path object to get access to NATS wildcard subject or RabbitMQ topic routing key (a shortcut to access Context(\"message.path.\") as well):

@nats_broker.subscriber(\"logs.{level}\")\nasync def handler(\n  level: str = Path(),\n)\n

Also, the original message Context annotation was copied from faststream.[broker].annotations.[Broker]Message to faststream.[broker].[Broker]Message to provide you with faster access to the most commonly used object (NATS example).

","boost":2},{"location":"release/#whats-changed_22","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.3...0.2.4

","boost":2},{"location":"release/#023","title":"0.2.3","text":"","boost":2},{"location":"release/#whats-changed_23","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.2...0.2.3

","boost":2},{"location":"release/#022","title":"0.2.2","text":"","boost":2},{"location":"release/#whats-changed_24","title":"What's Changed","text":"","boost":2},{"location":"release/#new-contributors_8","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.1...0.2.2

","boost":2},{"location":"release/#021","title":"0.2.1","text":"","boost":2},{"location":"release/#whats-changed_25","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.2.0...0.2.1

","boost":2},{"location":"release/#020","title":"0.2.0","text":"","boost":2},{"location":"release/#whats-changed_26","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.1.6...0.2.0

","boost":2},{"location":"release/#016","title":"0.1.6","text":"","boost":2},{"location":"release/#whats-changed_27","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.1.5...0.1.6

","boost":2},{"location":"release/#014","title":"0.1.4","text":"","boost":2},{"location":"release/#whats-changed_28","title":"What's Changed","text":"","boost":2},{"location":"release/#new-contributors_9","title":"New Contributors","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.1.3...0.1.4

","boost":2},{"location":"release/#013","title":"0.1.3","text":"","boost":2},{"location":"release/#whats-changed_29","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/compare/0.1.1...0.1.3

","boost":2},{"location":"release/#011","title":"0.1.1","text":"","boost":2},{"location":"release/#whats-changed_30","title":"What's Changed","text":"

Full Changelog: https://github.com/airtai/faststream/commits/0.1.1

","boost":2},{"location":"release/#010","title":"0.1.0","text":"

FastStream is a new package based on the ideas and experiences gained from FastKafka and Propan. By joining our forces, we picked up the best from both packages and created the unified way to write services capable of processing streamed data regardless of the underlying protocol. We'll continue to maintain both packages, but new development will be in this project. If you are starting a new service, this package is the recommended way to do it.

","boost":2},{"location":"release/#features_1","title":"Features","text":"

FastStream simplifies the process of writing producers and consumers for message queues, handling all the parsing, networking and documentation generation automatically.

Making streaming microservices has never been easier. Designed with junior developers in mind, FastStream simplifies your work while keeping the door open for more advanced use-cases. Here's a look at the core features that make FastStream a go-to framework for modern, data-centric microservices.

That's FastStream in a nutshell\u2014easy, efficient, and powerful. Whether you're just starting with streaming microservices or looking to scale, FastStream has got you covered.

","boost":2},{"location":"scheduling/","title":"Tasks Scheduling","text":"

FastStream is a framework for asynchronous service development. It allows you to build disturbed event-based systems in an easy way. Tasks scheduling is a pretty often usecase in such systems.

Unfortunatelly, this functional conflicts with the original FastStream ideology and can't be implemented as a part of the framework. But, you can integrate scheduling in your FastStream application by using some extra dependencies. And we have some reciepts how to make it.

","boost":10},{"location":"scheduling/#taskiq-faststream","title":"Taskiq-FastStream","text":"

Taskiq is an asynchronous distributed task queue for python. This project takes inspiration from big projects such as Celery and Dramatiq.

As a Celery replacement, Taskiq should support tasks sheduling and delayied publishing, of course. And it does!

By the way, you can easely integrate FastStream with the Taskiq. It allows you to create cron or delayied tasks to publish messages and trigger some functions this way.

We have a helpful project to provide you with this feature - Taskiq-FastStream.

You can install it by the following command

pip install taskiq-faststream\n

It has two hepfull classes BrokerWrapper and AppWrapper to make your FastStream App and Broker objects taskiq-compatible.

Let's take a look at the code example.

At first, we should create a regular FastStream application.

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-topic\")\n@broker.publisher(\"out-topic\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-queue\")\n@broker.publisher(\"out-queue\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-subject\")\n@broker.publisher(\"out-subject\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-channel\")\n@broker.publisher(\"out-channel\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n
","boost":10},{"location":"scheduling/#broker-wrapper","title":"Broker Wrapper","text":"

Now, if you want to make it just working, we should wrap our Broker to special BrokerWrapper object:

from taskiq_faststream import BrokerWrapper\n\ntaskiq_broker = BrokerWrapper(broker)\n

It creates a taskiq-compatible object, that can be used as an object to create a regular taskiq scheduler.

KafkaRabbitMQNATSRedis
from taskiq_faststream import StreamScheduler\nfrom taskiq.schedule_sources import LabelScheduleSource\n\ntaskiq_broker.task(\n    message={\"user\": \"John\", \"user_id\": 1},\n    topic=\"in-topic\",\n    schedule=[{\n        \"cron\": \"* * * * *\",\n    }],\n)\n\nscheduler = StreamScheduler(\n    broker=taskiq_broker,\n    sources=[LabelScheduleSource(taskiq_broker)],\n)\n
from taskiq_faststream import StreamScheduler\nfrom taskiq.schedule_sources import LabelScheduleSource\n\ntaskiq_broker.task(\n    message={\"user\": \"John\", \"user_id\": 1},\n    queue=\"in-queue\",\n    schedule=[{\n        \"cron\": \"* * * * *\",\n    }],\n)\n\nscheduler = StreamScheduler(\n    broker=taskiq_broker,\n    sources=[LabelScheduleSource(taskiq_broker)],\n)\n
from taskiq_faststream import StreamScheduler\nfrom taskiq.schedule_sources import LabelScheduleSource\n\ntaskiq_broker.task(\n    message={\"user\": \"John\", \"user_id\": 1},\n    subject=\"in-subject\",\n    schedule=[{\n        \"cron\": \"* * * * *\",\n    }],\n)\n\nscheduler = StreamScheduler(\n    broker=taskiq_broker,\n    sources=[LabelScheduleSource(taskiq_broker)],\n)\n
from taskiq_faststream import StreamScheduler\nfrom taskiq.schedule_sources import LabelScheduleSource\n\ntaskiq_broker.task(\n    message={\"user\": \"John\", \"user_id\": 1},\n    channel=\"in-channel\",\n    schedule=[{\n        \"cron\": \"* * * * *\",\n    }],\n)\n\nscheduler = StreamScheduler(\n    broker=taskiq_broker,\n    sources=[LabelScheduleSource(taskiq_broker)],\n)\n

We patched the original TaskiqScheduler to support message generation callbacks, but its signature remains the same.

broker.task(...) has the same with the original broker.publish(...) signature and allows you to plan your publishing tasks usign the great taskiq schedule option (you can learn more about it here).

Finally, to run the scheduler, please use the taskiq CLI command:

taskiq scheduler module:scheduler\n
","boost":10},{"location":"scheduling/#application-wrapper","title":"Application Wrapper","text":"

If you don't wont to lost application AsyncAPI schema or/and lifespans, you can wrap not the broker, but application by itself using AppWrapper class.

from taskiq_faststream import AppWrapper\n\ntaskiq_broker = AppWrapper(app)\n

It allows you to use taskiq_broker the same way with the previous example, but saves all original FastStream features.

Tip

Creating a separated Scheduler service is a best way to make really disturbed and susteinable system. In this case, you can just create an empty FastStream broker and use Taskiq-FastStream integration to publish your messages (consuming by another services).

","boost":10},{"location":"scheduling/#generate-message-payload","title":"Generate message payload","text":"

Also, you able to determine message payload right before sending and do not use the final one. To make it, just replace message option from the final value to function (sync or async), that returns data to send:

async def collect_information_to_send():\n    return \"Message to send\"\n\ntaskiq_broker.task(\n    message=collect_information_to_send,\n    ...\n)\n

It allows you to collect some data from database, request an outer API, or use another ways to generate data to send right before sending.

More than, you can send not one, but multiple messages per one task using this feature. Just turn your message callback function to generator (sync or async) - and Taskiq-FastStream will iterates over your payload and publishes all of your messages!

async def collect_information_to_send():\n    \"\"\"Publish 10 messages per task call.\"\"\"\n    for i in range(10):\n        yield i\n\ntaskiq_broker.task(\n    message=collect_information_to_send,\n    ...\n)\n
","boost":10},{"location":"scheduling/#rocketry","title":"Rocketry","text":"

Also, you can integrate your FastStream application with any other libraries provides you with a scheduling functional.

As an example, you can use Rocketry:

import asyncio\n\nfrom rocketry import Rocketry\nfrom rocketry.args import Arg\n\nfrom faststream.nats import NatsBroker\n\napp = Rocketry(execution=\"async\")\n\nbroker = NatsBroker()      # regular broker\napp.params(broker=broker)\n\nasync def start_app():\n    async with broker:     # connect broker\n        await app.serve()  # run rocketry\n\n@app.task(\"every 1 second\", execution=\"async\")\nasync def publish(br: NatsBroker = Arg(\"broker\")):\n    await br.publish(\"Hi, Rocketry!\", \"test\")\n\nif __name__ == \"__main__\":\n    asyncio.run(start_app())\n
","boost":10},{"location":"api/","title":"Reference - Code API","text":"

Here's the reference or code API, the classes, functions, parameters, attributes, and all the FastAPI parts you can use in your applications.

If you want to learn FastStream you are much better off reading the FastStream Tutorial.

"},{"location":"api/faststream/BaseMiddleware/","title":"BaseMiddleware","text":"","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware","title":"faststream.BaseMiddleware","text":"
BaseMiddleware(msg: Any)\n

A base middleware class.

METHOD DESCRIPTION on_receive

Called when a message is received.

after_processed

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) -> Optional[bool]: Called after processing a message.

__aenter__

Called when entering a context.

__aexit__

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) -> Optional[bool]: Called when exiting a context.

on_consume

DecodedMessage) -> DecodedMessage: Called before consuming a message.

after_consume

Optional[Exception]) -> None: Called after consuming a message.

consume_scope

DecodedMessage) -> AsyncIterator[DecodedMessage]: Context manager for consuming a message.

on_publish

SendableMessage) -> SendableMessage: Called before publishing a message.

after_publish

Optional[Exception]) -> None: Asynchronous function to handle the after publish event.

Initialize the class.

PARAMETER DESCRIPTION msg

Any message to be stored.

TYPE: Any

Source code in faststream/broker/middlewares.py
def __init__(self, msg: Any) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        msg: Any message to be stored.\n    \"\"\"\n    self.msg = msg\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.msg","title":"msg instance-attribute","text":"
msg = msg\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.after_consume","title":"after_consume async","text":"
after_consume(err: Optional[Exception]) -> None\n

A function to handle the result of consuming a resource asynchronously.

PARAMETER DESCRIPTION err

Optional exception that occurred during consumption

RAISES DESCRIPTION err

If an exception occurred during consumption

Source code in faststream/broker/middlewares.py
async def after_consume(self, err: Optional[Exception]) -> None:\n    \"\"\"A function to handle the result of consuming a resource asynchronously.\n\n    Args:\n        err : Optional exception that occurred during consumption\n\n    Raises:\n        err : If an exception occurred during consumption\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.after_processed","title":"after_processed async","text":"
after_processed(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> Optional[bool]\n

Asynchronously called after processing.

PARAMETER DESCRIPTION exc_type

Optional exception type

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

Optional exception value

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

Optional traceback

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION Optional[bool]

Optional boolean value indicating whether the processing was successful or not.

Source code in faststream/broker/middlewares.py
async def after_processed(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> Optional[bool]:\n    \"\"\"Asynchronously called after processing.\n\n    Args:\n        exc_type: Optional exception type\n        exc_val: Optional exception value\n        exec_tb: Optional traceback\n\n    Returns:\n        Optional boolean value indicating whether the processing was successful or not.\n    \"\"\"\n    return False\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.after_publish","title":"after_publish async","text":"
after_publish(err: Optional[Exception]) -> None\n

Asynchronous function to handle the after publish event.

PARAMETER DESCRIPTION err

Optional exception that occurred during the publish

TYPE: Optional[Exception]

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION Exception

If an error occurred during the publish

Source code in faststream/broker/middlewares.py
async def after_publish(self, err: Optional[Exception]) -> None:\n    \"\"\"Asynchronous function to handle the after publish event.\n\n    Args:\n        err: Optional exception that occurred during the publish\n\n    Returns:\n        None\n\n    Raises:\n        Exception: If an error occurred during the publish\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.consume_scope","title":"consume_scope async","text":"
consume_scope(\n    msg: DecodedMessage,\n) -> AsyncIterator[DecodedMessage]\n

Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.

PARAMETER DESCRIPTION msg

The decoded message to consume.

TYPE: DecodedMessage

YIELDS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RETURNS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RAISES DESCRIPTION Exception

If an error occurs while consuming the message.

AsyncIterator

An asynchronous iterator that yields decoded messages.

Note

This function is an async function.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def consume_scope(self, msg: DecodedMessage) -> AsyncIterator[DecodedMessage]:\n    \"\"\"Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.\n\n    Args:\n        msg: The decoded message to consume.\n\n    Yields:\n        An asynchronous iterator of decoded messages.\n\n    Returns:\n        An asynchronous iterator of decoded messages.\n\n    Raises:\n        Exception: If an error occurs while consuming the message.\n\n    AsyncIterator:\n        An asynchronous iterator that yields decoded messages.\n\n    Note:\n        This function is an async function.\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_consume(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_consume(err)\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.on_consume","title":"on_consume async","text":"
on_consume(msg: DecodedMessage) -> DecodedMessage\n

Asynchronously consumes a message.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: DecodedMessage

RETURNS DESCRIPTION DecodedMessage

The consumed message.

Source code in faststream/broker/middlewares.py
async def on_consume(self, msg: DecodedMessage) -> DecodedMessage:\n    \"\"\"Asynchronously consumes a message.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The consumed message.\n    \"\"\"\n    return msg\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.on_publish","title":"on_publish async","text":"
on_publish(msg: SendableMessage) -> SendableMessage\n

Asynchronously handle a publish event.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

RETURNS DESCRIPTION SendableMessage

The published message.

Source code in faststream/broker/middlewares.py
async def on_publish(self, msg: SendableMessage) -> SendableMessage:\n    \"\"\"Asynchronously handle a publish event.\n\n    Args:\n        msg: The message to be published.\n\n    Returns:\n        The published message.\n    \"\"\"\n    return msg\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.on_receive","title":"on_receive async","text":"
on_receive() -> None\n
Source code in faststream/broker/middlewares.py
async def on_receive(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/BaseMiddleware/#faststream.BaseMiddleware.publish_scope","title":"publish_scope async","text":"
publish_scope(\n    msg: SendableMessage,\n) -> AsyncIterator[SendableMessage]\n

Publish a message and return an async iterator.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

YIELDS DESCRIPTION AsyncIterator[SendableMessage]

A sendable message.

RETURNS DESCRIPTION AsyncIterator[SendableMessage]

An async iterator of sendable messages.

RAISES DESCRIPTION Exception

If an error occurs during publishing.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def publish_scope(\n    self, msg: SendableMessage\n) -> AsyncIterator[SendableMessage]:\n    \"\"\"Publish a message and return an async iterator.\n\n    Args:\n        msg: The message to be published.\n\n    Yields:\n        A sendable message.\n\n    Returns:\n        An async iterator of sendable messages.\n\n    Raises:\n        Exception: If an error occurs during publishing.\n\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_publish(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_publish(err)\n
","boost":0.5},{"location":"api/faststream/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/Context/#faststream.Context","title":"faststream.Context","text":"
Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n    )\n
","boost":0.5},{"location":"api/faststream/Depends/","title":"Depends","text":"","boost":0.5},{"location":"api/faststream/Depends/#fast_depends.use.Depends","title":"fast_depends.use.Depends","text":"
Depends(\n    dependency: Callable[P, T],\n    *,\n    use_cache: bool = True,\n    cast: bool = True\n) -> Any\n
Source code in fast_depends/use.py
def Depends(\n    dependency: Callable[P, T],\n    *,\n    use_cache: bool = True,\n    cast: bool = True,\n) -> Any:\n    return model.Depends(\n        dependency=dependency,\n        use_cache=use_cache,\n        cast=cast,\n    )\n
","boost":0.5},{"location":"api/faststream/FastStream/","title":"FastStream","text":"","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream","title":"faststream.FastStream","text":"
FastStream(\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    lifespan: Optional[Lifespan] = None,\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[\n        Union[License, LicenseDict, AnyDict]\n    ] = None,\n    contact: Optional[\n        Union[Contact, ContactDict, AnyDict]\n    ] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[\n        Sequence[Union[Tag, TagDict, AnyDict]]\n    ] = None,\n    external_docs: Optional[\n        Union[ExternalDocs, ExternalDocsDict, AnyDict]\n    ] = None,\n)\n

Bases: ABCApp

A class representing a FastStream application.

METHOD DESCRIPTION __init__

initializes the FastStream application

on_startup

adds a hook to run before the broker is connected

on_shutdown

adds a hook to run before the broker is disconnected

after_startup

adds a hook to run after the broker is connected

after_shutdown

adds a hook to run after the broker is disconnected

run

runs the FastStream application

_init_async_cycle

initializes the async cycle

_start

starts the FastStream application

_stop

stops the FastStream application

_startup

runs the startup hooks

_shutdown

runs the shutdown hooks

__exit

exits the FastStream application

Asyncronous FastStream Application class

stores and run broker, control hooks

PARAMETER DESCRIPTION broker

async broker to run (may be None, then specify by set_broker)

TYPE: Optional[BrokerAsyncUsecase[Any, Any]] DEFAULT: None

logger

logger object to log startup/shutdown messages (None to disable)

TYPE: Optional[Logger] DEFAULT: logger

title

application title - for AsyncAPI docs

TYPE: str DEFAULT: 'FastStream'

version

application version - for AsyncAPI docs

TYPE: str DEFAULT: '0.1.0'

description

application description - for AsyncAPI docs

TYPE: str DEFAULT: ''

Source code in faststream/app.py
def __init__(\n    self,\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    lifespan: Optional[Lifespan] = None,\n    # AsyncAPI args,\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[Union[License, LicenseDict, AnyDict]] = None,\n    contact: Optional[Union[Contact, ContactDict, AnyDict]] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[Sequence[Union[Tag, TagDict, AnyDict]]] = None,\n    external_docs: Optional[Union[ExternalDocs, ExternalDocsDict, AnyDict]] = None,\n) -> None:\n    \"\"\"Asyncronous FastStream Application class\n\n    stores and run broker, control hooks\n\n    Args:\n        broker: async broker to run (may be `None`, then specify by `set_broker`)\n        logger: logger object to log startup/shutdown messages (`None` to disable)\n        title: application title - for AsyncAPI docs\n        version: application version - for AsyncAPI docs\n        description: application description - for AsyncAPI docs\n    \"\"\"\n    super().__init__(\n        broker=broker,\n        logger=logger,\n        title=title,\n        version=version,\n        description=description,\n        terms_of_service=terms_of_service,\n        license=license,\n        contact=contact,\n        identifier=identifier,\n        tags=tags,\n        external_docs=external_docs,\n    )\n\n    self._stop_event = None\n\n    self.lifespan_context = (\n        apply_types(\n            func=lifespan,\n            wrap_model=drop_response_type,\n        )\n        if lifespan is not None\n        else fake_context\n    )\n\n    set_exit(lambda *_: self.__exit())\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = tags\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.contact","title":"contact instance-attribute","text":"
contact = contact\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.context","title":"context instance-attribute","text":"
context = context\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.external_docs","title":"external_docs instance-attribute","text":"
external_docs = external_docs\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.identifier","title":"identifier instance-attribute","text":"
identifier = identifier\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.license","title":"license instance-attribute","text":"
license = license\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context = (\n    apply_types(\n        func=lifespan, wrap_model=drop_response_type\n    )\n    if lifespan is not None\n    else fake_context\n)\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = terms_of_service\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.title","title":"title instance-attribute","text":"
title = title\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.version","title":"version instance-attribute","text":"
version = version\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.after_shutdown","title":"after_shutdown","text":"
after_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker disconnected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def after_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker disconnected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().after_shutdown(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.after_startup","title":"after_startup","text":"
after_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker connected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def after_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker connected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().after_startup(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.on_shutdown","title":"on_shutdown","text":"
on_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker disconnected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def on_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker disconnected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().on_shutdown(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.on_startup","title":"on_startup","text":"
on_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker connected

This hook also takes an extra CLI options as a kwargs

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def on_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker connected\n\n    This hook also takes an extra CLI options as a kwargs\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().on_startup(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.run","title":"run async","text":"
run(\n    log_level: int = logging.INFO,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n) -> None\n

Run FastStream Application

PARAMETER DESCRIPTION log_level

force application log level

TYPE: int DEFAULT: INFO

RETURNS DESCRIPTION None

Block an event loop until stopped

Source code in faststream/app.py
async def run(\n    self,\n    log_level: int = logging.INFO,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Run FastStream Application\n\n    Args:\n        log_level: force application log level\n\n    Returns:\n        Block an event loop until stopped\n    \"\"\"\n    assert self.broker, \"You should setup a broker\"  # nosec B101\n\n    self._init_async_cycle()\n    async with self.lifespan_context(**(run_extra_options or {})):\n        try:\n            async with anyio.create_task_group() as tg:\n                tg.start_soon(self._start, log_level, run_extra_options)\n                await self._stop(log_level)\n                tg.cancel_scope.cancel()\n        except ExceptionGroup as e:\n            for ex in e.exceptions:\n                raise ex from None\n
","boost":0.5},{"location":"api/faststream/FastStream/#faststream.FastStream.set_broker","title":"set_broker","text":"
set_broker(broker: BrokerAsyncUsecase[Any, Any]) -> None\n

Set already existed App object broker Usefull then you create/init broker in on_startup hook

Source code in faststream/app.py
def set_broker(self, broker: BrokerAsyncUsecase[Any, Any]) -> None:\n    \"\"\"Set already existed App object broker\n    Usefull then you create/init broker in `on_startup` hook\"\"\"\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/Header/","title":"Header","text":"","boost":0.5},{"location":"api/faststream/Header/#faststream.Header","title":"faststream.Header","text":"
Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.headers.\",\n    )\n
","boost":0.5},{"location":"api/faststream/Path/","title":"Path","text":"","boost":0.5},{"location":"api/faststream/Path/#faststream.Path","title":"faststream.Path","text":"
Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.path.\",\n    )\n
","boost":0.5},{"location":"api/faststream/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/TestApp/#faststream.TestApp","title":"faststream.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/TestApp/#faststream.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/apply_types/","title":"apply_types","text":"","boost":0.5},{"location":"api/faststream/apply_types/#fast_depends.use.inject","title":"fast_depends.use.inject","text":"
inject(\n    func: Optional[Callable[P, T]] = None,\n    *,\n    cast: bool = True,\n    extra_dependencies: Sequence[model.Depends] = (),\n    pydantic_config: Optional[ConfigDict] = None,\n    dependency_overrides_provider: Optional[\n        Any\n    ] = dependency_provider,\n    wrap_model: Callable[\n        [CallModel[P, T]], CallModel[P, T]\n    ] = lambda: x\n) -> Union[Callable[P, T], _InjectWrapper[P, T]]\n
Source code in fast_depends/use.py
def inject(\n    func: Optional[Callable[P, T]] = None,\n    *,\n    cast: bool = True,\n    extra_dependencies: Sequence[model.Depends] = (),\n    pydantic_config: Optional[ConfigDict] = None,\n    dependency_overrides_provider: Optional[Any] = dependency_provider,\n    wrap_model: Callable[[CallModel[P, T]], CallModel[P, T]] = lambda x: x,\n) -> Union[Callable[P, T], _InjectWrapper[P, T],]:\n    decorator = _wrap_inject(\n        dependency_overrides_provider=dependency_overrides_provider,\n        wrap_model=wrap_model,\n        extra_dependencies=extra_dependencies,\n        cast=cast,\n        pydantic_config=pydantic_config,\n    )\n\n    if func is None:\n        return decorator\n\n    else:\n        return decorator(func)\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/","title":"ABCApp","text":"","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp","title":"faststream.app.ABCApp","text":"
ABCApp(\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[\n        Union[License, LicenseDict, AnyDict]\n    ] = None,\n    contact: Optional[\n        Union[Contact, ContactDict, AnyDict]\n    ] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[\n        Sequence[Union[Tag, TagDict, AnyDict]]\n    ] = None,\n    external_docs: Optional[\n        Union[ExternalDocs, ExternalDocsDict, AnyDict]\n    ] = None,\n)\n

Bases: ABC

A class representing an ABC App.

METHOD DESCRIPTION set_broker

Set the broker object

on_startup

Add a hook to be run before the broker is connected

on_shutdown

Add a hook to be run before the broker is disconnected

after_startup

Add a hook to be run after the broker is connected

after_shutdown

Add a hook to be run after the broker is disconnected

_log

Log a message at a specified

Initialize an instance of the class.

PARAMETER DESCRIPTION broker

An optional instance of the BrokerAsyncUsecase class.

TYPE: Optional[BrokerAsyncUsecase[Any, Any]] DEFAULT: None

logger

An optional instance of the logging.Logger class.

TYPE: Optional[Logger] DEFAULT: logger

title

A string representing the title of the AsyncAPI.

TYPE: str DEFAULT: 'FastStream'

version

A string representing the version of the AsyncAPI.

TYPE: str DEFAULT: '0.1.0'

description

A string representing the description of the AsyncAPI.

TYPE: str DEFAULT: ''

terms_of_service

An optional URL representing the terms of service of the AsyncAPI.

TYPE: Optional[AnyHttpUrl] DEFAULT: None

license

An optional instance of the License class.

TYPE: Optional[Union[License, LicenseDict, AnyDict]] DEFAULT: None

contact

An optional instance of the Contact class.

TYPE: Optional[Union[Contact, ContactDict, AnyDict]] DEFAULT: None

identifier

An optional string representing the identifier of the AsyncAPI.

TYPE: Optional[str] DEFAULT: None

tags

An optional sequence of Tag instances.

TYPE: Optional[Sequence[Union[Tag, TagDict, AnyDict]]] DEFAULT: None

external_docs

An optional instance of the ExternalDocs class.

TYPE: Optional[Union[ExternalDocs, ExternalDocsDict, AnyDict]] DEFAULT: None

Source code in faststream/app.py
def __init__(\n    self,\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    # AsyncAPI information\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[Union[License, LicenseDict, AnyDict]] = None,\n    contact: Optional[Union[Contact, ContactDict, AnyDict]] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[Sequence[Union[Tag, TagDict, AnyDict]]] = None,\n    external_docs: Optional[Union[ExternalDocs, ExternalDocsDict, AnyDict]] = None,\n) -> None:\n    \"\"\"Initialize an instance of the class.\n\n    Args:\n        broker: An optional instance of the BrokerAsyncUsecase class.\n        logger: An optional instance of the logging.Logger class.\n        title: A string representing the title of the AsyncAPI.\n        version: A string representing the version of the AsyncAPI.\n        description: A string representing the description of the AsyncAPI.\n        terms_of_service: An optional URL representing the terms of service of the AsyncAPI.\n        license: An optional instance of the License class.\n        contact: An optional instance of the Contact class.\n        identifier: An optional string representing the identifier of the AsyncAPI.\n        tags: An optional sequence of Tag instances.\n        external_docs: An optional instance of the ExternalDocs class.\n    \"\"\"\n    self.broker = broker\n    self.logger = logger\n    self.context = context\n    context.set_global(\"app\", self)\n\n    self._on_startup_calling = []\n    self._after_startup_calling = []\n    self._on_shutdown_calling = []\n    self._after_shutdown_calling = []\n\n    # AsyncAPI information\n    self.title = title\n    self.version = version\n    self.description = description\n    self.terms_of_service = terms_of_service\n    self.license = license\n    self.contact = contact\n    self.identifier = identifier\n    self.asyncapi_tags = tags\n    self.external_docs = external_docs\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = tags\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.contact","title":"contact instance-attribute","text":"
contact = contact\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.context","title":"context instance-attribute","text":"
context = context\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.external_docs","title":"external_docs instance-attribute","text":"
external_docs = external_docs\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.identifier","title":"identifier instance-attribute","text":"
identifier = identifier\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.license","title":"license instance-attribute","text":"
license = license\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = terms_of_service\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.title","title":"title instance-attribute","text":"
title = title\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.version","title":"version instance-attribute","text":"
version = version\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.after_shutdown","title":"after_shutdown","text":"
after_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker disconnected

Source code in faststream/app.py
def after_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker disconnected\"\"\"\n    self._after_shutdown_calling.append(apply_types(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.after_startup","title":"after_startup","text":"
after_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker connected

Source code in faststream/app.py
def after_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker connected\"\"\"\n    self._after_startup_calling.append(apply_types(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.on_shutdown","title":"on_shutdown","text":"
on_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker disconnected

Source code in faststream/app.py
def on_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker disconnected\"\"\"\n    self._on_shutdown_calling.append(apply_types(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.on_startup","title":"on_startup","text":"
on_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker connected This hook also takes an extra CLI options as a kwargs

Source code in faststream/app.py
def on_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker connected\n    This hook also takes an extra CLI options as a kwargs\"\"\"\n    self._on_startup_calling.append(apply_types(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/ABCApp/#faststream.app.ABCApp.set_broker","title":"set_broker","text":"
set_broker(broker: BrokerAsyncUsecase[Any, Any]) -> None\n

Set already existed App object broker Usefull then you create/init broker in on_startup hook

Source code in faststream/app.py
def set_broker(self, broker: BrokerAsyncUsecase[Any, Any]) -> None:\n    \"\"\"Set already existed App object broker\n    Usefull then you create/init broker in `on_startup` hook\"\"\"\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/app/FastStream/","title":"FastStream","text":"","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream","title":"faststream.app.FastStream","text":"
FastStream(\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    lifespan: Optional[Lifespan] = None,\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[\n        Union[License, LicenseDict, AnyDict]\n    ] = None,\n    contact: Optional[\n        Union[Contact, ContactDict, AnyDict]\n    ] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[\n        Sequence[Union[Tag, TagDict, AnyDict]]\n    ] = None,\n    external_docs: Optional[\n        Union[ExternalDocs, ExternalDocsDict, AnyDict]\n    ] = None,\n)\n

Bases: ABCApp

A class representing a FastStream application.

METHOD DESCRIPTION __init__

initializes the FastStream application

on_startup

adds a hook to run before the broker is connected

on_shutdown

adds a hook to run before the broker is disconnected

after_startup

adds a hook to run after the broker is connected

after_shutdown

adds a hook to run after the broker is disconnected

run

runs the FastStream application

_init_async_cycle

initializes the async cycle

_start

starts the FastStream application

_stop

stops the FastStream application

_startup

runs the startup hooks

_shutdown

runs the shutdown hooks

__exit

exits the FastStream application

Asyncronous FastStream Application class

stores and run broker, control hooks

PARAMETER DESCRIPTION broker

async broker to run (may be None, then specify by set_broker)

TYPE: Optional[BrokerAsyncUsecase[Any, Any]] DEFAULT: None

logger

logger object to log startup/shutdown messages (None to disable)

TYPE: Optional[Logger] DEFAULT: logger

title

application title - for AsyncAPI docs

TYPE: str DEFAULT: 'FastStream'

version

application version - for AsyncAPI docs

TYPE: str DEFAULT: '0.1.0'

description

application description - for AsyncAPI docs

TYPE: str DEFAULT: ''

Source code in faststream/app.py
def __init__(\n    self,\n    broker: Optional[BrokerAsyncUsecase[Any, Any]] = None,\n    logger: Optional[logging.Logger] = logger,\n    lifespan: Optional[Lifespan] = None,\n    # AsyncAPI args,\n    title: str = \"FastStream\",\n    version: str = \"0.1.0\",\n    description: str = \"\",\n    terms_of_service: Optional[AnyHttpUrl] = None,\n    license: Optional[Union[License, LicenseDict, AnyDict]] = None,\n    contact: Optional[Union[Contact, ContactDict, AnyDict]] = None,\n    identifier: Optional[str] = None,\n    tags: Optional[Sequence[Union[Tag, TagDict, AnyDict]]] = None,\n    external_docs: Optional[Union[ExternalDocs, ExternalDocsDict, AnyDict]] = None,\n) -> None:\n    \"\"\"Asyncronous FastStream Application class\n\n    stores and run broker, control hooks\n\n    Args:\n        broker: async broker to run (may be `None`, then specify by `set_broker`)\n        logger: logger object to log startup/shutdown messages (`None` to disable)\n        title: application title - for AsyncAPI docs\n        version: application version - for AsyncAPI docs\n        description: application description - for AsyncAPI docs\n    \"\"\"\n    super().__init__(\n        broker=broker,\n        logger=logger,\n        title=title,\n        version=version,\n        description=description,\n        terms_of_service=terms_of_service,\n        license=license,\n        contact=contact,\n        identifier=identifier,\n        tags=tags,\n        external_docs=external_docs,\n    )\n\n    self._stop_event = None\n\n    self.lifespan_context = (\n        apply_types(\n            func=lifespan,\n            wrap_model=drop_response_type,\n        )\n        if lifespan is not None\n        else fake_context\n    )\n\n    set_exit(lambda *_: self.__exit())\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = tags\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.contact","title":"contact instance-attribute","text":"
contact = contact\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.context","title":"context instance-attribute","text":"
context = context\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.external_docs","title":"external_docs instance-attribute","text":"
external_docs = external_docs\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.identifier","title":"identifier instance-attribute","text":"
identifier = identifier\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.license","title":"license instance-attribute","text":"
license = license\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context = (\n    apply_types(\n        func=lifespan, wrap_model=drop_response_type\n    )\n    if lifespan is not None\n    else fake_context\n)\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = terms_of_service\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.title","title":"title instance-attribute","text":"
title = title\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.version","title":"version instance-attribute","text":"
version = version\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.after_shutdown","title":"after_shutdown","text":"
after_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker disconnected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def after_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker disconnected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().after_shutdown(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.after_startup","title":"after_startup","text":"
after_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running AFTER broker connected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def after_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running AFTER broker connected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().after_startup(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.on_shutdown","title":"on_shutdown","text":"
on_shutdown(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker disconnected

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def on_shutdown(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker disconnected\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().on_shutdown(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.on_startup","title":"on_startup","text":"
on_startup(\n    func: Callable[P_HookParams, T_HookReturn]\n) -> Callable[P_HookParams, T_HookReturn]\n

Add hook running BEFORE broker connected

This hook also takes an extra CLI options as a kwargs

PARAMETER DESCRIPTION func

async or sync func to call as a hook

TYPE: Callable[P_HookParams, T_HookReturn]

RETURNS DESCRIPTION Callable[P_HookParams, T_HookReturn]

Async version of the func argument

Source code in faststream/app.py
def on_startup(\n    self,\n    func: Callable[P_HookParams, T_HookReturn],\n) -> Callable[P_HookParams, T_HookReturn]:\n    \"\"\"Add hook running BEFORE broker connected\n\n    This hook also takes an extra CLI options as a kwargs\n\n    Args:\n        func: async or sync func to call as a hook\n\n    Returns:\n        Async version of the func argument\n    \"\"\"\n    super().on_startup(to_async(func))\n    return func\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.run","title":"run async","text":"
run(\n    log_level: int = logging.INFO,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n) -> None\n

Run FastStream Application

PARAMETER DESCRIPTION log_level

force application log level

TYPE: int DEFAULT: INFO

RETURNS DESCRIPTION None

Block an event loop until stopped

Source code in faststream/app.py
async def run(\n    self,\n    log_level: int = logging.INFO,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Run FastStream Application\n\n    Args:\n        log_level: force application log level\n\n    Returns:\n        Block an event loop until stopped\n    \"\"\"\n    assert self.broker, \"You should setup a broker\"  # nosec B101\n\n    self._init_async_cycle()\n    async with self.lifespan_context(**(run_extra_options or {})):\n        try:\n            async with anyio.create_task_group() as tg:\n                tg.start_soon(self._start, log_level, run_extra_options)\n                await self._stop(log_level)\n                tg.cancel_scope.cancel()\n        except ExceptionGroup as e:\n            for ex in e.exceptions:\n                raise ex from None\n
","boost":0.5},{"location":"api/faststream/app/FastStream/#faststream.app.FastStream.set_broker","title":"set_broker","text":"
set_broker(broker: BrokerAsyncUsecase[Any, Any]) -> None\n

Set already existed App object broker Usefull then you create/init broker in on_startup hook

Source code in faststream/app.py
def set_broker(self, broker: BrokerAsyncUsecase[Any, Any]) -> None:\n    \"\"\"Set already existed App object broker\n    Usefull then you create/init broker in `on_startup` hook\"\"\"\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/asyncapi/get_asyncapi_html/","title":"get_asyncapi_html","text":"","boost":0.5},{"location":"api/faststream/asyncapi/get_asyncapi_html/#faststream.asyncapi.get_asyncapi_html","title":"faststream.asyncapi.get_asyncapi_html","text":"
get_asyncapi_html(\n    schema: Schema,\n    sidebar: bool = True,\n    info: bool = True,\n    servers: bool = True,\n    operations: bool = True,\n    messages: bool = True,\n    schemas: bool = True,\n    errors: bool = True,\n    expand_message_examples: bool = True,\n    title: str = \"FastStream\",\n) -> str\n

Generate HTML for displaying an AsyncAPI document.

PARAMETER DESCRIPTION schema

The AsyncAPI schema object.

TYPE: Schema

sidebar

Whether to show the sidebar. Defaults to True.

TYPE: bool DEFAULT: True

info

Whether to show the info section. Defaults to True.

TYPE: bool DEFAULT: True

servers

Whether to show the servers section. Defaults to True.

TYPE: bool DEFAULT: True

operations

Whether to show the operations section. Defaults to True.

TYPE: bool DEFAULT: True

messages

Whether to show the messages section. Defaults to True.

TYPE: bool DEFAULT: True

schemas

Whether to show the schemas section. Defaults to True.

TYPE: bool DEFAULT: True

errors

Whether to show the errors section. Defaults to True.

TYPE: bool DEFAULT: True

expand_message_examples

Whether to expand message examples. Defaults to True.

TYPE: bool DEFAULT: True

title

The title of the HTML document. Defaults to \"FastStream\".

TYPE: str DEFAULT: 'FastStream'

RETURNS DESCRIPTION str

The generated HTML document.

TYPE: str

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/asyncapi/site.py
def get_asyncapi_html(\n    schema: \"Schema\",\n    sidebar: bool = True,\n    info: bool = True,\n    servers: bool = True,\n    operations: bool = True,\n    messages: bool = True,\n    schemas: bool = True,\n    errors: bool = True,\n    expand_message_examples: bool = True,\n    title: str = \"FastStream\",\n) -> str:\n    \"\"\"Generate HTML for displaying an AsyncAPI document.\n\n    Args:\n        schema (Schema): The AsyncAPI schema object.\n        sidebar (bool, optional): Whether to show the sidebar. Defaults to True.\n        info (bool, optional): Whether to show the info section. Defaults to True.\n        servers (bool, optional): Whether to show the servers section. Defaults to True.\n        operations (bool, optional): Whether to show the operations section. Defaults to True.\n        messages (bool, optional): Whether to show the messages section. Defaults to True.\n        schemas (bool, optional): Whether to show the schemas section. Defaults to True.\n        errors (bool, optional): Whether to show the errors section. Defaults to True.\n        expand_message_examples (bool, optional): Whether to expand message examples. Defaults to True.\n        title (str, optional): The title of the HTML document. Defaults to \"FastStream\".\n\n    Returns:\n        str: The generated HTML document.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    schema_json = schema.to_json()\n\n    config = {\n        \"schema\": schema_json,\n        \"config\": {\n            \"show\": {\n                \"sidebar\": sidebar,\n                \"info\": info,\n                \"servers\": servers,\n                \"operations\": operations,\n                \"messages\": messages,\n                \"schemas\": schemas,\n                \"errors\": errors,\n            },\n            \"expand\": {\n                \"messageExamples\": expand_message_examples,\n            },\n            \"sidebar\": {\n                \"showServers\": \"byDefault\",\n                \"showOperations\": \"byDefault\",\n            },\n        },\n    }\n\n    return (\n        \"\"\"\n    <!DOCTYPE html>\n    <html>\n        <head>\n    \"\"\"\n        f\"\"\"\n        <title>{title} AsyncAPI</title>\n    \"\"\"\n        \"\"\"\n        <link rel=\"icon\" href=\"https://www.asyncapi.com/favicon.ico\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"https://www.asyncapi.com/favicon-16x16.png\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"https://www.asyncapi.com/favicon-32x32.png\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"194x194\" href=\"https://www.asyncapi.com/favicon-194x194.png\">\n        <link rel=\"stylesheet\" href=\"https://unpkg.com/@asyncapi/react-component@1.0.0-next.46/styles/default.min.css\">\n        </head>\n\n        <style>\n        html {\n            font-family: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;\n            line-height: 1.5;\n        }\n        </style>\n\n        <body>\n        <div id=\"asyncapi\"></div>\n\n        <script src=\"https://unpkg.com/@asyncapi/react-component@1.0.0-next.47/browser/standalone/index.js\"></script>\n        <script>\n    \"\"\"\n        f\"\"\"\n            AsyncApiStandalone.render({json.dumps(config)}, document.getElementById('asyncapi'));\n    \"\"\"\n        \"\"\"\n        </script>\n        </body>\n    </html>\n    \"\"\"\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/base/AsyncAPIOperation/","title":"AsyncAPIOperation","text":"","boost":0.5},{"location":"api/faststream/asyncapi/base/AsyncAPIOperation/#faststream.asyncapi.base.AsyncAPIOperation","title":"faststream.asyncapi.base.AsyncAPIOperation dataclass","text":"

A class representing an asynchronous API operation.

METHOD DESCRIPTION schema

returns the schema of the API operation as a dictionary of channel names and channel objects

","boost":0.5},{"location":"api/faststream/asyncapi/base/AsyncAPIOperation/#faststream.asyncapi.base.AsyncAPIOperation.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/asyncapi/base/AsyncAPIOperation/#faststream.asyncapi.base.AsyncAPIOperation.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/asyncapi/base/AsyncAPIOperation/#faststream.asyncapi.base.AsyncAPIOperation.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_broker_channels/","title":"get_app_broker_channels","text":"","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_broker_channels/#faststream.asyncapi.generate.get_app_broker_channels","title":"faststream.asyncapi.generate.get_app_broker_channels","text":"
get_app_broker_channels(\n    app: Union[FastStream, StreamRouter[Any]]\n) -> Dict[str, Channel]\n

Get the broker channels for an application.

PARAMETER DESCRIPTION app

An instance of FastStream or StreamRouter.

TYPE: Union[FastStream, StreamRouter[Any]]

RETURNS DESCRIPTION Dict[str, Channel]

A dictionary of channel names and their corresponding Channel objects.

RAISES DESCRIPTION AssertionError

If the app does not have a broker.

Source code in faststream/asyncapi/generate.py
def get_app_broker_channels(\n    app: Union[FastStream, \"StreamRouter[Any]\"]\n) -> Dict[str, Channel]:\n    \"\"\"Get the broker channels for an application.\n\n    Args:\n        app: An instance of FastStream or StreamRouter.\n\n    Returns:\n        A dictionary of channel names and their corresponding Channel objects.\n\n    Raises:\n        AssertionError: If the app does not have a broker.\n\n    \"\"\"\n    channels = {}\n    assert app.broker  # nosec B101\n\n    for h in app.broker.handlers.values():\n        channels.update(h.schema())\n\n    for p in app.broker._publishers.values():\n        channels.update(p.schema())\n\n    return channels\n
","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_broker_server/","title":"get_app_broker_server","text":"","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_broker_server/#faststream.asyncapi.generate.get_app_broker_server","title":"faststream.asyncapi.generate.get_app_broker_server","text":"
get_app_broker_server(\n    app: Union[FastStream, StreamRouter[Any]]\n) -> Dict[str, Server]\n

Get the broker server for an application.

PARAMETER DESCRIPTION app

An instance of FastStream or StreamRouter representing the application.

TYPE: Union[FastStream, StreamRouter[Any]]

RETURNS DESCRIPTION Dict[str, Server]

A dictionary containing the broker servers. The keys are the server names and the values are instances of Server class.

RAISES DESCRIPTION AssertionError

If the broker attribute of the app is not present.

Note

This function is currently incomplete and the following fields in the broker_meta dictionary are not populated: \"security\", \"variables\", \"bindings\".

Source code in faststream/asyncapi/generate.py
def get_app_broker_server(\n    app: Union[FastStream, \"StreamRouter[Any]\"]\n) -> Dict[str, Server]:\n    \"\"\"Get the broker server for an application.\n\n    Args:\n        app: An instance of `FastStream` or `StreamRouter` representing the application.\n\n    Returns:\n        A dictionary containing the broker servers. The keys are the server names and the values are instances of `Server` class.\n\n    Raises:\n        AssertionError: If the `broker` attribute of the app is not present.\n\n    Note:\n        This function is currently incomplete and the following fields in the `broker_meta` dictionary are not populated: \"security\", \"variables\", \"bindings\".\n\n    \"\"\"\n    servers = {}\n\n    broker = app.broker\n    assert broker  # nosec B101\n\n    broker_meta: Dict[str, Any] = {\n        \"protocol\": broker.protocol,\n        \"protocolVersion\": broker.protocol_version,\n        \"description\": broker.description,\n        \"tags\": broker.tags,\n        # TODO\n        # \"variables\": \"\",\n        # \"bindings\": \"\",\n    }\n\n    if broker.security is not None:\n        broker_meta[\"security\"] = broker.security.get_requirement()\n\n    if isinstance(broker.url, str):\n        servers[\"development\"] = Server(\n            url=broker.url,\n            **broker_meta,\n        )\n\n    elif len(broker.url) == 1:\n        servers[\"development\"] = Server(\n            url=broker.url[0],\n            **broker_meta,\n        )\n\n    else:\n        for i, url in enumerate(broker.url, 1):\n            servers[f\"Server{i}\"] = Server(\n                url=url,\n                **broker_meta,\n            )\n\n    return servers\n
","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_schema/","title":"get_app_schema","text":"","boost":0.5},{"location":"api/faststream/asyncapi/generate/get_app_schema/#faststream.asyncapi.generate.get_app_schema","title":"faststream.asyncapi.generate.get_app_schema","text":"
get_app_schema(\n    app: Union[FastStream, StreamRouter[Any]]\n) -> Schema\n

Get the application schema.

PARAMETER DESCRIPTION app

An instance of FastStream or StreamRouter.

TYPE: Union[FastStream, StreamRouter[Any]]

RETURNS DESCRIPTION Schema

The schema object.

Source code in faststream/asyncapi/generate.py
def get_app_schema(app: Union[FastStream, \"StreamRouter[Any]\"]) -> Schema:\n    \"\"\"Get the application schema.\n\n    Args:\n        app: An instance of FastStream or StreamRouter.\n\n    Returns:\n        The schema object.\n\n    \"\"\"\n    servers = get_app_broker_server(app)\n    channels = get_app_broker_channels(app)\n\n    messages: Dict[str, Message] = {}\n    payloads: Dict[str, Dict[str, Any]] = {}\n    for channel_name, ch in channels.items():\n        ch.servers = list(servers.keys())\n\n        if ch.subscribe is not None:\n            m = ch.subscribe.message\n\n            if isinstance(m, Message):  # pragma: no branch\n                ch.subscribe.message = _resolve_msg_payloads(\n                    m,\n                    channel_name,\n                    payloads,\n                    messages,\n                )\n\n        if ch.publish is not None:\n            m = ch.publish.message\n\n            if isinstance(m, Message):  # pragma: no branch\n                ch.publish.message = _resolve_msg_payloads(\n                    m,\n                    channel_name,\n                    payloads,\n                    messages,\n                )\n\n    broker = app.broker\n    if broker is None:  # pragma: no cover\n        raise RuntimeError()\n\n    schema = Schema(\n        info=Info(\n            title=app.title,\n            version=app.version,\n            description=app.description,\n            termsOfService=app.terms_of_service,\n            contact=app.contact,\n            license=app.license,\n        ),\n        defaultContentType=ContentTypes.json.value,\n        id=app.identifier,\n        tags=list(app.asyncapi_tags) if app.asyncapi_tags else None,\n        externalDocs=app.external_docs,\n        servers=servers,\n        channels=channels,\n        components=Components(\n            messages=messages,\n            schemas=payloads,\n            securitySchemes=None\n            if broker.security is None\n            else broker.security.get_schema(),\n        ),\n    )\n    return schema\n
","boost":0.5},{"location":"api/faststream/asyncapi/message/get_model_schema/","title":"get_model_schema","text":"","boost":0.5},{"location":"api/faststream/asyncapi/message/get_model_schema/#faststream.asyncapi.message.get_model_schema","title":"faststream.asyncapi.message.get_model_schema","text":"
get_model_schema(\n    call: Optional[Type[BaseModel]],\n    prefix: str = \"\",\n    exclude: Sequence[str] = (),\n) -> Optional[Dict[str, Any]]\n

Get the schema of a model.

PARAMETER DESCRIPTION call

The model class to get the schema for.

TYPE: Optional[Type[BaseModel]]

prefix

A prefix to add to the schema title.

TYPE: str DEFAULT: ''

exclude

A sequence of field names to exclude from the schema.

TYPE: Sequence[str] DEFAULT: ()

RETURNS DESCRIPTION Optional[Dict[str, Any]]

The schema of the model as a dictionary, or None if the model has no fields.

RAISES DESCRIPTION NotImplementedError

If the model is a silent animal.

Source code in faststream/asyncapi/message.py
def get_model_schema(\n    call: Optional[Type[BaseModel]],\n    prefix: str = \"\",\n    exclude: Sequence[str] = (),\n) -> Optional[Dict[str, Any]]:\n    \"\"\"Get the schema of a model.\n\n    Args:\n        call: The model class to get the schema for.\n        prefix: A prefix to add to the schema title.\n        exclude: A sequence of field names to exclude from the schema.\n\n    Returns:\n        The schema of the model as a dictionary, or None if the model has no fields.\n\n    Raises:\n        NotImplementedError: If the model is a silent animal.\n\n    \"\"\"\n    if call is None:\n        return None\n\n    params = {k: v for k, v in get_model_fields(call).items() if k not in exclude}\n    params_number = len(params)\n\n    if params_number == 0:\n        return None\n\n    model = None\n    use_original_model = False\n    if params_number == 1:\n        name, param = tuple(params.items())[0]\n\n        if (\n            param.annotation\n            and isclass(param.annotation)\n            and issubclass(param.annotation, BaseModel)  # NOTE: 3.7-3.10 compatibility\n        ):\n            model = param.annotation\n            use_original_model = True\n\n    if model is None:\n        model = call\n\n    body: Dict[str, Any] = model_schema(model)\n    body[\"properties\"] = body.get(\"properties\", {})\n    for i in exclude:\n        body[\"properties\"].pop(i, None)\n    if required := body.get(\"required\"):\n        body[\"required\"] = list(filter(lambda x: x not in exclude, required))\n\n    if params_number == 1 and not use_original_model:\n        param_body: Dict[str, Any] = body.get(\"properties\", {})\n        param_body = param_body[name]\n\n        if PYDANTIC_V2:\n            original_title = param.title\n        else:\n            original_title = param.field_info.title  # type: ignore[attr-defined]\n\n        if original_title:\n            use_original_model = True\n            param_body[\"title\"] = original_title\n        else:\n            param_body[\"title\"] = name\n\n        body = param_body\n\n    if not use_original_model:\n        body[\"title\"] = f\"{prefix}:Payload\"\n\n    return body\n
","boost":0.5},{"location":"api/faststream/asyncapi/message/get_response_schema/","title":"get_response_schema","text":"","boost":0.5},{"location":"api/faststream/asyncapi/message/get_response_schema/#faststream.asyncapi.message.get_response_schema","title":"faststream.asyncapi.message.get_response_schema","text":"
get_response_schema(\n    call: Optional[CallModel[Any, Any]], prefix: str = \"\"\n) -> Optional[Dict[str, Any]]\n

Get the response schema for a given call.

PARAMETER DESCRIPTION call

The call model.

TYPE: Optional[CallModel[Any, Any]]

prefix

A prefix to add to the schema keys.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION Optional[Dict[str, Any]]

The response schema as a dictionary.

Source code in faststream/asyncapi/message.py
def get_response_schema(\n    call: Optional[CallModel[Any, Any]],\n    prefix: str = \"\",\n) -> Optional[Dict[str, Any]]:\n    \"\"\"Get the response schema for a given call.\n\n    Args:\n        call: The call model.\n        prefix: A prefix to add to the schema keys.\n\n    Returns:\n        The response schema as a dictionary.\n\n    \"\"\"\n    return get_model_schema(\n        getattr(\n            call, \"response_model\", None\n        ),  # NOTE: FastAPI Dependant object compatibility\n        prefix=prefix,\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/message/parse_handler_params/","title":"parse_handler_params","text":"","boost":0.5},{"location":"api/faststream/asyncapi/message/parse_handler_params/#faststream.asyncapi.message.parse_handler_params","title":"faststream.asyncapi.message.parse_handler_params","text":"
parse_handler_params(\n    call: CallModel[Any, Any], prefix: str = \"\"\n) -> Dict[str, Any]\n

Parses the handler parameters.

PARAMETER DESCRIPTION call

The call model.

TYPE: CallModel[Any, Any]

prefix

The prefix for the model schema.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION Dict[str, Any]

A dictionary containing the parsed parameters.

Source code in faststream/asyncapi/message.py
def parse_handler_params(call: CallModel[Any, Any], prefix: str = \"\") -> Dict[str, Any]:\n    \"\"\"Parses the handler parameters.\n\n    Args:\n        call: The call model.\n        prefix: The prefix for the model schema.\n\n    Returns:\n        A dictionary containing the parsed parameters.\n\n    \"\"\"\n    body = get_model_schema(\n        call.model,\n        prefix=prefix,\n        exclude=tuple(call.custom_fields.keys()),\n    )\n\n    if body is None:\n        return {\"title\": \"EmptyPayload\", \"type\": \"null\"}\n\n    return body\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/","title":"Channel","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel","title":"faststream.asyncapi.schema.Channel","text":"

Bases: BaseModel

A class to represent a channel.

Configurations

model_config : configuration for the model (only applicable for Pydantic version 2) Config : configuration for the class (only applicable for Pydantic version 1)

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.parameters","title":"parameters class-attribute instance-attribute","text":"
parameters: Optional[Parameter] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.publish","title":"publish class-attribute instance-attribute","text":"
publish: Optional[Operation] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.servers","title":"servers class-attribute instance-attribute","text":"
servers: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.subscribe","title":"subscribe class-attribute instance-attribute","text":"
subscribe: Optional[Operation] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Channel/#faststream.asyncapi.schema.Channel.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding","title":"faststream.asyncapi.schema.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ChannelBinding/#faststream.asyncapi.schema.ChannelBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/","title":"Components","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components","title":"faststream.asyncapi.schema.Components","text":"

Bases: BaseModel

A class to represent components in a system.

Note

The following attributes are not implemented yet: - servers - serverVariables - channels - securitySchemes - parameters - correlationIds - operationTraits - messageTraits - serverBindings - channelBindings - operationBindings - messageBindings

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.messages","title":"messages class-attribute instance-attribute","text":"
messages: Optional[Dict[str, Message]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.schemas","title":"schemas class-attribute instance-attribute","text":"
schemas: Optional[Dict[str, Dict[str, Any]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.securitySchemes","title":"securitySchemes class-attribute instance-attribute","text":"
securitySchemes: Optional[Dict[str, Dict[str, Any]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Components/#faststream.asyncapi.schema.Components.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/","title":"Contact","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact","title":"faststream.asyncapi.schema.Contact","text":"

Bases: BaseModel

A class to represent a contact.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.email","title":"email class-attribute instance-attribute","text":"
email: Optional[EmailStr] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.url","title":"url class-attribute instance-attribute","text":"
url: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Contact/#faststream.asyncapi.schema.Contact.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ContactDict/","title":"ContactDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ContactDict/#faststream.asyncapi.schema.ContactDict","title":"faststream.asyncapi.schema.ContactDict","text":"

Bases: TypedDict

A class to represent a dictionary of contact information.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/ContactDict/#faststream.asyncapi.schema.ContactDict.email","title":"email instance-attribute","text":"
email: EmailStr\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ContactDict/#faststream.asyncapi.schema.ContactDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ContactDict/#faststream.asyncapi.schema.ContactDict.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/","title":"CorrelationId","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId","title":"faststream.asyncapi.schema.CorrelationId","text":"

Bases: BaseModel

A class to represent a correlation ID.

Configurations

extra : allows extra fields in the correlation ID model

","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId.location","title":"location instance-attribute","text":"
location: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/CorrelationId/#faststream.asyncapi.schema.CorrelationId.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/","title":"ExternalDocs","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs","title":"faststream.asyncapi.schema.ExternalDocs","text":"

Bases: BaseModel

A class to represent external documentation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocs/#faststream.asyncapi.schema.ExternalDocs.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocsDict/","title":"ExternalDocsDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocsDict/#faststream.asyncapi.schema.ExternalDocsDict","title":"faststream.asyncapi.schema.ExternalDocsDict","text":"

Bases: TypedDict

A dictionary type for representing external documentation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocsDict/#faststream.asyncapi.schema.ExternalDocsDict.description","title":"description instance-attribute","text":"
description: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ExternalDocsDict/#faststream.asyncapi.schema.ExternalDocsDict.url","title":"url instance-attribute","text":"
url: Required[AnyHttpUrl]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/","title":"Info","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info","title":"faststream.asyncapi.schema.Info","text":"

Bases: BaseModel

A class to represent information.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.contact","title":"contact class-attribute instance-attribute","text":"
contact: Optional[\n    Union[Contact, ContactDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.description","title":"description class-attribute instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.license","title":"license class-attribute instance-attribute","text":"
license: Optional[\n    Union[License, LicenseDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.termsOfService","title":"termsOfService class-attribute instance-attribute","text":"
termsOfService: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.title","title":"title instance-attribute","text":"
title: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.version","title":"version class-attribute instance-attribute","text":"
version: str = '1.0.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Info/#faststream.asyncapi.schema.Info.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/","title":"License","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License","title":"faststream.asyncapi.schema.License","text":"

Bases: BaseModel

A class to represent a license.

Config

extra : allow additional attributes in the model (PYDANTIC_V2)

","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License.url","title":"url class-attribute instance-attribute","text":"
url: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/License/#faststream.asyncapi.schema.License.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/LicenseDict/","title":"LicenseDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/LicenseDict/#faststream.asyncapi.schema.LicenseDict","title":"faststream.asyncapi.schema.LicenseDict","text":"

Bases: TypedDict

A dictionary-like class to represent a license.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/LicenseDict/#faststream.asyncapi.schema.LicenseDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/LicenseDict/#faststream.asyncapi.schema.LicenseDict.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/","title":"Message","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message","title":"faststream.asyncapi.schema.Message","text":"

Bases: BaseModel

A class to represent a message.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.contentType","title":"contentType class-attribute instance-attribute","text":"
contentType: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.correlationId","title":"correlationId class-attribute instance-attribute","text":"
correlationId: Optional[CorrelationId] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.messageId","title":"messageId class-attribute instance-attribute","text":"
messageId: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.payload","title":"payload instance-attribute","text":"
payload: Dict[str, Any]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.summary","title":"summary class-attribute instance-attribute","text":"
summary: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[List[Union[Tag, Dict[str, Any]]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Message/#faststream.asyncapi.schema.Message.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/","title":"Operation","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation","title":"faststream.asyncapi.schema.Operation","text":"

Bases: BaseModel

A class to represent an operation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.message","title":"message instance-attribute","text":"
message: Union[Message, Reference]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.operationId","title":"operationId class-attribute instance-attribute","text":"
operationId: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.security","title":"security class-attribute instance-attribute","text":"
security: Optional[Dict[str, List[str]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.summary","title":"summary class-attribute instance-attribute","text":"
summary: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Operation/#faststream.asyncapi.schema.Operation.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding","title":"faststream.asyncapi.schema.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/OperationBinding/#faststream.asyncapi.schema.OperationBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Reference/","title":"Reference","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Reference/#faststream.asyncapi.schema.Reference","title":"faststream.asyncapi.schema.Reference","text":"

Bases: BaseModel

A class to represent a reference.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Reference/#faststream.asyncapi.schema.Reference.ref","title":"ref class-attribute instance-attribute","text":"
ref: str = Field(..., alias='$ref')\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/","title":"Schema","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema","title":"faststream.asyncapi.schema.Schema","text":"

Bases: BaseModel

A class to represent a schema.

METHOD DESCRIPTION to_jsonable

Convert the schema to a JSON-serializable object.

to_json

Convert the schema to a JSON string.

to_yaml

Convert the schema to a YAML string.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.asyncapi","title":"asyncapi class-attribute instance-attribute","text":"
asyncapi: str = ASYNC_API_VERSION\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.channels","title":"channels instance-attribute","text":"
channels: Dict[str, Channel]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.components","title":"components class-attribute instance-attribute","text":"
components: Optional[Components] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.defaultContentType","title":"defaultContentType class-attribute instance-attribute","text":"
defaultContentType: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.id","title":"id class-attribute instance-attribute","text":"
id: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.info","title":"info instance-attribute","text":"
info: Info\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.servers","title":"servers class-attribute instance-attribute","text":"
servers: Optional[Dict[str, Server]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.to_json","title":"to_json","text":"
to_json() -> str\n
Source code in faststream/asyncapi/schema/main.py
def to_json(self) -> str:\n    return model_to_json(\n        self,\n        by_alias=True,\n        exclude_none=True,\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.to_jsonable","title":"to_jsonable","text":"
to_jsonable() -> Any\n
Source code in faststream/asyncapi/schema/main.py
def to_jsonable(self) -> Any:\n    return model_to_jsonable(\n        self,\n        by_alias=True,\n        exclude_none=True,\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Schema/#faststream.asyncapi.schema.Schema.to_yaml","title":"to_yaml","text":"
to_yaml() -> str\n
Source code in faststream/asyncapi/schema/main.py
def to_yaml(self) -> str:\n    from io import StringIO\n\n    import yaml\n\n    io = StringIO(initial_value=\"\", newline=\"\\n\")\n    yaml.dump(self.to_jsonable(), io, sort_keys=False)\n    return io.getvalue()\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/","title":"SecuritySchemaComponent","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent","title":"faststream.asyncapi.schema.SecuritySchemaComponent","text":"

Bases: BaseModel

A class to represent a security schema component.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.bearerFormat","title":"bearerFormat class-attribute instance-attribute","text":"
bearerFormat: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.flows","title":"flows class-attribute instance-attribute","text":"
flows: Optional[OauthFlows] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.in_","title":"in_ class-attribute instance-attribute","text":"
in_: Optional[str] = Field(default=None, alias='in')\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.openIdConnectUrl","title":"openIdConnectUrl class-attribute instance-attribute","text":"
openIdConnectUrl: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.schema_","title":"schema_ class-attribute instance-attribute","text":"
schema_: Optional[str] = Field(default=None, alias=\"schema\")\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.type","title":"type instance-attribute","text":"
type: Literal[\n    \"userPassword\",\n    \"apikey\",\n    \"X509\",\n    \"symmetricEncryption\",\n    \"asymmetricEncryption\",\n    \"httpApiKey\",\n    \"http\",\n    \"oauth2\",\n    \"openIdConnect\",\n    \"plain\",\n    \"scramSha256\",\n    \"scramSha512\",\n    \"gssapi\",\n]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/SecuritySchemaComponent/#faststream.asyncapi.schema.SecuritySchemaComponent.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/","title":"Server","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server","title":"faststream.asyncapi.schema.Server","text":"

Bases: BaseModel

A class to represent a server.

Note

The attributes description, protocolVersion, tags, security, variables, and bindings are all optional.

Configurations

If PYDANTIC_V2 is True, the model configuration is set to allow extra attributes. Otherwise, the Config class is defined with the extra attribute set to \"allow\".

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[Union[ServerBinding, Reference]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.protocol","title":"protocol instance-attribute","text":"
protocol: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.protocolVersion","title":"protocolVersion class-attribute instance-attribute","text":"
protocolVersion: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.security","title":"security class-attribute instance-attribute","text":"
security: Optional[SecurityRequirement] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.variables","title":"variables class-attribute instance-attribute","text":"
variables: Optional[\n    Dict[str, Union[ServerVariable, Reference]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Server/#faststream.asyncapi.schema.Server.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding","title":"faststream.asyncapi.schema.ServerBinding","text":"

Bases: BaseModel

A class to represent server bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/ServerBinding/#faststream.asyncapi.schema.ServerBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/","title":"Tag","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag","title":"faststream.asyncapi.schema.Tag","text":"

Bases: BaseModel

A class to represent a tag.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/Tag/#faststream.asyncapi.schema.Tag.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/TagDict/","title":"TagDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/TagDict/#faststream.asyncapi.schema.TagDict","title":"faststream.asyncapi.schema.TagDict","text":"

Bases: TypedDict

A dictionary-like class for storing tags.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/TagDict/#faststream.asyncapi.schema.TagDict.description","title":"description instance-attribute","text":"
description: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/TagDict/#faststream.asyncapi.schema.TagDict.externalDocs","title":"externalDocs instance-attribute","text":"
externalDocs: Union[ExternalDocs, ExternalDocsDict]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/TagDict/#faststream.asyncapi.schema.TagDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding","title":"faststream.asyncapi.schema.bindings.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ChannelBinding/#faststream.asyncapi.schema.bindings.ChannelBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding","title":"faststream.asyncapi.schema.bindings.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/OperationBinding/#faststream.asyncapi.schema.bindings.OperationBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding","title":"faststream.asyncapi.schema.bindings.ServerBinding","text":"

Bases: BaseModel

A class to represent server bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/ServerBinding/#faststream.asyncapi.schema.bindings.ServerBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/#faststream.asyncapi.schema.bindings.amqp.ChannelBinding","title":"faststream.asyncapi.schema.bindings.amqp.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/#faststream.asyncapi.schema.bindings.amqp.ChannelBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.2.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/#faststream.asyncapi.schema.bindings.amqp.ChannelBinding.exchange","title":"exchange class-attribute instance-attribute","text":"
exchange: Optional[Exchange] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/#faststream.asyncapi.schema.bindings.amqp.ChannelBinding.is_","title":"is_ class-attribute instance-attribute","text":"
is_: Literal[\"queue\", \"routingKey\"] = Field(..., alias=\"is\")\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ChannelBinding/#faststream.asyncapi.schema.bindings.amqp.ChannelBinding.queue","title":"queue class-attribute instance-attribute","text":"
queue: Optional[Queue] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/","title":"Exchange","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange","title":"faststream.asyncapi.schema.bindings.amqp.Exchange","text":"

Bases: BaseModel

A class to represent an exchange.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange.autoDelete","title":"autoDelete class-attribute instance-attribute","text":"
autoDelete: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange.durable","title":"durable class-attribute instance-attribute","text":"
durable: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange.type","title":"type instance-attribute","text":"
type: Literal[\n    \"default\", \"direct\", \"topic\", \"fanout\", \"headers\"\n]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Exchange/#faststream.asyncapi.schema.bindings.amqp.Exchange.vhost","title":"vhost class-attribute instance-attribute","text":"
vhost: str = '/'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding","title":"faststream.asyncapi.schema.bindings.amqp.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.ack","title":"ack class-attribute instance-attribute","text":"
ack: bool = True\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.2.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.cc","title":"cc class-attribute instance-attribute","text":"
cc: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.deliveryMode","title":"deliveryMode class-attribute instance-attribute","text":"
deliveryMode: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.priority","title":"priority class-attribute instance-attribute","text":"
priority: Optional[PositiveInt] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/OperationBinding/#faststream.asyncapi.schema.bindings.amqp.OperationBinding.replyTo","title":"replyTo class-attribute instance-attribute","text":"
replyTo: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/","title":"Queue","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue","title":"faststream.asyncapi.schema.bindings.amqp.Queue","text":"

Bases: BaseModel

A class to represent a queue.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue.autoDelete","title":"autoDelete instance-attribute","text":"
autoDelete: bool\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue.durable","title":"durable instance-attribute","text":"
durable: bool\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue.exclusive","title":"exclusive instance-attribute","text":"
exclusive: bool\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/Queue/#faststream.asyncapi.schema.bindings.amqp.Queue.vhost","title":"vhost class-attribute instance-attribute","text":"
vhost: str = '/'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ServerBinding/#faststream.asyncapi.schema.bindings.amqp.ServerBinding","title":"faststream.asyncapi.schema.bindings.amqp.ServerBinding","text":"

Bases: BaseModel

A class to represent a server binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/amqp/ServerBinding/#faststream.asyncapi.schema.bindings.amqp.ServerBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.2.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/#faststream.asyncapi.schema.bindings.kafka.ChannelBinding","title":"faststream.asyncapi.schema.bindings.kafka.ChannelBinding","text":"

Bases: BaseModel

A class to represent a channel binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/#faststream.asyncapi.schema.bindings.kafka.ChannelBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.4.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/#faststream.asyncapi.schema.bindings.kafka.ChannelBinding.partitions","title":"partitions class-attribute instance-attribute","text":"
partitions: Optional[PositiveInt] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/#faststream.asyncapi.schema.bindings.kafka.ChannelBinding.replicas","title":"replicas class-attribute instance-attribute","text":"
replicas: Optional[PositiveInt] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ChannelBinding/#faststream.asyncapi.schema.bindings.kafka.ChannelBinding.topic","title":"topic class-attribute instance-attribute","text":"
topic: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/#faststream.asyncapi.schema.bindings.kafka.OperationBinding","title":"faststream.asyncapi.schema.bindings.kafka.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/#faststream.asyncapi.schema.bindings.kafka.OperationBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.4.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/#faststream.asyncapi.schema.bindings.kafka.OperationBinding.clientId","title":"clientId class-attribute instance-attribute","text":"
clientId: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/#faststream.asyncapi.schema.bindings.kafka.OperationBinding.groupId","title":"groupId class-attribute instance-attribute","text":"
groupId: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/OperationBinding/#faststream.asyncapi.schema.bindings.kafka.OperationBinding.replyTo","title":"replyTo class-attribute instance-attribute","text":"
replyTo: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ServerBinding/#faststream.asyncapi.schema.bindings.kafka.ServerBinding","title":"faststream.asyncapi.schema.bindings.kafka.ServerBinding","text":"

Bases: BaseModel

A class to represent a server binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/kafka/ServerBinding/#faststream.asyncapi.schema.bindings.kafka.ServerBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = '0.4.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding","title":"faststream.asyncapi.schema.bindings.main.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ChannelBinding/#faststream.asyncapi.schema.bindings.main.ChannelBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding","title":"faststream.asyncapi.schema.bindings.main.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/OperationBinding/#faststream.asyncapi.schema.bindings.main.OperationBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding","title":"faststream.asyncapi.schema.bindings.main.ServerBinding","text":"

Bases: BaseModel

A class to represent server bindings.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.amqp","title":"amqp class-attribute instance-attribute","text":"
amqp: Optional[amqp_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.kafka","title":"kafka class-attribute instance-attribute","text":"
kafka: Optional[kafka_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.nats","title":"nats class-attribute instance-attribute","text":"
nats: Optional[nats_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.redis","title":"redis class-attribute instance-attribute","text":"
redis: Optional[redis_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.sqs","title":"sqs class-attribute instance-attribute","text":"
sqs: Optional[sqs_bindings.ServerBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/main/ServerBinding/#faststream.asyncapi.schema.bindings.main.ServerBinding.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ChannelBinding/#faststream.asyncapi.schema.bindings.nats.ChannelBinding","title":"faststream.asyncapi.schema.bindings.nats.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ChannelBinding/#faststream.asyncapi.schema.bindings.nats.ChannelBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ChannelBinding/#faststream.asyncapi.schema.bindings.nats.ChannelBinding.queue","title":"queue class-attribute instance-attribute","text":"
queue: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ChannelBinding/#faststream.asyncapi.schema.bindings.nats.ChannelBinding.subject","title":"subject instance-attribute","text":"
subject: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/OperationBinding/#faststream.asyncapi.schema.bindings.nats.OperationBinding","title":"faststream.asyncapi.schema.bindings.nats.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/OperationBinding/#faststream.asyncapi.schema.bindings.nats.OperationBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/OperationBinding/#faststream.asyncapi.schema.bindings.nats.OperationBinding.replyTo","title":"replyTo class-attribute instance-attribute","text":"
replyTo: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ServerBinding/#faststream.asyncapi.schema.bindings.nats.ServerBinding","title":"faststream.asyncapi.schema.bindings.nats.ServerBinding","text":"

Bases: BaseModel

A class to represent a server binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/nats/ServerBinding/#faststream.asyncapi.schema.bindings.nats.ServerBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding","title":"faststream.asyncapi.schema.bindings.redis.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding.channel","title":"channel instance-attribute","text":"
channel: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding.consumer_name","title":"consumer_name class-attribute instance-attribute","text":"
consumer_name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding.group_name","title":"group_name class-attribute instance-attribute","text":"
group_name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ChannelBinding/#faststream.asyncapi.schema.bindings.redis.ChannelBinding.method","title":"method class-attribute instance-attribute","text":"
method: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/OperationBinding/#faststream.asyncapi.schema.bindings.redis.OperationBinding","title":"faststream.asyncapi.schema.bindings.redis.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/OperationBinding/#faststream.asyncapi.schema.bindings.redis.OperationBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/OperationBinding/#faststream.asyncapi.schema.bindings.redis.OperationBinding.replyTo","title":"replyTo class-attribute instance-attribute","text":"
replyTo: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ServerBinding/#faststream.asyncapi.schema.bindings.redis.ServerBinding","title":"faststream.asyncapi.schema.bindings.redis.ServerBinding","text":"

Bases: BaseModel

A class to represent a server binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/redis/ServerBinding/#faststream.asyncapi.schema.bindings.redis.ServerBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ChannelBinding/","title":"ChannelBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ChannelBinding/#faststream.asyncapi.schema.bindings.sqs.ChannelBinding","title":"faststream.asyncapi.schema.bindings.sqs.ChannelBinding","text":"

Bases: BaseModel

A class to represent channel binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ChannelBinding/#faststream.asyncapi.schema.bindings.sqs.ChannelBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ChannelBinding/#faststream.asyncapi.schema.bindings.sqs.ChannelBinding.queue","title":"queue instance-attribute","text":"
queue: Dict[str, Any]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/OperationBinding/","title":"OperationBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/OperationBinding/#faststream.asyncapi.schema.bindings.sqs.OperationBinding","title":"faststream.asyncapi.schema.bindings.sqs.OperationBinding","text":"

Bases: BaseModel

A class to represent an operation binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/OperationBinding/#faststream.asyncapi.schema.bindings.sqs.OperationBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/OperationBinding/#faststream.asyncapi.schema.bindings.sqs.OperationBinding.replyTo","title":"replyTo class-attribute instance-attribute","text":"
replyTo: Optional[Dict[str, Any]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ServerBinding/","title":"ServerBinding","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ServerBinding/#faststream.asyncapi.schema.bindings.sqs.ServerBinding","title":"faststream.asyncapi.schema.bindings.sqs.ServerBinding","text":"

Bases: BaseModel

A class to represent a server binding.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/bindings/sqs/ServerBinding/#faststream.asyncapi.schema.bindings.sqs.ServerBinding.bindingVersion","title":"bindingVersion class-attribute instance-attribute","text":"
bindingVersion: str = 'custom'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/","title":"Channel","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel","title":"faststream.asyncapi.schema.channels.Channel","text":"

Bases: BaseModel

A class to represent a channel.

Configurations

model_config : configuration for the model (only applicable for Pydantic version 2) Config : configuration for the class (only applicable for Pydantic version 1)

","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[ChannelBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.parameters","title":"parameters class-attribute instance-attribute","text":"
parameters: Optional[Parameter] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.publish","title":"publish class-attribute instance-attribute","text":"
publish: Optional[Operation] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.servers","title":"servers class-attribute instance-attribute","text":"
servers: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.subscribe","title":"subscribe class-attribute instance-attribute","text":"
subscribe: Optional[Operation] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/channels/Channel/#faststream.asyncapi.schema.channels.Channel.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/","title":"Contact","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact","title":"faststream.asyncapi.schema.info.Contact","text":"

Bases: BaseModel

A class to represent a contact.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.email","title":"email class-attribute instance-attribute","text":"
email: Optional[EmailStr] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.url","title":"url class-attribute instance-attribute","text":"
url: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Contact/#faststream.asyncapi.schema.info.Contact.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/ContactDict/","title":"ContactDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/ContactDict/#faststream.asyncapi.schema.info.ContactDict","title":"faststream.asyncapi.schema.info.ContactDict","text":"

Bases: TypedDict

A class to represent a dictionary of contact information.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/ContactDict/#faststream.asyncapi.schema.info.ContactDict.email","title":"email instance-attribute","text":"
email: EmailStr\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/ContactDict/#faststream.asyncapi.schema.info.ContactDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/ContactDict/#faststream.asyncapi.schema.info.ContactDict.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/EmailStr/","title":"EmailStr","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/EmailStr/#faststream.asyncapi.schema.info.EmailStr","title":"faststream.asyncapi.schema.info.EmailStr","text":"

Bases: str

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/EmailStr/#faststream.asyncapi.schema.info.EmailStr.validate","title":"validate classmethod","text":"
validate(v: Any) -> str\n
Source code in faststream/asyncapi/schema/info.py
@classmethod\ndef validate(cls, v: Any) -> str:\n    logger.warning(\n        \"email-validator bot installed, email fields will be treated as str.\\n\"\n        \"To install, run: pip install email-validator\"\n    )\n    return str(v)\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/","title":"Info","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info","title":"faststream.asyncapi.schema.info.Info","text":"

Bases: BaseModel

A class to represent information.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.contact","title":"contact class-attribute instance-attribute","text":"
contact: Optional[\n    Union[Contact, ContactDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.description","title":"description class-attribute instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.license","title":"license class-attribute instance-attribute","text":"
license: Optional[\n    Union[License, LicenseDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.termsOfService","title":"termsOfService class-attribute instance-attribute","text":"
termsOfService: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.title","title":"title instance-attribute","text":"
title: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.version","title":"version class-attribute instance-attribute","text":"
version: str = '1.0.0'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/Info/#faststream.asyncapi.schema.info.Info.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/","title":"License","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License","title":"faststream.asyncapi.schema.info.License","text":"

Bases: BaseModel

A class to represent a license.

Config

extra : allow additional attributes in the model (PYDANTIC_V2)

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License.url","title":"url class-attribute instance-attribute","text":"
url: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/License/#faststream.asyncapi.schema.info.License.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/LicenseDict/","title":"LicenseDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/LicenseDict/#faststream.asyncapi.schema.info.LicenseDict","title":"faststream.asyncapi.schema.info.LicenseDict","text":"

Bases: TypedDict

A dictionary-like class to represent a license.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/LicenseDict/#faststream.asyncapi.schema.info.LicenseDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/info/LicenseDict/#faststream.asyncapi.schema.info.LicenseDict.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/","title":"Components","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components","title":"faststream.asyncapi.schema.main.Components","text":"

Bases: BaseModel

A class to represent components in a system.

Note

The following attributes are not implemented yet: - servers - serverVariables - channels - securitySchemes - parameters - correlationIds - operationTraits - messageTraits - serverBindings - channelBindings - operationBindings - messageBindings

","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.messages","title":"messages class-attribute instance-attribute","text":"
messages: Optional[Dict[str, Message]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.schemas","title":"schemas class-attribute instance-attribute","text":"
schemas: Optional[Dict[str, Dict[str, Any]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.securitySchemes","title":"securitySchemes class-attribute instance-attribute","text":"
securitySchemes: Optional[Dict[str, Dict[str, Any]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Components/#faststream.asyncapi.schema.main.Components.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/","title":"Schema","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema","title":"faststream.asyncapi.schema.main.Schema","text":"

Bases: BaseModel

A class to represent a schema.

METHOD DESCRIPTION to_jsonable

Convert the schema to a JSON-serializable object.

to_json

Convert the schema to a JSON string.

to_yaml

Convert the schema to a YAML string.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.asyncapi","title":"asyncapi class-attribute instance-attribute","text":"
asyncapi: str = ASYNC_API_VERSION\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.channels","title":"channels instance-attribute","text":"
channels: Dict[str, Channel]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.components","title":"components class-attribute instance-attribute","text":"
components: Optional[Components] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.defaultContentType","title":"defaultContentType class-attribute instance-attribute","text":"
defaultContentType: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.id","title":"id class-attribute instance-attribute","text":"
id: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.info","title":"info instance-attribute","text":"
info: Info\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.servers","title":"servers class-attribute instance-attribute","text":"
servers: Optional[Dict[str, Server]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.to_json","title":"to_json","text":"
to_json() -> str\n
Source code in faststream/asyncapi/schema/main.py
def to_json(self) -> str:\n    return model_to_json(\n        self,\n        by_alias=True,\n        exclude_none=True,\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.to_jsonable","title":"to_jsonable","text":"
to_jsonable() -> Any\n
Source code in faststream/asyncapi/schema/main.py
def to_jsonable(self) -> Any:\n    return model_to_jsonable(\n        self,\n        by_alias=True,\n        exclude_none=True,\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/main/Schema/#faststream.asyncapi.schema.main.Schema.to_yaml","title":"to_yaml","text":"
to_yaml() -> str\n
Source code in faststream/asyncapi/schema/main.py
def to_yaml(self) -> str:\n    from io import StringIO\n\n    import yaml\n\n    io = StringIO(initial_value=\"\", newline=\"\\n\")\n    yaml.dump(self.to_jsonable(), io, sort_keys=False)\n    return io.getvalue()\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/","title":"CorrelationId","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId","title":"faststream.asyncapi.schema.message.CorrelationId","text":"

Bases: BaseModel

A class to represent a correlation ID.

Configurations

extra : allows extra fields in the correlation ID model

","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId.location","title":"location instance-attribute","text":"
location: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/CorrelationId/#faststream.asyncapi.schema.message.CorrelationId.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/","title":"Message","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message","title":"faststream.asyncapi.schema.message.Message","text":"

Bases: BaseModel

A class to represent a message.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.contentType","title":"contentType class-attribute instance-attribute","text":"
contentType: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.correlationId","title":"correlationId class-attribute instance-attribute","text":"
correlationId: Optional[CorrelationId] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.messageId","title":"messageId class-attribute instance-attribute","text":"
messageId: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.payload","title":"payload instance-attribute","text":"
payload: Dict[str, Any]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.summary","title":"summary class-attribute instance-attribute","text":"
summary: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[List[Union[Tag, Dict[str, Any]]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/message/Message/#faststream.asyncapi.schema.message.Message.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/","title":"Operation","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation","title":"faststream.asyncapi.schema.operations.Operation","text":"

Bases: BaseModel

A class to represent an operation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[OperationBinding] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict, Dict[str, Any]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.message","title":"message instance-attribute","text":"
message: Union[Message, Reference]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.operationId","title":"operationId class-attribute instance-attribute","text":"
operationId: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.security","title":"security class-attribute instance-attribute","text":"
security: Optional[Dict[str, List[str]]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.summary","title":"summary class-attribute instance-attribute","text":"
summary: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/operations/Operation/#faststream.asyncapi.schema.operations.Operation.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/","title":"OauthFlowObj","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj","title":"faststream.asyncapi.schema.security.OauthFlowObj","text":"

Bases: BaseModel

A class to represent an OAuth flow object.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.authorizationUrl","title":"authorizationUrl class-attribute instance-attribute","text":"
authorizationUrl: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.refreshUrl","title":"refreshUrl class-attribute instance-attribute","text":"
refreshUrl: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.scopes","title":"scopes instance-attribute","text":"
scopes: Dict[str, str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.tokenUrl","title":"tokenUrl class-attribute instance-attribute","text":"
tokenUrl: Optional[AnyHttpUrl] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlowObj/#faststream.asyncapi.schema.security.OauthFlowObj.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/","title":"OauthFlows","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows","title":"faststream.asyncapi.schema.security.OauthFlows","text":"

Bases: BaseModel

A class to represent OAuth flows.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.authorizationCode","title":"authorizationCode class-attribute instance-attribute","text":"
authorizationCode: Optional[OauthFlowObj] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.clientCredentials","title":"clientCredentials class-attribute instance-attribute","text":"
clientCredentials: Optional[OauthFlowObj] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.implicit","title":"implicit class-attribute instance-attribute","text":"
implicit: Optional[OauthFlowObj] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.password","title":"password class-attribute instance-attribute","text":"
password: Optional[OauthFlowObj] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/OauthFlows/#faststream.asyncapi.schema.security.OauthFlows.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/","title":"SecuritySchemaComponent","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent","title":"faststream.asyncapi.schema.security.SecuritySchemaComponent","text":"

Bases: BaseModel

A class to represent a security schema component.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.bearerFormat","title":"bearerFormat class-attribute instance-attribute","text":"
bearerFormat: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.flows","title":"flows class-attribute instance-attribute","text":"
flows: Optional[OauthFlows] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.in_","title":"in_ class-attribute instance-attribute","text":"
in_: Optional[str] = Field(default=None, alias='in')\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.openIdConnectUrl","title":"openIdConnectUrl class-attribute instance-attribute","text":"
openIdConnectUrl: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.schema_","title":"schema_ class-attribute instance-attribute","text":"
schema_: Optional[str] = Field(default=None, alias=\"schema\")\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.type","title":"type instance-attribute","text":"
type: Literal[\n    \"userPassword\",\n    \"apikey\",\n    \"X509\",\n    \"symmetricEncryption\",\n    \"asymmetricEncryption\",\n    \"httpApiKey\",\n    \"http\",\n    \"oauth2\",\n    \"openIdConnect\",\n    \"plain\",\n    \"scramSha256\",\n    \"scramSha512\",\n    \"gssapi\",\n]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/security/SecuritySchemaComponent/#faststream.asyncapi.schema.security.SecuritySchemaComponent.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/","title":"Server","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server","title":"faststream.asyncapi.schema.servers.Server","text":"

Bases: BaseModel

A class to represent a server.

Note

The attributes description, protocolVersion, tags, security, variables, and bindings are all optional.

Configurations

If PYDANTIC_V2 is True, the model configuration is set to allow extra attributes. Otherwise, the Config class is defined with the extra attribute set to \"allow\".

","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.bindings","title":"bindings class-attribute instance-attribute","text":"
bindings: Optional[Union[ServerBinding, Reference]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.protocol","title":"protocol instance-attribute","text":"
protocol: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.protocolVersion","title":"protocolVersion class-attribute instance-attribute","text":"
protocolVersion: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.security","title":"security class-attribute instance-attribute","text":"
security: Optional[SecurityRequirement] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[\n    List[Union[Tag, TagDict, Dict[str, Any]]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.variables","title":"variables class-attribute instance-attribute","text":"
variables: Optional[\n    Dict[str, Union[ServerVariable, Reference]]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/Server/#faststream.asyncapi.schema.servers.Server.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/","title":"ServerVariable","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable","title":"faststream.asyncapi.schema.servers.ServerVariable","text":"

Bases: BaseModel

A class to represent a server variable.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.default","title":"default class-attribute instance-attribute","text":"
default: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.enum","title":"enum class-attribute instance-attribute","text":"
enum: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.examples","title":"examples class-attribute instance-attribute","text":"
examples: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/servers/ServerVariable/#faststream.asyncapi.schema.servers.ServerVariable.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/","title":"ExternalDocs","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs","title":"faststream.asyncapi.schema.utils.ExternalDocs","text":"

Bases: BaseModel

A class to represent external documentation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs.url","title":"url instance-attribute","text":"
url: AnyHttpUrl\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocs/#faststream.asyncapi.schema.utils.ExternalDocs.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocsDict/","title":"ExternalDocsDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocsDict/#faststream.asyncapi.schema.utils.ExternalDocsDict","title":"faststream.asyncapi.schema.utils.ExternalDocsDict","text":"

Bases: TypedDict

A dictionary type for representing external documentation.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocsDict/#faststream.asyncapi.schema.utils.ExternalDocsDict.description","title":"description instance-attribute","text":"
description: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/ExternalDocsDict/#faststream.asyncapi.schema.utils.ExternalDocsDict.url","title":"url instance-attribute","text":"
url: Required[AnyHttpUrl]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Parameter/","title":"Parameter","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Parameter/#faststream.asyncapi.schema.utils.Parameter","title":"faststream.asyncapi.schema.utils.Parameter","text":"

Bases: BaseModel

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Reference/","title":"Reference","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Reference/#faststream.asyncapi.schema.utils.Reference","title":"faststream.asyncapi.schema.utils.Reference","text":"

Bases: BaseModel

A class to represent a reference.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Reference/#faststream.asyncapi.schema.utils.Reference.ref","title":"ref class-attribute instance-attribute","text":"
ref: str = Field(..., alias='$ref')\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/","title":"Tag","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag","title":"faststream.asyncapi.schema.utils.Tag","text":"

Bases: BaseModel

A class to represent a tag.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.externalDocs","title":"externalDocs class-attribute instance-attribute","text":"
externalDocs: Optional[\n    Union[ExternalDocs, ExternalDocsDict]\n] = None\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'extra': 'allow'}\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/Tag/#faststream.asyncapi.schema.utils.Tag.Config.extra","title":"extra class-attribute instance-attribute","text":"
extra = 'allow'\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/TagDict/","title":"TagDict","text":"","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/TagDict/#faststream.asyncapi.schema.utils.TagDict","title":"faststream.asyncapi.schema.utils.TagDict","text":"

Bases: TypedDict

A dictionary-like class for storing tags.

","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/TagDict/#faststream.asyncapi.schema.utils.TagDict.description","title":"description instance-attribute","text":"
description: str\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/TagDict/#faststream.asyncapi.schema.utils.TagDict.externalDocs","title":"externalDocs instance-attribute","text":"
externalDocs: Union[ExternalDocs, ExternalDocsDict]\n
","boost":0.5},{"location":"api/faststream/asyncapi/schema/utils/TagDict/#faststream.asyncapi.schema.utils.TagDict.name","title":"name instance-attribute","text":"
name: Required[str]\n
","boost":0.5},{"location":"api/faststream/asyncapi/site/get_asyncapi_html/","title":"get_asyncapi_html","text":"","boost":0.5},{"location":"api/faststream/asyncapi/site/get_asyncapi_html/#faststream.asyncapi.site.get_asyncapi_html","title":"faststream.asyncapi.site.get_asyncapi_html","text":"
get_asyncapi_html(\n    schema: Schema,\n    sidebar: bool = True,\n    info: bool = True,\n    servers: bool = True,\n    operations: bool = True,\n    messages: bool = True,\n    schemas: bool = True,\n    errors: bool = True,\n    expand_message_examples: bool = True,\n    title: str = \"FastStream\",\n) -> str\n

Generate HTML for displaying an AsyncAPI document.

PARAMETER DESCRIPTION schema

The AsyncAPI schema object.

TYPE: Schema

sidebar

Whether to show the sidebar. Defaults to True.

TYPE: bool DEFAULT: True

info

Whether to show the info section. Defaults to True.

TYPE: bool DEFAULT: True

servers

Whether to show the servers section. Defaults to True.

TYPE: bool DEFAULT: True

operations

Whether to show the operations section. Defaults to True.

TYPE: bool DEFAULT: True

messages

Whether to show the messages section. Defaults to True.

TYPE: bool DEFAULT: True

schemas

Whether to show the schemas section. Defaults to True.

TYPE: bool DEFAULT: True

errors

Whether to show the errors section. Defaults to True.

TYPE: bool DEFAULT: True

expand_message_examples

Whether to expand message examples. Defaults to True.

TYPE: bool DEFAULT: True

title

The title of the HTML document. Defaults to \"FastStream\".

TYPE: str DEFAULT: 'FastStream'

RETURNS DESCRIPTION str

The generated HTML document.

TYPE: str

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/asyncapi/site.py
def get_asyncapi_html(\n    schema: \"Schema\",\n    sidebar: bool = True,\n    info: bool = True,\n    servers: bool = True,\n    operations: bool = True,\n    messages: bool = True,\n    schemas: bool = True,\n    errors: bool = True,\n    expand_message_examples: bool = True,\n    title: str = \"FastStream\",\n) -> str:\n    \"\"\"Generate HTML for displaying an AsyncAPI document.\n\n    Args:\n        schema (Schema): The AsyncAPI schema object.\n        sidebar (bool, optional): Whether to show the sidebar. Defaults to True.\n        info (bool, optional): Whether to show the info section. Defaults to True.\n        servers (bool, optional): Whether to show the servers section. Defaults to True.\n        operations (bool, optional): Whether to show the operations section. Defaults to True.\n        messages (bool, optional): Whether to show the messages section. Defaults to True.\n        schemas (bool, optional): Whether to show the schemas section. Defaults to True.\n        errors (bool, optional): Whether to show the errors section. Defaults to True.\n        expand_message_examples (bool, optional): Whether to expand message examples. Defaults to True.\n        title (str, optional): The title of the HTML document. Defaults to \"FastStream\".\n\n    Returns:\n        str: The generated HTML document.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    schema_json = schema.to_json()\n\n    config = {\n        \"schema\": schema_json,\n        \"config\": {\n            \"show\": {\n                \"sidebar\": sidebar,\n                \"info\": info,\n                \"servers\": servers,\n                \"operations\": operations,\n                \"messages\": messages,\n                \"schemas\": schemas,\n                \"errors\": errors,\n            },\n            \"expand\": {\n                \"messageExamples\": expand_message_examples,\n            },\n            \"sidebar\": {\n                \"showServers\": \"byDefault\",\n                \"showOperations\": \"byDefault\",\n            },\n        },\n    }\n\n    return (\n        \"\"\"\n    <!DOCTYPE html>\n    <html>\n        <head>\n    \"\"\"\n        f\"\"\"\n        <title>{title} AsyncAPI</title>\n    \"\"\"\n        \"\"\"\n        <link rel=\"icon\" href=\"https://www.asyncapi.com/favicon.ico\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"16x16\" href=\"https://www.asyncapi.com/favicon-16x16.png\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"32x32\" href=\"https://www.asyncapi.com/favicon-32x32.png\">\n        <link rel=\"icon\" type=\"image/png\" sizes=\"194x194\" href=\"https://www.asyncapi.com/favicon-194x194.png\">\n        <link rel=\"stylesheet\" href=\"https://unpkg.com/@asyncapi/react-component@1.0.0-next.46/styles/default.min.css\">\n        </head>\n\n        <style>\n        html {\n            font-family: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;\n            line-height: 1.5;\n        }\n        </style>\n\n        <body>\n        <div id=\"asyncapi\"></div>\n\n        <script src=\"https://unpkg.com/@asyncapi/react-component@1.0.0-next.47/browser/standalone/index.js\"></script>\n        <script>\n    \"\"\"\n        f\"\"\"\n            AsyncApiStandalone.render({json.dumps(config)}, document.getElementById('asyncapi'));\n    \"\"\"\n        \"\"\"\n        </script>\n        </body>\n    </html>\n    \"\"\"\n    )\n
","boost":0.5},{"location":"api/faststream/asyncapi/site/serve_app/","title":"serve_app","text":"","boost":0.5},{"location":"api/faststream/asyncapi/site/serve_app/#faststream.asyncapi.site.serve_app","title":"faststream.asyncapi.site.serve_app","text":"
serve_app(schema: Schema, host: str, port: int) -> None\n

Serve the FastAPI application.

PARAMETER DESCRIPTION schema

The schema object representing the API specification.

TYPE: Schema

host

The host address to run the application on.

TYPE: str

port

The port number to run the application on.

TYPE: int

RETURNS DESCRIPTION None

None

Source code in faststream/asyncapi/site.py
def serve_app(\n    schema: \"Schema\",\n    host: str,\n    port: int,\n) -> None:\n    \"\"\"Serve the FastAPI application.\n\n    Args:\n        schema: The schema object representing the API specification.\n        host: The host address to run the application on.\n        port: The port number to run the application on.\n\n    Returns:\n        None\n\n    \"\"\"\n    import uvicorn\n    from fastapi import FastAPI\n    from fastapi.responses import HTMLResponse\n\n    app = FastAPI()\n\n    @app.get(\"/\")\n    def asyncapi(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:  # pragma: no cover\n        \"\"\"Generate an AsyncAPI HTML response.\n\n        Args:\n            sidebar (bool): Whether to include the sidebar. Default is True.\n            info (bool): Whether to include the info section. Default is True.\n            servers (bool): Whether to include the servers section. Default is True.\n            operations (bool): Whether to include the operations section. Default is True.\n            messages (bool): Whether to include the messages section. Default is True.\n            schemas (bool): Whether to include the schemas section. Default is True.\n            errors (bool): Whether to include the errors section. Default is True.\n            expandMessageExamples (bool): Whether to expand message examples. Default is True.\n\n        Returns:\n            HTMLResponse: The generated HTML response.\n\n        \"\"\"\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=schema.info.title,\n            )\n        )\n\n    uvicorn.run(app, host=host, port=port)\n
","boost":0.5},{"location":"api/faststream/asyncapi/utils/resolve_payloads/","title":"resolve_payloads","text":"","boost":0.5},{"location":"api/faststream/asyncapi/utils/resolve_payloads/#faststream.asyncapi.utils.resolve_payloads","title":"faststream.asyncapi.utils.resolve_payloads","text":"
resolve_payloads(\n    payloads: List[Tuple[AnyDict, str]],\n    extra: str = \"\",\n    served_words: int = 1,\n) -> AnyDict\n

Resolve payloads.

PARAMETER DESCRIPTION payloads

A list of dictionaries representing payloads.

TYPE: List[Tuple[AnyDict, str]]

RETURNS DESCRIPTION AnyDict

A dictionary representing the resolved payload.

Source code in faststream/asyncapi/utils.py
def resolve_payloads(\n    payloads: List[Tuple[AnyDict, str]],\n    extra: str = \"\",\n    served_words: int = 1,\n) -> AnyDict:\n    \"\"\"Resolve payloads.\n\n    Args:\n        payloads: A list of dictionaries representing payloads.\n\n    Returns:\n        A dictionary representing the resolved payload.\n\n    \"\"\"\n    ln = len(payloads)\n    payload: AnyDict\n    if ln > 1:\n        one_of_payloads = {}\n\n        for body, handler_name in payloads:\n            title = body[\"title\"]\n            words = title.split(\":\")\n\n            if len(words) > 1:  # not pydantic model case\n                body[\"title\"] = title = \":\".join(\n                    filter(\n                        lambda x: bool(x),\n                        (\n                            handler_name,\n                            extra if extra not in words else \"\",\n                            *words[served_words:],\n                        ),\n                    )\n                )\n\n            one_of_payloads[title] = body\n\n        payload = {\"oneOf\": one_of_payloads}\n\n    elif ln == 1:\n        payload = payloads[0][0]\n\n    else:\n        payload = {}\n\n    return payload\n
","boost":0.5},{"location":"api/faststream/asyncapi/utils/to_camelcase/","title":"to_camelcase","text":"","boost":0.5},{"location":"api/faststream/asyncapi/utils/to_camelcase/#faststream.asyncapi.utils.to_camelcase","title":"faststream.asyncapi.utils.to_camelcase","text":"
to_camelcase(*names: str) -> str\n

Converts a list of names to camel case.

PARAMETER DESCRIPTION *names

Variable length list of names to be converted to camel case.

TYPE: str DEFAULT: ()

RETURNS DESCRIPTION str

The camel case representation of the names.

Example

to_camelcase(\"hello_world\") \"HelloWorld\"

Source code in faststream/asyncapi/utils.py
def to_camelcase(*names: str) -> str:\n    \"\"\"Converts a list of names to camel case.\n\n    Args:\n        *names: Variable length list of names to be converted to camel case.\n\n    Returns:\n        The camel case representation of the names.\n\n    Example:\n        >>> to_camelcase(\"hello_world\")\n        \"HelloWorld\"\n\n    \"\"\"\n    return \" \".join(names).replace(\"_\", \" \").title().replace(\" \", \"\")\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/","title":"BrokerUsecase","text":"","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase","title":"faststream.broker.core.abc.BrokerUsecase","text":"
BrokerUsecase(\n    url: Union[str, List[str]],\n    *args: Any,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = None,\n    description: Optional[str] = None,\n    tags: Optional[\n        Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]\n    ] = None,\n    asyncapi_url: Union[str, List[str], None] = None,\n    apply_types: bool = True,\n    validate: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[\n        str\n    ] = \"%(asctime)s %(levelname)s - %(message)s\",\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[Callable[[MsgType], BaseMiddleware]]\n    ] = None,\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: ABC, Generic[MsgType, ConnectionType], LoggingMixin

A class representing a broker use case.

METHOD DESCRIPTION __init__

constructor method

include_router

include a router in the broker

include_routers

include multiple routers in the broker

_resolve_connection_kwargs

resolve connection kwargs

_wrap_handler

wrap a handler function

_abc_start

start the broker

_abc_close

close the broker

_abc__close

close the broker connection

_process_message

process a message

subscriber

decorator to register a subscriber

publisher

register a publisher

_wrap_decode_message

wrap a message decoding function

Initialize a broker.

PARAMETER DESCRIPTION url

The URL or list of URLs to connect to.

TYPE: Union[str, List[str]]

*args

Additional arguments.

TYPE: Any DEFAULT: ()

protocol

The protocol to use for the connection.

TYPE: Optional[str] DEFAULT: None

protocol_version

The version of the protocol.

TYPE: Optional[str] DEFAULT: None

description

A description of the broker.

TYPE: Optional[str] DEFAULT: None

tags

Tags associated with the broker.

TYPE: Optional[Sequence[Union[Tag, TagDict]]] DEFAULT: None

apply_types

Whether to apply types to messages.

TYPE: bool DEFAULT: True

validate

Whether to cast types using Pydantic validation.

TYPE: bool DEFAULT: True

logger

The logger to use.

TYPE: Optional[Logger] DEFAULT: access_logger

log_level

The log level to use.

TYPE: int DEFAULT: INFO

log_fmt

The log format to use.

TYPE: Optional[str] DEFAULT: '%(asctime)s %(levelname)s - %(message)s'

dependencies

Dependencies of the broker.

TYPE: Sequence[Depends] DEFAULT: ()

middlewares

Middlewares to use.

TYPE: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] DEFAULT: None

decoder

Custom decoder for messages.

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

parser

Custom parser for messages.

TYPE: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/core/abc.py
def __init__(\n    self,\n    url: Union[str, List[str]],\n    *args: Any,\n    # AsyncAPI kwargs\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = None,\n    description: Optional[str] = None,\n    tags: Optional[Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]] = None,\n    asyncapi_url: Union[str, List[str], None] = None,\n    # broker kwargs\n    apply_types: bool = True,\n    validate: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = \"%(asctime)s %(levelname)s - %(message)s\",\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] = None,\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a broker.\n\n    Args:\n        url: The URL or list of URLs to connect to.\n        *args: Additional arguments.\n        protocol: The protocol to use for the connection.\n        protocol_version: The version of the protocol.\n        description: A description of the broker.\n        tags: Tags associated with the broker.\n        apply_types: Whether to apply types to messages.\n        validate: Whether to cast types using Pydantic validation.\n        logger: The logger to use.\n        log_level: The log level to use.\n        log_fmt: The log format to use.\n        dependencies: Dependencies of the broker.\n        middlewares: Middlewares to use.\n        decoder: Custom decoder for messages.\n        parser: Custom parser for messages.\n        **kwargs: Additional keyword arguments.\n\n    \"\"\"\n    super().__init__(\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n    )\n\n    self._connection = None\n    self._is_apply_types = apply_types\n    self._is_validate = validate\n    self.handlers = {}\n    self._publishers = {}\n    empty_middleware: Sequence[Callable[[MsgType], BaseMiddleware]] = ()\n    midd_args: Sequence[Callable[[MsgType], BaseMiddleware]] = (\n        middlewares or empty_middleware\n    )\n    self.middlewares = [CriticalLogMiddleware(logger, log_level), *midd_args]\n    self.dependencies = dependencies\n\n    self._connection_args = (url, *args)\n    self._connection_kwargs = kwargs\n\n    self._global_parser = parser\n    self._global_decoder = decoder\n\n    context.set_global(\"logger\", logger)\n    context.set_global(\"broker\", self)\n\n    self.started = False\n\n    # AsyncAPI information\n    self.url = asyncapi_url or url\n    self.protocol = protocol\n    self.protocol_version = protocol_version\n    self.description = description\n    self.tags = tags\n    self.security = security\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.handlers","title":"handlers instance-attribute","text":"
handlers: Mapping[Any, BaseHandler[MsgType]] = {}\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[Any], BaseMiddleware]] = [\n    CriticalLogMiddleware(logger, log_level),\n    *midd_args,\n]\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.url","title":"url instance-attribute","text":"
url = asyncapi_url or url\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.publisher","title":"publisher abstractmethod","text":"
publisher(\n    key: Any, publisher: BasePublisher[MsgType]\n) -> BasePublisher[MsgType]\n

Publishes a publisher.

PARAMETER DESCRIPTION key

The key associated with the publisher.

TYPE: Any

publisher

The publisher to be published.

TYPE: BasePublisher[MsgType]

RETURNS DESCRIPTION BasePublisher[MsgType]

The published publisher.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/abc.py
@abstractmethod\ndef publisher(\n    self,\n    key: Any,\n    publisher: BasePublisher[MsgType],\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a publisher.\n\n    Args:\n        key: The key associated with the publisher.\n        publisher: The publisher to be published.\n\n    Returns:\n        The published publisher.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    self._publishers = {**self._publishers, key: publisher}\n    return publisher\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/BrokerUsecase/#faststream.broker.core.abc.BrokerUsecase.subscriber","title":"subscriber abstractmethod","text":"
subscriber(\n    *broker_args: Any,\n    retry: Union[bool, int] = False,\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Filter[\n        StreamMessage[MsgType]\n    ] = lambda: not m.processed,\n    _raw: bool = False,\n    _get_dependant: Optional[Any] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [\n        Union[\n            Callable[P_HandlerParams, T_HandlerReturn],\n            HandlerCallWrapper[\n                MsgType, P_HandlerParams, T_HandlerReturn\n            ],\n        ]\n    ],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

This is a function decorator for subscribing to a message broker.

PARAMETER DESCRIPTION *broker_args

Positional arguments to be passed to the broker.

TYPE: Any DEFAULT: ()

retry

Whether to retry the subscription if it fails. Can be a boolean or an integer specifying the number of retries.

TYPE: Union[bool, int] DEFAULT: False

dependencies

Sequence of dependencies to be injected into the handler function.

TYPE: Sequence[Depends] DEFAULT: ()

decoder

Custom decoder function to decode the message.

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

parser

Custom parser function to parse the decoded message.

TYPE: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] DEFAULT: None

middlewares

Sequence of middleware functions to be applied to the message.

TYPE: Optional[Sequence[Callable[[StreamMessage[MsgType]], BaseMiddleware]]] DEFAULT: None

filter

Filter function to filter the messages to be processed.

TYPE: Filter[StreamMessage[MsgType]] DEFAULT: lambda : not processed

_raw

Whether to return the raw message instead of the processed message.

TYPE: bool DEFAULT: False

_get_dependant

Optional parameter to get the dependant object.

TYPE: Optional[Any] DEFAULT: None

**broker_kwargs

Keyword arguments to be passed to the broker.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Callable[[Union[Callable[P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable object that can be used as a decorator for a handler function.

RAISES DESCRIPTION RuntimeWarning

If the broker is already running.

Source code in faststream/broker/core/abc.py
@abstractmethod\ndef subscriber(  # type: ignore[return]\n    self,\n    *broker_args: Any,\n    retry: Union[bool, int] = False,\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                BaseMiddleware,\n            ]\n        ]\n    ] = None,\n    filter: Filter[StreamMessage[MsgType]] = lambda m: not m.processed,\n    _raw: bool = False,\n    _get_dependant: Optional[Any] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [\n        Union[\n            Callable[P_HandlerParams, T_HandlerReturn],\n            HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n        ]\n    ],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"This is a function decorator for subscribing to a message broker.\n\n    Args:\n        *broker_args: Positional arguments to be passed to the broker.\n        retry: Whether to retry the subscription if it fails. Can be a boolean or an integer specifying the number of retries.\n        dependencies: Sequence of dependencies to be injected into the handler function.\n        decoder: Custom decoder function to decode the message.\n        parser: Custom parser function to parse the decoded message.\n        middlewares: Sequence of middleware functions to be applied to the message.\n        filter: Filter function to filter the messages to be processed.\n        _raw: Whether to return the raw message instead of the processed message.\n        _get_dependant: Optional parameter to get the dependant object.\n        **broker_kwargs: Keyword arguments to be passed to the broker.\n\n    Returns:\n        A callable object that can be used as a decorator for a handler function.\n\n    Raises:\n        RuntimeWarning: If the broker is already running.\n\n    \"\"\"\n    if self.started and not is_test_env():  # pragma: no cover\n        warnings.warn(\n            \"You are trying to register `handler` with already running broker\\n\"  # noqa: E501\n            \"It has no effect until broker restarting.\",  # noqa: E501\n            category=RuntimeWarning,\n            stacklevel=1,\n        )\n
","boost":0.5},{"location":"api/faststream/broker/core/abc/extend_dependencies/","title":"extend_dependencies","text":"","boost":0.5},{"location":"api/faststream/broker/core/abc/extend_dependencies/#faststream.broker.core.abc.extend_dependencies","title":"faststream.broker.core.abc.extend_dependencies","text":"
extend_dependencies(\n    extra: Sequence[CallModel[Any, Any]],\n    dependant: CallModel[Any, Any],\n) -> CallModel[Any, Any]\n

Extends the dependencies of a function or FastAPI dependency.

PARAMETER DESCRIPTION extra

Additional dependencies to be added.

TYPE: Sequence[CallModel[Any, Any]]

dependant

The function or FastAPI dependency whose dependencies will be extended.

TYPE: CallModel[Any, Any]

RETURNS DESCRIPTION CallModel[Any, Any]

The updated function or FastAPI dependency.

Source code in faststream/broker/core/abc.py
def extend_dependencies(\n    extra: Sequence[CallModel[Any, Any]], dependant: CallModel[Any, Any]\n) -> CallModel[Any, Any]:\n    \"\"\"Extends the dependencies of a function or FastAPI dependency.\n\n    Args:\n        extra: Additional dependencies to be added.\n        dependant: The function or FastAPI dependency whose dependencies will be extended.\n\n    Returns:\n        The updated function or FastAPI dependency.\n\n    \"\"\"\n    if isinstance(dependant, CallModel):\n        dependant.extra_dependencies = (*dependant.extra_dependencies, *extra)\n    else:  # FastAPI dependencies\n        dependant.dependencies.extend(extra)\n    return dependant\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/","title":"BrokerAsyncUsecase","text":"","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase","title":"faststream.broker.core.asyncronous.BrokerAsyncUsecase","text":"
BrokerAsyncUsecase(\n    *args: Any,\n    apply_types: bool = True,\n    validate: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[\n        str\n    ] = \"%(asctime)s %(levelname)s - %(message)s\",\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    middlewares: Optional[\n        Sequence[Callable[[MsgType], BaseMiddleware]]\n    ] = None,\n    graceful_timeout: Optional[float] = None,\n    **kwargs: Any\n)\n

Bases: BrokerUsecase[MsgType, ConnectionType]

A class representing a broker async usecase.

METHOD DESCRIPTION start

Abstract method to start the broker async usecase.

_connect

Any) : Abstract method to connect to the broker.

_close

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) : Abstract method to close the connection to the broker.

close

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) : Close the connection to the broker.

_process_message

Callable[[StreamMessage[MsgType]], Awaitable[T_HandlerReturn]], watcher: BaseWatcher) : Abstract method to process a message.

publish

SendableMessage, *args: Any, reply_to: str = \"\", rpc: bool = False, rpc_timeout: Optional[float]

Initialize the class.

PARAMETER DESCRIPTION *args

Variable length arguments

TYPE: Any DEFAULT: ()

apply_types

Whether to apply types or not

TYPE: bool DEFAULT: True

validate

Whether to cast types using Pydantic validation.

TYPE: bool DEFAULT: True

logger

Logger object for logging

TYPE: Optional[Logger] DEFAULT: access_logger

log_level

Log level for logging

TYPE: int DEFAULT: INFO

log_fmt

Log format for logging

TYPE: Optional[str] DEFAULT: '%(asctime)s %(levelname)s - %(message)s'

dependencies

Sequence of dependencies

TYPE: Sequence[Depends] DEFAULT: ()

decoder

Custom decoder object

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

parser

Custom parser object

TYPE: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] DEFAULT: None

middlewares

Sequence of middlewares

TYPE: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] DEFAULT: None

**kwargs

Keyword arguments

TYPE: Any DEFAULT: {}

Source code in faststream/broker/core/asyncronous.py
def __init__(\n    self,\n    *args: Any,\n    apply_types: bool = True,\n    validate: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = \"%(asctime)s %(levelname)s - %(message)s\",\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    middlewares: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] = None,\n    graceful_timeout: Optional[float] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        *args: Variable length arguments\n        apply_types: Whether to apply types or not\n        validate: Whether to cast types using Pydantic validation.\n        logger: Logger object for logging\n        log_level: Log level for logging\n        log_fmt: Log format for logging\n        dependencies: Sequence of dependencies\n        decoder: Custom decoder object\n        parser: Custom parser object\n        middlewares: Sequence of middlewares\n        **kwargs: Keyword arguments\n\n    \"\"\"\n    super().__init__(\n        *args,\n        apply_types=apply_types,\n        validate=validate,\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n        dependencies=dependencies,\n        decoder=cast(\n            Optional[AsyncCustomDecoder[StreamMessage[MsgType]]],\n            to_async(decoder) if decoder else None,\n        ),\n        parser=cast(\n            Optional[AsyncCustomParser[MsgType, StreamMessage[MsgType]]],\n            to_async(parser) if parser else None,\n        ),\n        middlewares=middlewares,\n        **kwargs,\n    )\n    self.graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.handlers","title":"handlers instance-attribute","text":"
handlers: Mapping[Any, AsyncHandler[MsgType]]\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.url","title":"url instance-attribute","text":"
url = asyncapi_url or url\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.connect","title":"connect async","text":"
connect(*args: Any, **kwargs: Any) -> ConnectionType\n

Connect to a remote server.

PARAMETER DESCRIPTION *args

Variable length argument list.

TYPE: Any DEFAULT: ()

**kwargs

Arbitrary keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION ConnectionType

The connection object.

Source code in faststream/broker/core/asyncronous.py
async def connect(self, *args: Any, **kwargs: Any) -> ConnectionType:\n    \"\"\"Connect to a remote server.\n\n    Args:\n        *args: Variable length argument list.\n        **kwargs: Arbitrary keyword arguments.\n\n    Returns:\n        The connection object.\n\n    \"\"\"\n    if self._connection is None:\n        _kwargs = self._resolve_connection_kwargs(*args, **kwargs)\n        self._connection = await self._connect(**_kwargs)\n    return self._connection\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.publish","title":"publish abstractmethod async","text":"
publish(\n    message: SendableMessage,\n    *args: Any,\n    reply_to: str = \"\",\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

*args

Additional arguments.

TYPE: Any DEFAULT: ()

reply_to

The reply-to address for the message.

TYPE: str DEFAULT: ''

rpc

Whether the message is for RPC.

TYPE: bool DEFAULT: False

rpc_timeout

The timeout for RPC.

TYPE: Optional[float] DEFAULT: None

raise_timeout

Whether to raise an exception on timeout.

TYPE: bool DEFAULT: False

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
@abstractmethod\nasync def publish(\n    self,\n    message: SendableMessage,\n    *args: Any,\n    reply_to: str = \"\",\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        *args: Additional arguments.\n        reply_to: The reply-to address for the message.\n        rpc: Whether the message is for RPC.\n        rpc_timeout: The timeout for RPC.\n        raise_timeout: Whether to raise an exception on timeout.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.publisher","title":"publisher abstractmethod","text":"
publisher(\n    key: Any, publisher: BasePublisher[MsgType]\n) -> BasePublisher[MsgType]\n

Publishes a publisher.

PARAMETER DESCRIPTION key

The key associated with the publisher.

TYPE: Any

publisher

The publisher to be published.

TYPE: BasePublisher[MsgType]

RETURNS DESCRIPTION BasePublisher[MsgType]

The published publisher.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/abc.py
@abstractmethod\ndef publisher(\n    self,\n    key: Any,\n    publisher: BasePublisher[MsgType],\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a publisher.\n\n    Args:\n        key: The key associated with the publisher.\n        publisher: The publisher to be published.\n\n    Returns:\n        The published publisher.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    self._publishers = {**self._publishers, key: publisher}\n    return publisher\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.start","title":"start abstractmethod async","text":"
start() -> None\n
Source code in faststream/broker/core/asyncronous.py
@abstractmethod\nasync def start(self) -> None:\n    super()._abc_start()\n    for h in self.handlers.values():\n        for f, _, _, _, _, _ in h.calls:\n            f.refresh(with_mock=False)\n    await self.connect()\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/BrokerAsyncUsecase/#faststream.broker.core.asyncronous.BrokerAsyncUsecase.subscriber","title":"subscriber abstractmethod","text":"
subscriber(\n    *broker_args: Any,\n    retry: Union[bool, int] = False,\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    middlewares: Optional[\n        Sequence[Callable[[MsgType], BaseMiddleware]]\n    ] = None,\n    filter: Filter[StreamMessage[MsgType]] = default_filter,\n    _raw: bool = False,\n    _get_dependant: Optional[Any] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [\n        Union[\n            Callable[P_HandlerParams, T_HandlerReturn],\n            HandlerCallWrapper[\n                MsgType, P_HandlerParams, T_HandlerReturn\n            ],\n        ]\n    ],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function decorator for subscribing to a message broker.

PARAMETER DESCRIPTION *broker_args

Positional arguments to be passed to the message broker.

TYPE: Any DEFAULT: ()

retry

Whether to retry the subscription if it fails. Can be a boolean or an integer specifying the number of retries.

TYPE: Union[bool, int] DEFAULT: False

dependencies

Sequence of dependencies to be injected into the decorated function.

TYPE: Sequence[Depends] DEFAULT: ()

decoder

Custom decoder function for decoding the message.

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

parser

Custom parser function for parsing the decoded message.

TYPE: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] DEFAULT: None

middlewares

Sequence of middleware functions to be applied to the message.

TYPE: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] DEFAULT: None

filter

Filter function for filtering the messages to be processed.

TYPE: Filter[StreamMessage[MsgType]] DEFAULT: default_filter

_raw

Whether to return the raw message instead of the processed result.

TYPE: bool DEFAULT: False

_get_dependant

Optional argument to get the dependant object.

TYPE: Optional[Any] DEFAULT: None

RETURNS DESCRIPTION Callable[[Union[Callable[P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable decorator that wraps the decorated function and handles the subscription.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/core/asyncronous.py
@override\n@abstractmethod\ndef subscriber(  # type: ignore[override,return]\n    self,\n    *broker_args: Any,\n    retry: Union[bool, int] = False,\n    dependencies: Sequence[Depends] = (),\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    middlewares: Optional[Sequence[Callable[[MsgType], BaseMiddleware]]] = None,\n    filter: Filter[StreamMessage[MsgType]] = default_filter,\n    _raw: bool = False,\n    _get_dependant: Optional[Any] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [\n        Union[\n            Callable[P_HandlerParams, T_HandlerReturn],\n            HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n        ]\n    ],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function decorator for subscribing to a message broker.\n\n    Args:\n        *broker_args: Positional arguments to be passed to the message broker.\n        retry: Whether to retry the subscription if it fails. Can be a boolean or an integer specifying the number of retries.\n        dependencies: Sequence of dependencies to be injected into the decorated function.\n        decoder: Custom decoder function for decoding the message.\n        parser: Custom parser function for parsing the decoded message.\n        middlewares: Sequence of middleware functions to be applied to the message.\n        filter: Filter function for filtering the messages to be processed.\n        _raw: Whether to return the raw message instead of the processed result.\n        _get_dependant: Optional argument to get the dependant object.\n\n    Returns:\n        A callable decorator that wraps the decorated function and handles the subscription.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    super().subscriber()\n
","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/default_filter/","title":"default_filter","text":"","boost":0.5},{"location":"api/faststream/broker/core/asyncronous/default_filter/#faststream.broker.core.asyncronous.default_filter","title":"faststream.broker.core.asyncronous.default_filter async","text":"
default_filter(msg: StreamMessage[Any]) -> bool\n

A function to filter stream messages.

PARAMETER DESCRIPTION msg

A stream message object

RETURNS DESCRIPTION bool

True if the message has not been processed, False otherwise

Source code in faststream/broker/core/asyncronous.py
async def default_filter(msg: StreamMessage[Any]) -> bool:\n    \"\"\"A function to filter stream messages.\n\n    Args:\n        msg : A stream message object\n\n    Returns:\n        True if the message has not been processed, False otherwise\n\n    \"\"\"\n    return not msg.processed\n
","boost":0.5},{"location":"api/faststream/broker/core/mixins/LoggingMixin/","title":"LoggingMixin","text":"","boost":0.5},{"location":"api/faststream/broker/core/mixins/LoggingMixin/#faststream.broker.core.mixins.LoggingMixin","title":"faststream.broker.core.mixins.LoggingMixin","text":"
LoggingMixin(\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[\n        str\n    ] = \"%(asctime)s %(levelname)s - %(message)s\",\n    **kwargs: Any\n)\n

A mixin class for logging.

METHOD DESCRIPTION fmt

getter method for _fmt attribute

_get_log_context

returns a dictionary with log context information

_log

logs a message with optional log level, extra data, and exception info

Initialize the class.

PARAMETER DESCRIPTION *args

Variable length argument list

TYPE: Any DEFAULT: ()

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: access_logger

log_level

Log level (default: logging.INFO)

TYPE: int DEFAULT: INFO

log_fmt

Log format (default: \"%(asctime)s %(levelname)s - %(message)s\")

TYPE: Optional[str] DEFAULT: '%(asctime)s %(levelname)s - %(message)s'

**kwargs

Arbitrary keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/mixins.py
def __init__(\n    self,\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = \"%(asctime)s %(levelname)s - %(message)s\",\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        *args: Variable length argument list\n        logger: Optional logger object\n        log_level: Log level (default: logging.INFO)\n        log_fmt: Log format (default: \"%(asctime)s %(levelname)s - %(message)s\")\n        **kwargs: Arbitrary keyword arguments\n\n    Returns:\n        None\n\n    \"\"\"\n    self.logger = logger\n    self.log_level = log_level\n    self._fmt = log_fmt\n    self._message_id_ln = 10\n
","boost":0.5},{"location":"api/faststream/broker/core/mixins/LoggingMixin/#faststream.broker.core.mixins.LoggingMixin.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/broker/core/mixins/LoggingMixin/#faststream.broker.core.mixins.LoggingMixin.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/broker/core/mixins/LoggingMixin/#faststream.broker.core.mixins.LoggingMixin.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/","title":"StreamMessage","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage","title":"faststream.broker.fastapi.StreamMessage","text":"
StreamMessage(\n    *,\n    body: Union[AnyDict, List[Any]],\n    headers: AnyDict,\n    path: AnyDict\n)\n

Bases: Request

A class to represent a stream message.

METHOD DESCRIPTION __init__

initializes the StreamMessage object

get_session

returns a callable function that handles the session of the message

Initialize a class instance.

PARAMETER DESCRIPTION body

The body of the request as a dictionary.

TYPE: Union[AnyDict, List[Any]]

headers

The headers of the request as a dictionary.

TYPE: AnyDict

Source code in faststream/broker/fastapi/route.py
def __init__(\n    self,\n    *,\n    body: Union[AnyDict, List[Any]],\n    headers: AnyDict,\n    path: AnyDict,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        body: The body of the request as a dictionary.\n        headers: The headers of the request as a dictionary.\n\n    Attributes:\n        scope: A dictionary to store the scope of the request.\n        _cookies: A dictionary to store the cookies of the request.\n        _headers: A dictionary to store the headers of the request.\n        _body: A dictionary to store the body of the request.\n        _query_params: A dictionary to store the query parameters of the request.\n\n    \"\"\"\n    self._headers = headers\n    self._body = body\n    self._query_params = path\n\n    self.scope = {\"path_params\": self._query_params}\n    self._cookies = {}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.app","title":"app property","text":"
app: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.auth","title":"auth property","text":"
auth: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.base_url","title":"base_url property","text":"
base_url: URL\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.client","title":"client property","text":"
client: typing.Optional[Address]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.cookies","title":"cookies property","text":"
cookies: typing.Dict[str, str]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.headers","title":"headers property","text":"
headers: Headers\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.method","title":"method property","text":"
method: str\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.path_params","title":"path_params property","text":"
path_params: typing.Dict[str, typing.Any]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.query_params","title":"query_params property","text":"
query_params: QueryParams\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.receive","title":"receive property","text":"
receive: Receive\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.scope","title":"scope instance-attribute","text":"
scope: AnyDict = {'path_params': self._query_params}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.session","title":"session property","text":"
session: typing.Dict[str, typing.Any]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.state","title":"state property","text":"
state: State\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.url","title":"url property","text":"
url: URL\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.user","title":"user property","text":"
user: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.body","title":"body async","text":"
body() -> bytes\n
Source code in starlette/requests.py
async def body(self) -> bytes:\n    if not hasattr(self, \"_body\"):\n        chunks: \"typing.List[bytes]\" = []\n        async for chunk in self.stream():\n            chunks.append(chunk)\n        self._body = b\"\".join(chunks)\n    return self._body\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.close","title":"close async","text":"
close() -> None\n
Source code in starlette/requests.py
async def close(self) -> None:\n    if self._form is not None:\n        await self._form.close()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.form","title":"form","text":"
form(\n    *,\n    max_files: typing.Union[int, float] = 1000,\n    max_fields: typing.Union[int, float] = 1000\n) -> AwaitableOrContextManager[FormData]\n
Source code in starlette/requests.py
def form(\n    self,\n    *,\n    max_files: typing.Union[int, float] = 1000,\n    max_fields: typing.Union[int, float] = 1000,\n) -> AwaitableOrContextManager[FormData]:\n    return AwaitableOrContextManagerWrapper(\n        self._get_form(max_files=max_files, max_fields=max_fields)\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.get_session","title":"get_session classmethod","text":"
get_session(\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[\n    [NativeMessage[Any]], Awaitable[SendableMessage]\n]\n

Creates a session for handling requests.

PARAMETER DESCRIPTION dependant

The dependant object representing the session.

TYPE: Dependant

dependency_overrides_provider

Optional provider for dependency overrides.

TYPE: Optional[Any] DEFAULT: None

RETURNS DESCRIPTION Callable[[StreamMessage[Any]], Awaitable[SendableMessage]]

A callable that takes a native message and returns an awaitable sendable message.

RAISES DESCRIPTION AssertionError

If the dependant call is not defined.

Note

This function is used to create a session for handling requests. It takes a dependant object, which represents the session, and a dependency overrides provider, which allows for overriding dependencies. It returns a callable that takes a native message and returns an awaitable sendable message. The session is created based on the dependant object and the message passed to the callable. The session is then used to call the function obtained from the dependant object, and the result is returned.

Source code in faststream/broker/fastapi/route.py
@classmethod\ndef get_session(\n    cls,\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[[NativeMessage[Any]], Awaitable[SendableMessage]]:\n    \"\"\"Creates a session for handling requests.\n\n    Args:\n        dependant: The dependant object representing the session.\n        dependency_overrides_provider: Optional provider for dependency overrides.\n\n    Returns:\n        A callable that takes a native message and returns an awaitable sendable message.\n\n    Raises:\n        AssertionError: If the dependant call is not defined.\n\n    Note:\n        This function is used to create a session for handling requests. It takes a dependant object, which represents the session, and a dependency overrides provider, which allows for overriding dependencies. It returns a callable that takes a native message and returns an awaitable sendable message. The session is created based on the dependant object and the message passed to the callable. The session is then used to call the function obtained from the dependant object, and the result is returned.\n\n    \"\"\"\n    assert dependant.call  # nosec B101\n\n    func = get_app(dependant, dependency_overrides_provider)\n\n    dependencies_names = tuple(i.name for i in dependant.dependencies)\n\n    first_arg = next(\n        dropwhile(\n            lambda i: i in dependencies_names,\n            inspect.signature(dependant.call).parameters,\n        ),\n        None,\n    )\n\n    async def app(message: NativeMessage[Any]) -> SendableMessage:\n        \"\"\"An asynchronous function that processes an incoming message and returns a sendable message.\n\n        Args:\n            message : The incoming message to be processed\n\n        Returns:\n            The sendable message\n\n        Raises:\n            TypeError: If the body of the message is not a dictionary\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        body = message.decoded_body\n\n        fastapi_body: Union[AnyDict, List[Any]]\n        if first_arg is not None:\n            if isinstance(body, dict):\n                path = fastapi_body = body or {}\n            elif isinstance(body, list):\n                fastapi_body, path = body, {}\n            else:\n                path = fastapi_body = {first_arg: body}\n\n            session = cls(\n                body=fastapi_body,\n                headers=message.headers,\n                path={**path, **message.path},\n            )\n\n        else:\n            session = cls(\n                body={},\n                headers={},\n                path={},\n            )\n\n        return await func(session)\n\n    return app\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.is_disconnected","title":"is_disconnected async","text":"
is_disconnected() -> bool\n
Source code in starlette/requests.py
async def is_disconnected(self) -> bool:\n    if not self._is_disconnected:\n        message: Message = {}\n\n        # If message isn't immediately available, move on\n        with anyio.CancelScope() as cs:\n            cs.cancel()\n            message = await self._receive()\n\n        if message.get(\"type\") == \"http.disconnect\":\n            self._is_disconnected = True\n\n    return self._is_disconnected\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.json","title":"json async","text":"
json() -> typing.Any\n
Source code in starlette/requests.py
async def json(self) -> typing.Any:\n    if not hasattr(self, \"_json\"):\n        body = await self.body()\n        self._json = json.loads(body)\n    return self._json\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.send_push_promise","title":"send_push_promise async","text":"
send_push_promise(path: str) -> None\n
Source code in starlette/requests.py
async def send_push_promise(self, path: str) -> None:\n    if \"http.response.push\" in self.scope.get(\"extensions\", {}):\n        raw_headers: \"typing.List[typing.Tuple[bytes, bytes]]\" = []\n        for name in SERVER_PUSH_HEADERS_TO_COPY:\n            for value in self.headers.getlist(name):\n                raw_headers.append(\n                    (name.encode(\"latin-1\"), value.encode(\"latin-1\"))\n                )\n        await self._send(\n            {\"type\": \"http.response.push\", \"path\": path, \"headers\": raw_headers}\n        )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.stream","title":"stream async","text":"
stream() -> typing.AsyncGenerator[bytes, None]\n
Source code in starlette/requests.py
async def stream(self) -> typing.AsyncGenerator[bytes, None]:\n    if hasattr(self, \"_body\"):\n        yield self._body\n        yield b\"\"\n        return\n    if self._stream_consumed:\n        raise RuntimeError(\"Stream consumed\")\n    self._stream_consumed = True\n    while True:\n        message = await self._receive()\n        if message[\"type\"] == \"http.request\":\n            body = message.get(\"body\", b\"\")\n            if body:\n                yield body\n            if not message.get(\"more_body\", False):\n                break\n        elif message[\"type\"] == \"http.disconnect\":\n            self._is_disconnected = True\n            raise ClientDisconnect()\n    yield b\"\"\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamMessage/#faststream.broker.fastapi.StreamMessage.url_for","title":"url_for","text":"
url_for(__name: str, **path_params: typing.Any) -> URL\n
Source code in starlette/requests.py
def url_for(self, __name: str, **path_params: typing.Any) -> URL:\n    router: Router = self.scope[\"router\"]\n    url_path = router.url_path_for(__name, **path_params)\n    return url_path.make_absolute_url(base_url=self.base_url)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/","title":"StreamRoute","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute","title":"faststream.broker.fastapi.StreamRoute","text":"
StreamRoute(\n    path: Union[NameRequired, str, None],\n    *extra: Union[NameRequired, str],\n    endpoint: Union[\n        Callable[P_HandlerParams, T_HandlerReturn],\n        HandlerCallWrapper[\n            MsgType, P_HandlerParams, T_HandlerReturn\n        ],\n    ],\n    broker: BrokerAsyncUsecase[MsgType, Any],\n    dependencies: Sequence[params.Depends] = (),\n    dependency_overrides_provider: Optional[Any] = None,\n    **handle_kwargs: Any\n)\n

Bases: BaseRoute, Generic[MsgType, P_HandlerParams, T_HandlerReturn]

A class representing a stream route.

Initialize a class instance.

PARAMETER DESCRIPTION path

The path of the instance.

TYPE: Union[NameRequired, str, None]

*extra

Additional arguments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint of the instance.

TYPE: Union[Callable[P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

broker

The broker of the instance.

TYPE: BrokerAsyncUsecase[MsgType, Any]

dependencies

The dependencies of the instance.

TYPE: Sequence[Depends] DEFAULT: ()

dependency_overrides_provider

The provider for dependency overrides.

TYPE: Optional[Any] DEFAULT: None

**handle_kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None.

Source code in faststream/broker/fastapi/route.py
def __init__(\n    self,\n    path: Union[NameRequired, str, None],\n    *extra: Union[NameRequired, str],\n    endpoint: Union[\n        Callable[P_HandlerParams, T_HandlerReturn],\n        HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n    ],\n    broker: BrokerAsyncUsecase[MsgType, Any],\n    dependencies: Sequence[params.Depends] = (),\n    dependency_overrides_provider: Optional[Any] = None,\n    **handle_kwargs: Any,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        path: The path of the instance.\n        *extra: Additional arguments.\n        endpoint: The endpoint of the instance.\n        broker: The broker of the instance.\n        dependencies: The dependencies of the instance.\n        dependency_overrides_provider: The provider for dependency overrides.\n        **handle_kwargs: Additional keyword arguments.\n\n    Returns:\n        None.\n\n    \"\"\"\n    self.path = path or \"\"\n    self.broker = broker\n\n    path_name = self.path if isinstance(self.path, str) else self.path.name\n\n    if isinstance(endpoint, HandlerCallWrapper):\n        orig_call = endpoint._original_call\n    else:\n        orig_call = endpoint\n\n    dependant = get_dependant(\n        path=path_name,\n        call=orig_call,\n    )\n    for depends in dependencies[::-1]:\n        dependant.dependencies.insert(\n            0,\n            get_parameterless_sub_dependant(depends=depends, path=path_name),\n        )\n    self.dependant = dependant\n\n    call = wraps(orig_call)(\n        StreamMessage.get_session(\n            dependant,\n            dependency_overrides_provider,\n        )\n    )\n\n    if isinstance(endpoint, HandlerCallWrapper):\n        endpoint._original_call = call\n        handler = endpoint\n\n    else:\n        handler = call\n\n    self.handler = broker.subscriber(\n        path,\n        *extra,\n        _raw=True,\n        _get_dependant=lambda call: dependant,\n        **handle_kwargs,\n    )(\n        handler  # type: ignore[arg-type]\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.dependant","title":"dependant instance-attribute","text":"
dependant = dependant\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.handler","title":"handler instance-attribute","text":"
handler: HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n] = broker.subscriber(\n    path,\n    *extra,\n    _raw=True,\n    _get_dependant=lambda: dependant,\n    **handle_kwargs\n)(\n    handler\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.path","title":"path instance-attribute","text":"
path = path or ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.handle","title":"handle async","text":"
handle(scope: Scope, receive: Receive, send: Send) -> None\n
Source code in starlette/routing.py
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.matches","title":"matches","text":"
matches(scope: Scope) -> typing.Tuple[Match, Scope]\n
Source code in starlette/routing.py
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRoute/#faststream.broker.fastapi.StreamRoute.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/","title":"StreamRouter","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter","title":"faststream.broker.fastapi.StreamRouter","text":"
StreamRouter(\n    *connection_args: Tuple[Any, ...],\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    setup_state: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id),\n    asyncapi_tags: Optional[\n        Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]\n    ] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    **connection_kwars: Any\n)\n

Bases: APIRouter, Generic[MsgType]

A class to route streams.

METHOD DESCRIPTION __init__

initialize the StreamRouter

add_api_mq_route

add a route for API and message queue

subscriber

decorator to define a subscriber

wrap_lifespan

wrap the lifespan of the router

after_startup

decorator to define a function to be executed after startup

publisher

create a publisher for the broker

asyncapi_router

create an APIRouter for AsyncAPI documentation

include_router

include another router in the StreamRouter

_setup_log_context

setup log context for the broker

Initialize an instance of a class.

PARAMETER DESCRIPTION *connection_args

Variable length arguments for the connection

TYPE: Tuple[Any, ...] DEFAULT: ()

prefix

Prefix for the class

TYPE: str DEFAULT: ''

tags

Optional list of tags for the class

TYPE: Optional[List[Union[str, Enum]]] DEFAULT: None

dependencies

Optional sequence of dependencies for the class

TYPE: Optional[Sequence[Depends]] DEFAULT: None

default_response_class

Default response class for the class

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

Optional dictionary of responses for the class

TYPE: Optional[Dict[Union[int, str], AnyDict]] DEFAULT: None

callbacks

Optional list of callbacks for the class

TYPE: Optional[List[BaseRoute]] DEFAULT: None

routes

Optional list of routes for the class

TYPE: Optional[List[BaseRoute]] DEFAULT: None

redirect_slashes

Boolean value indicating whether to redirect slashes

TYPE: bool DEFAULT: True

default

Optional default value for the class

TYPE: Optional[ASGIApp] DEFAULT: None

dependency_overrides_provider

Optional provider for dependency overrides

TYPE: Optional[Any] DEFAULT: None

route_class

Route class for the class

TYPE: Type[APIRoute] DEFAULT: APIRoute

on_startup

Optional sequence of functions to run on startup

TYPE: Optional[Sequence[Callable[[], Any]]] DEFAULT: None

on_shutdown

Optional sequence of functions to run on shutdown

TYPE: Optional[Sequence[Callable[[], Any]]] DEFAULT: None

deprecated

Optional boolean value indicating whether the class is deprecated

TYPE: Optional[bool] DEFAULT: None

include_in_schema

Boolean value indicating whether to include the class in the schema

TYPE: bool DEFAULT: True

setup_state

Boolean value indicating whether to setup state

TYPE: bool DEFAULT: True

lifespan

Optional lifespan for the class

TYPE: Optional[Lifespan[Any]] DEFAULT: None

generate_unique_id_function

Function to generate unique ID for the class

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

asyncapi_tags

Optional sequence of asyncapi tags for the class schema

TYPE: Optional[Sequence[Union[Tag, TagDict]]] DEFAULT: None

Source code in faststream/broker/fastapi/router.py
def __init__(\n    self,\n    *connection_args: Tuple[Any, ...],\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[Sequence[Callable[[], Any]]] = None,\n    on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    setup_state: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n    # AsyncAPI information\n    asyncapi_tags: Optional[Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    **connection_kwars: Any,\n) -> None:\n    \"\"\"Initialize an instance of a class.\n\n    Args:\n        *connection_args: Variable length arguments for the connection\n        prefix: Prefix for the class\n        tags: Optional list of tags for the class\n        dependencies: Optional sequence of dependencies for the class\n        default_response_class: Default response class for the class\n        responses: Optional dictionary of responses for the class\n        callbacks: Optional list of callbacks for the class\n        routes: Optional list of routes for the class\n        redirect_slashes: Boolean value indicating whether to redirect slashes\n        default: Optional default value for the class\n        dependency_overrides_provider: Optional provider for dependency overrides\n        route_class: Route class for the class\n        on_startup: Optional sequence of functions to run on startup\n        on_shutdown: Optional sequence of functions to run on shutdown\n        deprecated: Optional boolean value indicating whether the class is deprecated\n        include_in_schema: Boolean value indicating whether to include the class in the schema\n        setup_state: Boolean value indicating whether to setup state\n        lifespan: Optional lifespan for the class\n        generate_unique_id_function: Function to generate unique ID for the class\n        asyncapi_tags: Optional sequence of asyncapi tags for the class schema\n\n    \"\"\"\n    assert (  # nosec B101\n        self.broker_class\n    ), \"You should specify `broker_class` at your implementation\"\n\n    self.broker = self.broker_class(\n        *connection_args,\n        apply_types=False,\n        tags=asyncapi_tags,\n        **connection_kwars,\n    )\n\n    self.setup_state = setup_state\n\n    # AsyncAPI information\n    # Empty\n    self.terms_of_service = None\n    self.identifier = None\n    self.asyncapi_tags = None\n    self.external_docs = None\n    # parse from FastAPI app on startup\n    self.title = \"\"\n    self.version = \"\"\n    self.description = \"\"\n    self.license = None\n    self.contact = None\n\n    self.schema = None\n\n    super().__init__(\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        routes=routes,\n        redirect_slashes=redirect_slashes,\n        default=default,\n        dependency_overrides_provider=dependency_overrides_provider,\n        route_class=route_class,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n        lifespan=self.wrap_lifespan(lifespan),\n        on_startup=on_startup,\n        on_shutdown=on_shutdown,\n    )\n\n    self.docs_router = self.asyncapi_router(schema_url)\n\n    self._after_startup_hooks = []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.broker","title":"broker instance-attribute","text":"
broker: BrokerAsyncUsecase[\n    MsgType, Any\n] = self.broker_class(\n    *connection_args,\n    apply_types=False,\n    tags=asyncapi_tags,\n    **connection_kwars\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.broker_class","title":"broker_class instance-attribute","text":"
broker_class: Type[BrokerAsyncUsecase[MsgType, Any]]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any\n) -> HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n]\n

Add an API message queue route.

PARAMETER DESCRIPTION path

The path of the route.

TYPE: Union[NameRequired, str]

*extra

Additional path segments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint function to be called for this route.

TYPE: Callable[P_HandlerParams, T_HandlerReturn]

dependencies

The dependencies required by the endpoint function.

TYPE: Sequence[Depends]

**broker_kwargs

Additional keyword arguments to be passed to the broker.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]

The handler call wrapper for the route.

Source code in faststream/broker/fastapi/router.py
def add_api_mq_route(\n    self,\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any,\n) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n    \"\"\"Add an API message queue route.\n\n    Args:\n        path: The path of the route.\n        *extra: Additional path segments.\n        endpoint: The endpoint function to be called for this route.\n        dependencies: The dependencies required by the endpoint function.\n        **broker_kwargs: Additional keyword arguments to be passed to the broker.\n\n    Returns:\n        The handler call wrapper for the route.\n\n    \"\"\"\n    route: StreamRoute[MsgType, P_HandlerParams, T_HandlerReturn] = StreamRoute(\n        path,\n        *extra,\n        endpoint=endpoint,\n        dependencies=dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        broker=self.broker,\n        **broker_kwargs,\n    )\n    self.routes.append(route)\n    return route.handler\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.publisher","title":"publisher","text":"
publisher(\n    queue: Union[NameRequired, str],\n    *publisher_args: Any,\n    **publisher_kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes messages to a queue.

PARAMETER DESCRIPTION queue

The queue to publish the messages to. Can be either a NameRequired object or a string.

TYPE: Union[NameRequired, str]

*publisher_args

Additional arguments to be passed to the publisher.

TYPE: Any DEFAULT: ()

**publisher_kwargs

Additional keyword arguments to be passed to the publisher.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

An instance of BasePublisher that can be used to publish messages to the specified queue.

Source code in faststream/broker/fastapi/router.py
def publisher(\n    self,\n    queue: Union[NameRequired, str],\n    *publisher_args: Any,\n    **publisher_kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes messages to a queue.\n\n    Args:\n        queue: The queue to publish the messages to. Can be either a `NameRequired` object or a string.\n        *publisher_args: Additional arguments to be passed to the publisher.\n        **publisher_kwargs: Additional keyword arguments to be passed to the publisher.\n\n    Returns:\n        An instance of `BasePublisher` that can be used to publish messages to the specified queue.\n\n    \"\"\"\n    return self.broker.publisher(\n        queue,\n        *publisher_args,\n        **publisher_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.subscriber","title":"subscriber","text":"
subscriber(\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function decorator for subscribing to a message queue.

PARAMETER DESCRIPTION path

The path to subscribe to. Can be a string or a NameRequired object.

*extra

Additional path segments. Can be a NameRequired object or a string.

DEFAULT: ()

dependencies

Optional sequence of dependencies.

DEFAULT: None

**broker_kwargs

Additional keyword arguments for the broker.

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable decorator that adds the decorated function as an endpoint for the specified path.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def subscriber(\n    self,\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function decorator for subscribing to a message queue.\n\n    Args:\n        path : The path to subscribe to. Can be a string or a `NameRequired` object.\n        *extra : Additional path segments. Can be a `NameRequired` object or a string.\n        dependencies : Optional sequence of dependencies.\n        **broker_kwargs : Additional keyword arguments for the broker.\n\n    Returns:\n        A callable decorator that adds the decorated function as an endpoint for the specified path.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    def decorator(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n        \"\"\"A decorator function.\n\n        Args:\n            func: The function to be decorated.\n\n        Returns:\n            The decorated function.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        return self.add_api_mq_route(\n            path,\n            *extra,\n            endpoint=func,\n            dependencies=current_dependencies,\n            **broker_kwargs,\n        )\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/StreamRouter/#faststream.broker.fastapi.StreamRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/context/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/context/Context/#faststream.broker.fastapi.context.Context","title":"faststream.broker.fastapi.context.Context","text":"
Context(name: str) -> Any\n
Source code in faststream/broker/fastapi/context.py
def Context(name: str) -> Any:\n    return params.Depends(\n        lambda: context.resolve(name),\n        use_cache=True,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/","title":"StreamMessage","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage","title":"faststream.broker.fastapi.route.StreamMessage","text":"
StreamMessage(\n    *,\n    body: Union[AnyDict, List[Any]],\n    headers: AnyDict,\n    path: AnyDict\n)\n

Bases: Request

A class to represent a stream message.

METHOD DESCRIPTION __init__

initializes the StreamMessage object

get_session

returns a callable function that handles the session of the message

Initialize a class instance.

PARAMETER DESCRIPTION body

The body of the request as a dictionary.

TYPE: Union[AnyDict, List[Any]]

headers

The headers of the request as a dictionary.

TYPE: AnyDict

Source code in faststream/broker/fastapi/route.py
def __init__(\n    self,\n    *,\n    body: Union[AnyDict, List[Any]],\n    headers: AnyDict,\n    path: AnyDict,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        body: The body of the request as a dictionary.\n        headers: The headers of the request as a dictionary.\n\n    Attributes:\n        scope: A dictionary to store the scope of the request.\n        _cookies: A dictionary to store the cookies of the request.\n        _headers: A dictionary to store the headers of the request.\n        _body: A dictionary to store the body of the request.\n        _query_params: A dictionary to store the query parameters of the request.\n\n    \"\"\"\n    self._headers = headers\n    self._body = body\n    self._query_params = path\n\n    self.scope = {\"path_params\": self._query_params}\n    self._cookies = {}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.app","title":"app property","text":"
app: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.auth","title":"auth property","text":"
auth: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.base_url","title":"base_url property","text":"
base_url: URL\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.client","title":"client property","text":"
client: typing.Optional[Address]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.cookies","title":"cookies property","text":"
cookies: typing.Dict[str, str]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.headers","title":"headers property","text":"
headers: Headers\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.method","title":"method property","text":"
method: str\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.path_params","title":"path_params property","text":"
path_params: typing.Dict[str, typing.Any]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.query_params","title":"query_params property","text":"
query_params: QueryParams\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.receive","title":"receive property","text":"
receive: Receive\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.scope","title":"scope instance-attribute","text":"
scope: AnyDict = {'path_params': self._query_params}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.session","title":"session property","text":"
session: typing.Dict[str, typing.Any]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.state","title":"state property","text":"
state: State\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.url","title":"url property","text":"
url: URL\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.user","title":"user property","text":"
user: typing.Any\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.body","title":"body async","text":"
body() -> bytes\n
Source code in starlette/requests.py
async def body(self) -> bytes:\n    if not hasattr(self, \"_body\"):\n        chunks: \"typing.List[bytes]\" = []\n        async for chunk in self.stream():\n            chunks.append(chunk)\n        self._body = b\"\".join(chunks)\n    return self._body\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.close","title":"close async","text":"
close() -> None\n
Source code in starlette/requests.py
async def close(self) -> None:\n    if self._form is not None:\n        await self._form.close()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.form","title":"form","text":"
form(\n    *,\n    max_files: typing.Union[int, float] = 1000,\n    max_fields: typing.Union[int, float] = 1000\n) -> AwaitableOrContextManager[FormData]\n
Source code in starlette/requests.py
def form(\n    self,\n    *,\n    max_files: typing.Union[int, float] = 1000,\n    max_fields: typing.Union[int, float] = 1000,\n) -> AwaitableOrContextManager[FormData]:\n    return AwaitableOrContextManagerWrapper(\n        self._get_form(max_files=max_files, max_fields=max_fields)\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.get_session","title":"get_session classmethod","text":"
get_session(\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[\n    [NativeMessage[Any]], Awaitable[SendableMessage]\n]\n

Creates a session for handling requests.

PARAMETER DESCRIPTION dependant

The dependant object representing the session.

TYPE: Dependant

dependency_overrides_provider

Optional provider for dependency overrides.

TYPE: Optional[Any] DEFAULT: None

RETURNS DESCRIPTION Callable[[StreamMessage[Any]], Awaitable[SendableMessage]]

A callable that takes a native message and returns an awaitable sendable message.

RAISES DESCRIPTION AssertionError

If the dependant call is not defined.

Note

This function is used to create a session for handling requests. It takes a dependant object, which represents the session, and a dependency overrides provider, which allows for overriding dependencies. It returns a callable that takes a native message and returns an awaitable sendable message. The session is created based on the dependant object and the message passed to the callable. The session is then used to call the function obtained from the dependant object, and the result is returned.

Source code in faststream/broker/fastapi/route.py
@classmethod\ndef get_session(\n    cls,\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[[NativeMessage[Any]], Awaitable[SendableMessage]]:\n    \"\"\"Creates a session for handling requests.\n\n    Args:\n        dependant: The dependant object representing the session.\n        dependency_overrides_provider: Optional provider for dependency overrides.\n\n    Returns:\n        A callable that takes a native message and returns an awaitable sendable message.\n\n    Raises:\n        AssertionError: If the dependant call is not defined.\n\n    Note:\n        This function is used to create a session for handling requests. It takes a dependant object, which represents the session, and a dependency overrides provider, which allows for overriding dependencies. It returns a callable that takes a native message and returns an awaitable sendable message. The session is created based on the dependant object and the message passed to the callable. The session is then used to call the function obtained from the dependant object, and the result is returned.\n\n    \"\"\"\n    assert dependant.call  # nosec B101\n\n    func = get_app(dependant, dependency_overrides_provider)\n\n    dependencies_names = tuple(i.name for i in dependant.dependencies)\n\n    first_arg = next(\n        dropwhile(\n            lambda i: i in dependencies_names,\n            inspect.signature(dependant.call).parameters,\n        ),\n        None,\n    )\n\n    async def app(message: NativeMessage[Any]) -> SendableMessage:\n        \"\"\"An asynchronous function that processes an incoming message and returns a sendable message.\n\n        Args:\n            message : The incoming message to be processed\n\n        Returns:\n            The sendable message\n\n        Raises:\n            TypeError: If the body of the message is not a dictionary\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        body = message.decoded_body\n\n        fastapi_body: Union[AnyDict, List[Any]]\n        if first_arg is not None:\n            if isinstance(body, dict):\n                path = fastapi_body = body or {}\n            elif isinstance(body, list):\n                fastapi_body, path = body, {}\n            else:\n                path = fastapi_body = {first_arg: body}\n\n            session = cls(\n                body=fastapi_body,\n                headers=message.headers,\n                path={**path, **message.path},\n            )\n\n        else:\n            session = cls(\n                body={},\n                headers={},\n                path={},\n            )\n\n        return await func(session)\n\n    return app\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.is_disconnected","title":"is_disconnected async","text":"
is_disconnected() -> bool\n
Source code in starlette/requests.py
async def is_disconnected(self) -> bool:\n    if not self._is_disconnected:\n        message: Message = {}\n\n        # If message isn't immediately available, move on\n        with anyio.CancelScope() as cs:\n            cs.cancel()\n            message = await self._receive()\n\n        if message.get(\"type\") == \"http.disconnect\":\n            self._is_disconnected = True\n\n    return self._is_disconnected\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.json","title":"json async","text":"
json() -> typing.Any\n
Source code in starlette/requests.py
async def json(self) -> typing.Any:\n    if not hasattr(self, \"_json\"):\n        body = await self.body()\n        self._json = json.loads(body)\n    return self._json\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.send_push_promise","title":"send_push_promise async","text":"
send_push_promise(path: str) -> None\n
Source code in starlette/requests.py
async def send_push_promise(self, path: str) -> None:\n    if \"http.response.push\" in self.scope.get(\"extensions\", {}):\n        raw_headers: \"typing.List[typing.Tuple[bytes, bytes]]\" = []\n        for name in SERVER_PUSH_HEADERS_TO_COPY:\n            for value in self.headers.getlist(name):\n                raw_headers.append(\n                    (name.encode(\"latin-1\"), value.encode(\"latin-1\"))\n                )\n        await self._send(\n            {\"type\": \"http.response.push\", \"path\": path, \"headers\": raw_headers}\n        )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.stream","title":"stream async","text":"
stream() -> typing.AsyncGenerator[bytes, None]\n
Source code in starlette/requests.py
async def stream(self) -> typing.AsyncGenerator[bytes, None]:\n    if hasattr(self, \"_body\"):\n        yield self._body\n        yield b\"\"\n        return\n    if self._stream_consumed:\n        raise RuntimeError(\"Stream consumed\")\n    self._stream_consumed = True\n    while True:\n        message = await self._receive()\n        if message[\"type\"] == \"http.request\":\n            body = message.get(\"body\", b\"\")\n            if body:\n                yield body\n            if not message.get(\"more_body\", False):\n                break\n        elif message[\"type\"] == \"http.disconnect\":\n            self._is_disconnected = True\n            raise ClientDisconnect()\n    yield b\"\"\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamMessage/#faststream.broker.fastapi.route.StreamMessage.url_for","title":"url_for","text":"
url_for(__name: str, **path_params: typing.Any) -> URL\n
Source code in starlette/requests.py
def url_for(self, __name: str, **path_params: typing.Any) -> URL:\n    router: Router = self.scope[\"router\"]\n    url_path = router.url_path_for(__name, **path_params)\n    return url_path.make_absolute_url(base_url=self.base_url)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/","title":"StreamRoute","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute","title":"faststream.broker.fastapi.route.StreamRoute","text":"
StreamRoute(\n    path: Union[NameRequired, str, None],\n    *extra: Union[NameRequired, str],\n    endpoint: Union[\n        Callable[P_HandlerParams, T_HandlerReturn],\n        HandlerCallWrapper[\n            MsgType, P_HandlerParams, T_HandlerReturn\n        ],\n    ],\n    broker: BrokerAsyncUsecase[MsgType, Any],\n    dependencies: Sequence[params.Depends] = (),\n    dependency_overrides_provider: Optional[Any] = None,\n    **handle_kwargs: Any\n)\n

Bases: BaseRoute, Generic[MsgType, P_HandlerParams, T_HandlerReturn]

A class representing a stream route.

Initialize a class instance.

PARAMETER DESCRIPTION path

The path of the instance.

TYPE: Union[NameRequired, str, None]

*extra

Additional arguments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint of the instance.

TYPE: Union[Callable[P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

broker

The broker of the instance.

TYPE: BrokerAsyncUsecase[MsgType, Any]

dependencies

The dependencies of the instance.

TYPE: Sequence[Depends] DEFAULT: ()

dependency_overrides_provider

The provider for dependency overrides.

TYPE: Optional[Any] DEFAULT: None

**handle_kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None.

Source code in faststream/broker/fastapi/route.py
def __init__(\n    self,\n    path: Union[NameRequired, str, None],\n    *extra: Union[NameRequired, str],\n    endpoint: Union[\n        Callable[P_HandlerParams, T_HandlerReturn],\n        HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n    ],\n    broker: BrokerAsyncUsecase[MsgType, Any],\n    dependencies: Sequence[params.Depends] = (),\n    dependency_overrides_provider: Optional[Any] = None,\n    **handle_kwargs: Any,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        path: The path of the instance.\n        *extra: Additional arguments.\n        endpoint: The endpoint of the instance.\n        broker: The broker of the instance.\n        dependencies: The dependencies of the instance.\n        dependency_overrides_provider: The provider for dependency overrides.\n        **handle_kwargs: Additional keyword arguments.\n\n    Returns:\n        None.\n\n    \"\"\"\n    self.path = path or \"\"\n    self.broker = broker\n\n    path_name = self.path if isinstance(self.path, str) else self.path.name\n\n    if isinstance(endpoint, HandlerCallWrapper):\n        orig_call = endpoint._original_call\n    else:\n        orig_call = endpoint\n\n    dependant = get_dependant(\n        path=path_name,\n        call=orig_call,\n    )\n    for depends in dependencies[::-1]:\n        dependant.dependencies.insert(\n            0,\n            get_parameterless_sub_dependant(depends=depends, path=path_name),\n        )\n    self.dependant = dependant\n\n    call = wraps(orig_call)(\n        StreamMessage.get_session(\n            dependant,\n            dependency_overrides_provider,\n        )\n    )\n\n    if isinstance(endpoint, HandlerCallWrapper):\n        endpoint._original_call = call\n        handler = endpoint\n\n    else:\n        handler = call\n\n    self.handler = broker.subscriber(\n        path,\n        *extra,\n        _raw=True,\n        _get_dependant=lambda call: dependant,\n        **handle_kwargs,\n    )(\n        handler  # type: ignore[arg-type]\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.dependant","title":"dependant instance-attribute","text":"
dependant = dependant\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.handler","title":"handler instance-attribute","text":"
handler: HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n] = broker.subscriber(\n    path,\n    *extra,\n    _raw=True,\n    _get_dependant=lambda: dependant,\n    **handle_kwargs\n)(\n    handler\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.path","title":"path instance-attribute","text":"
path = path or ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.handle","title":"handle async","text":"
handle(scope: Scope, receive: Receive, send: Send) -> None\n
Source code in starlette/routing.py
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.matches","title":"matches","text":"
matches(scope: Scope) -> typing.Tuple[Match, Scope]\n
Source code in starlette/routing.py
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/StreamRoute/#faststream.broker.fastapi.route.StreamRoute.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    raise NotImplementedError()  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/route/get_app/","title":"get_app","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/route/get_app/#faststream.broker.fastapi.route.get_app","title":"faststream.broker.fastapi.route.get_app","text":"
get_app(\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[\n    [StreamMessage], Coroutine[Any, Any, SendableMessage]\n]\n

Creates a FastAPI application.

PARAMETER DESCRIPTION dependant

The dependant object that defines the endpoint function and its dependencies.

TYPE: Dependant

dependency_overrides_provider

Optional provider for dependency overrides.

TYPE: Optional[Any] DEFAULT: None

RETURNS DESCRIPTION Callable[[StreamMessage], Coroutine[Any, Any, SendableMessage]]

The FastAPI application as a callable that takes a StreamMessage object as input and returns a SendableMessage coroutine.

RAISES DESCRIPTION AssertionError

If the code reaches an unreachable state.

Source code in faststream/broker/fastapi/route.py
def get_app(\n    dependant: Dependant,\n    dependency_overrides_provider: Optional[Any] = None,\n) -> Callable[[StreamMessage], Coroutine[Any, Any, SendableMessage]]:\n    \"\"\"Creates a FastAPI application.\n\n    Args:\n        dependant: The dependant object that defines the endpoint function and its dependencies.\n        dependency_overrides_provider: Optional provider for dependency overrides.\n\n    Returns:\n        The FastAPI application as a callable that takes a StreamMessage object as input and returns a SendableMessage coroutine.\n\n    Raises:\n        AssertionError: If the code reaches an unreachable state.\n\n    \"\"\"\n\n    async def app(request: StreamMessage) -> SendableMessage:\n        \"\"\"Handle an HTTP request and return a response.\n\n        Args:\n            request: The incoming HTTP request.\n\n        Returns:\n            The response to be sent back to the client.\n\n        Raises:\n            AssertionError: If the code reaches an unreachable point.\n\n        \"\"\"\n        async with AsyncExitStack() as stack:\n            request.scope[\"fastapi_astack\"] = stack\n\n            solved_result = await solve_dependencies(\n                request=request,\n                body=request._body,\n                dependant=dependant,\n                dependency_overrides_provider=dependency_overrides_provider,\n            )\n\n            values, errors, _, _2, _3 = solved_result\n            if errors:\n                raise_fastapi_validation_error(errors, request._body)\n\n            return cast(\n                SendableMessage,\n                await run_endpoint_function(\n                    dependant=dependant,\n                    values=values,\n                    is_coroutine=asyncio.iscoroutinefunction(dependant.call),\n                ),\n            )\n\n        raise AssertionError(\"unreachable\")\n\n    return app\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/","title":"StreamRouter","text":"","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter","title":"faststream.broker.fastapi.router.StreamRouter","text":"
StreamRouter(\n    *connection_args: Tuple[Any, ...],\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    setup_state: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id),\n    asyncapi_tags: Optional[\n        Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]\n    ] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    **connection_kwars: Any\n)\n

Bases: APIRouter, Generic[MsgType]

A class to route streams.

METHOD DESCRIPTION __init__

initialize the StreamRouter

add_api_mq_route

add a route for API and message queue

subscriber

decorator to define a subscriber

wrap_lifespan

wrap the lifespan of the router

after_startup

decorator to define a function to be executed after startup

publisher

create a publisher for the broker

asyncapi_router

create an APIRouter for AsyncAPI documentation

include_router

include another router in the StreamRouter

_setup_log_context

setup log context for the broker

Initialize an instance of a class.

PARAMETER DESCRIPTION *connection_args

Variable length arguments for the connection

TYPE: Tuple[Any, ...] DEFAULT: ()

prefix

Prefix for the class

TYPE: str DEFAULT: ''

tags

Optional list of tags for the class

TYPE: Optional[List[Union[str, Enum]]] DEFAULT: None

dependencies

Optional sequence of dependencies for the class

TYPE: Optional[Sequence[Depends]] DEFAULT: None

default_response_class

Default response class for the class

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

Optional dictionary of responses for the class

TYPE: Optional[Dict[Union[int, str], AnyDict]] DEFAULT: None

callbacks

Optional list of callbacks for the class

TYPE: Optional[List[BaseRoute]] DEFAULT: None

routes

Optional list of routes for the class

TYPE: Optional[List[BaseRoute]] DEFAULT: None

redirect_slashes

Boolean value indicating whether to redirect slashes

TYPE: bool DEFAULT: True

default

Optional default value for the class

TYPE: Optional[ASGIApp] DEFAULT: None

dependency_overrides_provider

Optional provider for dependency overrides

TYPE: Optional[Any] DEFAULT: None

route_class

Route class for the class

TYPE: Type[APIRoute] DEFAULT: APIRoute

on_startup

Optional sequence of functions to run on startup

TYPE: Optional[Sequence[Callable[[], Any]]] DEFAULT: None

on_shutdown

Optional sequence of functions to run on shutdown

TYPE: Optional[Sequence[Callable[[], Any]]] DEFAULT: None

deprecated

Optional boolean value indicating whether the class is deprecated

TYPE: Optional[bool] DEFAULT: None

include_in_schema

Boolean value indicating whether to include the class in the schema

TYPE: bool DEFAULT: True

setup_state

Boolean value indicating whether to setup state

TYPE: bool DEFAULT: True

lifespan

Optional lifespan for the class

TYPE: Optional[Lifespan[Any]] DEFAULT: None

generate_unique_id_function

Function to generate unique ID for the class

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

asyncapi_tags

Optional sequence of asyncapi tags for the class schema

TYPE: Optional[Sequence[Union[Tag, TagDict]]] DEFAULT: None

Source code in faststream/broker/fastapi/router.py
def __init__(\n    self,\n    *connection_args: Tuple[Any, ...],\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[Sequence[Callable[[], Any]]] = None,\n    on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    setup_state: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n    # AsyncAPI information\n    asyncapi_tags: Optional[Sequence[Union[asyncapi.Tag, asyncapi.TagDict]]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    **connection_kwars: Any,\n) -> None:\n    \"\"\"Initialize an instance of a class.\n\n    Args:\n        *connection_args: Variable length arguments for the connection\n        prefix: Prefix for the class\n        tags: Optional list of tags for the class\n        dependencies: Optional sequence of dependencies for the class\n        default_response_class: Default response class for the class\n        responses: Optional dictionary of responses for the class\n        callbacks: Optional list of callbacks for the class\n        routes: Optional list of routes for the class\n        redirect_slashes: Boolean value indicating whether to redirect slashes\n        default: Optional default value for the class\n        dependency_overrides_provider: Optional provider for dependency overrides\n        route_class: Route class for the class\n        on_startup: Optional sequence of functions to run on startup\n        on_shutdown: Optional sequence of functions to run on shutdown\n        deprecated: Optional boolean value indicating whether the class is deprecated\n        include_in_schema: Boolean value indicating whether to include the class in the schema\n        setup_state: Boolean value indicating whether to setup state\n        lifespan: Optional lifespan for the class\n        generate_unique_id_function: Function to generate unique ID for the class\n        asyncapi_tags: Optional sequence of asyncapi tags for the class schema\n\n    \"\"\"\n    assert (  # nosec B101\n        self.broker_class\n    ), \"You should specify `broker_class` at your implementation\"\n\n    self.broker = self.broker_class(\n        *connection_args,\n        apply_types=False,\n        tags=asyncapi_tags,\n        **connection_kwars,\n    )\n\n    self.setup_state = setup_state\n\n    # AsyncAPI information\n    # Empty\n    self.terms_of_service = None\n    self.identifier = None\n    self.asyncapi_tags = None\n    self.external_docs = None\n    # parse from FastAPI app on startup\n    self.title = \"\"\n    self.version = \"\"\n    self.description = \"\"\n    self.license = None\n    self.contact = None\n\n    self.schema = None\n\n    super().__init__(\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        routes=routes,\n        redirect_slashes=redirect_slashes,\n        default=default,\n        dependency_overrides_provider=dependency_overrides_provider,\n        route_class=route_class,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n        lifespan=self.wrap_lifespan(lifespan),\n        on_startup=on_startup,\n        on_shutdown=on_shutdown,\n    )\n\n    self.docs_router = self.asyncapi_router(schema_url)\n\n    self._after_startup_hooks = []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.broker","title":"broker instance-attribute","text":"
broker: BrokerAsyncUsecase[\n    MsgType, Any\n] = self.broker_class(\n    *connection_args,\n    apply_types=False,\n    tags=asyncapi_tags,\n    **connection_kwars\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.broker_class","title":"broker_class instance-attribute","text":"
broker_class: Type[BrokerAsyncUsecase[MsgType, Any]]\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any\n) -> HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n]\n

Add an API message queue route.

PARAMETER DESCRIPTION path

The path of the route.

TYPE: Union[NameRequired, str]

*extra

Additional path segments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint function to be called for this route.

TYPE: Callable[P_HandlerParams, T_HandlerReturn]

dependencies

The dependencies required by the endpoint function.

TYPE: Sequence[Depends]

**broker_kwargs

Additional keyword arguments to be passed to the broker.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]

The handler call wrapper for the route.

Source code in faststream/broker/fastapi/router.py
def add_api_mq_route(\n    self,\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any,\n) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n    \"\"\"Add an API message queue route.\n\n    Args:\n        path: The path of the route.\n        *extra: Additional path segments.\n        endpoint: The endpoint function to be called for this route.\n        dependencies: The dependencies required by the endpoint function.\n        **broker_kwargs: Additional keyword arguments to be passed to the broker.\n\n    Returns:\n        The handler call wrapper for the route.\n\n    \"\"\"\n    route: StreamRoute[MsgType, P_HandlerParams, T_HandlerReturn] = StreamRoute(\n        path,\n        *extra,\n        endpoint=endpoint,\n        dependencies=dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        broker=self.broker,\n        **broker_kwargs,\n    )\n    self.routes.append(route)\n    return route.handler\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.publisher","title":"publisher","text":"
publisher(\n    queue: Union[NameRequired, str],\n    *publisher_args: Any,\n    **publisher_kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes messages to a queue.

PARAMETER DESCRIPTION queue

The queue to publish the messages to. Can be either a NameRequired object or a string.

TYPE: Union[NameRequired, str]

*publisher_args

Additional arguments to be passed to the publisher.

TYPE: Any DEFAULT: ()

**publisher_kwargs

Additional keyword arguments to be passed to the publisher.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

An instance of BasePublisher that can be used to publish messages to the specified queue.

Source code in faststream/broker/fastapi/router.py
def publisher(\n    self,\n    queue: Union[NameRequired, str],\n    *publisher_args: Any,\n    **publisher_kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes messages to a queue.\n\n    Args:\n        queue: The queue to publish the messages to. Can be either a `NameRequired` object or a string.\n        *publisher_args: Additional arguments to be passed to the publisher.\n        **publisher_kwargs: Additional keyword arguments to be passed to the publisher.\n\n    Returns:\n        An instance of `BasePublisher` that can be used to publish messages to the specified queue.\n\n    \"\"\"\n    return self.broker.publisher(\n        queue,\n        *publisher_args,\n        **publisher_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.subscriber","title":"subscriber","text":"
subscriber(\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function decorator for subscribing to a message queue.

PARAMETER DESCRIPTION path

The path to subscribe to. Can be a string or a NameRequired object.

*extra

Additional path segments. Can be a NameRequired object or a string.

DEFAULT: ()

dependencies

Optional sequence of dependencies.

DEFAULT: None

**broker_kwargs

Additional keyword arguments for the broker.

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable decorator that adds the decorated function as an endpoint for the specified path.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def subscriber(\n    self,\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function decorator for subscribing to a message queue.\n\n    Args:\n        path : The path to subscribe to. Can be a string or a `NameRequired` object.\n        *extra : Additional path segments. Can be a `NameRequired` object or a string.\n        dependencies : Optional sequence of dependencies.\n        **broker_kwargs : Additional keyword arguments for the broker.\n\n    Returns:\n        A callable decorator that adds the decorated function as an endpoint for the specified path.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    def decorator(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n        \"\"\"A decorator function.\n\n        Args:\n            func: The function to be decorated.\n\n        Returns:\n            The decorated function.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        return self.add_api_mq_route(\n            path,\n            *extra,\n            endpoint=func,\n            dependencies=current_dependencies,\n            **broker_kwargs,\n        )\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/broker/fastapi/router/StreamRouter/#faststream.broker.fastapi.router.StreamRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/","title":"AsyncHandler","text":"","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler","title":"faststream.broker.handler.AsyncHandler","text":"
AsyncHandler(\n    *,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    graceful_timeout: Optional[float] = None\n)\n

Bases: BaseHandler[MsgType]

A class representing an asynchronous handler.

METHOD DESCRIPTION add_call

adds a new call to the list of calls

consume

consumes a message and returns a sendable message

start

starts the handler

close

closes the handler

Source code in faststream/broker/handler.py
def __init__(\n    self,\n    *,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    graceful_timeout: Optional[float] = None,\n) -> None:\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n    )\n    self.lock = MultiLock()\n    self.graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n    parser: CustomParser[MsgType, Any],\n    decoder: CustomDecoder[Any],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    filter: Filter[StreamMessage[MsgType]],\n    middlewares: Optional[\n        Sequence[Callable[[Any], BaseMiddleware]]\n    ]\n) -> None\n

Adds a call to the handler.

PARAMETER DESCRIPTION handler

The handler call wrapper.

TYPE: HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]

parser

The custom parser.

TYPE: CustomParser[MsgType, Any]

decoder

The custom decoder.

TYPE: CustomDecoder[Any]

dependant

The call model.

TYPE: CallModel[P_HandlerParams, T_HandlerReturn]

filter

The filter for stream messages.

TYPE: Filter[StreamMessage[MsgType]]

middlewares

Optional sequence of middlewares.

TYPE: Optional[Sequence[Callable[[Any], BaseMiddleware]]]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n    parser: CustomParser[MsgType, Any],\n    decoder: CustomDecoder[Any],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    filter: Filter[StreamMessage[MsgType]],\n    middlewares: Optional[Sequence[Callable[[Any], BaseMiddleware]]],\n) -> None:\n    \"\"\"Adds a call to the handler.\n\n    Args:\n        handler: The handler call wrapper.\n        parser: The custom parser.\n        decoder: The custom decoder.\n        dependant: The call model.\n        filter: The filter for stream messages.\n        middlewares: Optional sequence of middlewares.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.calls.append(\n        (\n            handler,\n            to_async(filter),\n            to_async(parser) if parser else None,  # type: ignore[arg-type]\n            to_async(decoder) if decoder else None,  # type: ignore[arg-type]\n            middlewares or (),\n            dependant,\n        )\n    )\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.close","title":"close abstractmethod async","text":"
close() -> None\n
Source code in faststream/broker/handler.py
@abstractmethod\nasync def close(self) -> None:\n    self.running = False\n    await self.lock.wait_release(self.graceful_timeout)\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/broker/handler/AsyncHandler/#faststream.broker.handler.AsyncHandler.start","title":"start abstractmethod async","text":"
start() -> None\n
Source code in faststream/broker/handler.py
@abstractmethod\nasync def start(self) -> None:\n    self.running = True\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/","title":"BaseHandler","text":"","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler","title":"faststream.broker.handler.BaseHandler","text":"
BaseHandler(\n    *,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True\n)\n

Bases: AsyncAPIOperation, Generic[MsgType]

A base handler class for asynchronous API operations.

METHOD DESCRIPTION __init__

Initializes the BaseHandler object.

name

Returns the name of the handler.

call_name

Returns the name of the handler call.

description

Returns the description of the handler.

consume

Abstract method to consume a message.

Note: This class inherits from AsyncAPIOperation and is a generic class with type parameter MsgType.

Initialize a new instance of the class.

PARAMETER DESCRIPTION description

Optional description of the instance.

TYPE: Optional[str] DEFAULT: None

title

Optional title of the instance.

TYPE: Optional[str] DEFAULT: None

Source code in faststream/broker/handler.py
def __init__(\n    self,\n    *,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    \"\"\"Initialize a new instance of the class.\n\n    Args:\n        description: Optional description of the instance.\n        title: Optional title of the instance.\n\n    \"\"\"\n    self.calls = []  # type: ignore[assignment]\n    self.global_middlewares = []\n\n    self.log_context_builder = log_context_builder\n    self.running = False\n\n    # AsyncAPI information\n    self._description = description\n    self._title = title\n    self.include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.calls","title":"calls instance-attribute","text":"
calls: Union[\n    List[\n        Tuple[\n            HandlerCallWrapper[\n                MsgType, Any, SendableMessage\n            ],\n            Callable[[StreamMessage[MsgType]], bool],\n            SyncParser[MsgType, StreamMessage[MsgType]],\n            SyncDecoder[StreamMessage[MsgType]],\n            Sequence[Callable[[Any], BaseMiddleware]],\n            CallModel[Any, SendableMessage],\n        ]\n    ],\n    List[\n        Tuple[\n            HandlerCallWrapper[\n                MsgType, Any, SendableMessage\n            ],\n            Callable[\n                [StreamMessage[MsgType]], Awaitable[bool]\n            ],\n            AsyncParser[MsgType, StreamMessage[MsgType]],\n            AsyncDecoder[StreamMessage[MsgType]],\n            Sequence[Callable[[Any], BaseMiddleware]],\n            CallModel[Any, SendableMessage],\n        ]\n    ],\n] = []\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.consume","title":"consume abstractmethod","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/handler.py
@abstractmethod\ndef consume(self, msg: MsgType) -> SendableMessage:\n    \"\"\"Consume a message.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/handler/BaseHandler/#faststream.broker.handler.BaseHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/","title":"MultiLock","text":"","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/#faststream.broker.handler.MultiLock","title":"faststream.broker.handler.MultiLock","text":"
MultiLock()\n
Source code in faststream/broker/handler.py
def __init__(self) -> None:\n    self.queue: \"asyncio.Queue[None]\" = asyncio.Queue()\n
","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/#faststream.broker.handler.MultiLock.empty","title":"empty property","text":"
empty: bool\n
","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/#faststream.broker.handler.MultiLock.qsize","title":"qsize property","text":"
qsize: int\n
","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/#faststream.broker.handler.MultiLock.queue","title":"queue instance-attribute","text":"
queue: asyncio.Queue[None] = asyncio.Queue()\n
","boost":0.5},{"location":"api/faststream/broker/handler/MultiLock/#faststream.broker.handler.MultiLock.wait_release","title":"wait_release async","text":"
wait_release(timeout: Optional[float] = None) -> None\n
Source code in faststream/broker/handler.py
async def wait_release(self, timeout: Optional[float] = None) -> None:\n    if timeout:\n        with anyio.move_on_after(timeout):\n            await self.queue.join()\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/","title":"ABCStreamMessage","text":"","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage","title":"faststream.broker.message.ABCStreamMessage dataclass","text":"

Bases: Generic[Msg]

A generic class to represent a stream message.

","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/broker/message/ABCStreamMessage/#faststream.broker.message.ABCStreamMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/","title":"StreamMessage","text":"","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage","title":"faststream.broker.message.StreamMessage","text":"

Bases: ABCStreamMessage[Msg]

","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.ack","title":"ack async","text":"
ack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def ack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.nack","title":"nack async","text":"
nack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def nack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/message/StreamMessage/#faststream.broker.message.StreamMessage.reject","title":"reject async","text":"
reject(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def reject(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/","title":"SyncStreamMessage","text":"","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage","title":"faststream.broker.message.SyncStreamMessage","text":"

Bases: ABCStreamMessage[Msg]

","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.ack","title":"ack","text":"
ack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
def ack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.nack","title":"nack","text":"
nack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
def nack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/message/SyncStreamMessage/#faststream.broker.message.SyncStreamMessage.reject","title":"reject","text":"
reject(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
def reject(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/","title":"BaseMiddleware","text":"","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware","title":"faststream.broker.middlewares.BaseMiddleware","text":"
BaseMiddleware(msg: Any)\n

A base middleware class.

METHOD DESCRIPTION on_receive

Called when a message is received.

after_processed

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) -> Optional[bool]: Called after processing a message.

__aenter__

Called when entering a context.

__aexit__

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) -> Optional[bool]: Called when exiting a context.

on_consume

DecodedMessage) -> DecodedMessage: Called before consuming a message.

after_consume

Optional[Exception]) -> None: Called after consuming a message.

consume_scope

DecodedMessage) -> AsyncIterator[DecodedMessage]: Context manager for consuming a message.

on_publish

SendableMessage) -> SendableMessage: Called before publishing a message.

after_publish

Optional[Exception]) -> None: Asynchronous function to handle the after publish event.

Initialize the class.

PARAMETER DESCRIPTION msg

Any message to be stored.

TYPE: Any

Source code in faststream/broker/middlewares.py
def __init__(self, msg: Any) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        msg: Any message to be stored.\n    \"\"\"\n    self.msg = msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.msg","title":"msg instance-attribute","text":"
msg = msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.after_consume","title":"after_consume async","text":"
after_consume(err: Optional[Exception]) -> None\n

A function to handle the result of consuming a resource asynchronously.

PARAMETER DESCRIPTION err

Optional exception that occurred during consumption

RAISES DESCRIPTION err

If an exception occurred during consumption

Source code in faststream/broker/middlewares.py
async def after_consume(self, err: Optional[Exception]) -> None:\n    \"\"\"A function to handle the result of consuming a resource asynchronously.\n\n    Args:\n        err : Optional exception that occurred during consumption\n\n    Raises:\n        err : If an exception occurred during consumption\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.after_processed","title":"after_processed async","text":"
after_processed(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> Optional[bool]\n

Asynchronously called after processing.

PARAMETER DESCRIPTION exc_type

Optional exception type

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

Optional exception value

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

Optional traceback

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION Optional[bool]

Optional boolean value indicating whether the processing was successful or not.

Source code in faststream/broker/middlewares.py
async def after_processed(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> Optional[bool]:\n    \"\"\"Asynchronously called after processing.\n\n    Args:\n        exc_type: Optional exception type\n        exc_val: Optional exception value\n        exec_tb: Optional traceback\n\n    Returns:\n        Optional boolean value indicating whether the processing was successful or not.\n    \"\"\"\n    return False\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.after_publish","title":"after_publish async","text":"
after_publish(err: Optional[Exception]) -> None\n

Asynchronous function to handle the after publish event.

PARAMETER DESCRIPTION err

Optional exception that occurred during the publish

TYPE: Optional[Exception]

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION Exception

If an error occurred during the publish

Source code in faststream/broker/middlewares.py
async def after_publish(self, err: Optional[Exception]) -> None:\n    \"\"\"Asynchronous function to handle the after publish event.\n\n    Args:\n        err: Optional exception that occurred during the publish\n\n    Returns:\n        None\n\n    Raises:\n        Exception: If an error occurred during the publish\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.consume_scope","title":"consume_scope async","text":"
consume_scope(\n    msg: DecodedMessage,\n) -> AsyncIterator[DecodedMessage]\n

Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.

PARAMETER DESCRIPTION msg

The decoded message to consume.

TYPE: DecodedMessage

YIELDS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RETURNS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RAISES DESCRIPTION Exception

If an error occurs while consuming the message.

AsyncIterator

An asynchronous iterator that yields decoded messages.

Note

This function is an async function.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def consume_scope(self, msg: DecodedMessage) -> AsyncIterator[DecodedMessage]:\n    \"\"\"Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.\n\n    Args:\n        msg: The decoded message to consume.\n\n    Yields:\n        An asynchronous iterator of decoded messages.\n\n    Returns:\n        An asynchronous iterator of decoded messages.\n\n    Raises:\n        Exception: If an error occurs while consuming the message.\n\n    AsyncIterator:\n        An asynchronous iterator that yields decoded messages.\n\n    Note:\n        This function is an async function.\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_consume(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_consume(err)\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.on_consume","title":"on_consume async","text":"
on_consume(msg: DecodedMessage) -> DecodedMessage\n

Asynchronously consumes a message.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: DecodedMessage

RETURNS DESCRIPTION DecodedMessage

The consumed message.

Source code in faststream/broker/middlewares.py
async def on_consume(self, msg: DecodedMessage) -> DecodedMessage:\n    \"\"\"Asynchronously consumes a message.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The consumed message.\n    \"\"\"\n    return msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.on_publish","title":"on_publish async","text":"
on_publish(msg: SendableMessage) -> SendableMessage\n

Asynchronously handle a publish event.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

RETURNS DESCRIPTION SendableMessage

The published message.

Source code in faststream/broker/middlewares.py
async def on_publish(self, msg: SendableMessage) -> SendableMessage:\n    \"\"\"Asynchronously handle a publish event.\n\n    Args:\n        msg: The message to be published.\n\n    Returns:\n        The published message.\n    \"\"\"\n    return msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.on_receive","title":"on_receive async","text":"
on_receive() -> None\n
Source code in faststream/broker/middlewares.py
async def on_receive(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/BaseMiddleware/#faststream.broker.middlewares.BaseMiddleware.publish_scope","title":"publish_scope async","text":"
publish_scope(\n    msg: SendableMessage,\n) -> AsyncIterator[SendableMessage]\n

Publish a message and return an async iterator.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

YIELDS DESCRIPTION AsyncIterator[SendableMessage]

A sendable message.

RETURNS DESCRIPTION AsyncIterator[SendableMessage]

An async iterator of sendable messages.

RAISES DESCRIPTION Exception

If an error occurs during publishing.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def publish_scope(\n    self, msg: SendableMessage\n) -> AsyncIterator[SendableMessage]:\n    \"\"\"Publish a message and return an async iterator.\n\n    Args:\n        msg: The message to be published.\n\n    Yields:\n        A sendable message.\n\n    Returns:\n        An async iterator of sendable messages.\n\n    Raises:\n        Exception: If an error occurs during publishing.\n\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_publish(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_publish(err)\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/","title":"CriticalLogMiddleware","text":"","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware","title":"faststream.broker.middlewares.CriticalLogMiddleware","text":"
CriticalLogMiddleware(\n    logger: Optional[logging.Logger], log_level: int\n)\n

Bases: BaseMiddleware

A middleware class for logging critical errors.

PARAMETER DESCRIPTION logger

The logger object to use for logging

TYPE: Optional[Logger]

METHOD DESCRIPTION __call__

Any) -> Self: Returns the middleware instance

after_processed

Optional[Type[BaseException]] = None, exc_val: Optional[BaseException] = None, exec_tb: Optional[TracebackType] = None) -> bool: Logs critical errors if they occur and returns True

Initialize the class.

PARAMETER DESCRIPTION logger

an instance of the logging.Logger class

TYPE: Optional[Logger]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/middlewares.py
def __init__(\n    self,\n    logger: Optional[logging.Logger],\n    log_level: int,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        logger: an instance of the logging.Logger class\n\n    Returns:\n        None\n    \"\"\"\n    self.logger = logger\n    self.log_level = log_level\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.msg","title":"msg instance-attribute","text":"
msg = msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.after_consume","title":"after_consume async","text":"
after_consume(err: Optional[Exception]) -> None\n

A function to handle the result of consuming a resource asynchronously.

PARAMETER DESCRIPTION err

Optional exception that occurred during consumption

RAISES DESCRIPTION err

If an exception occurred during consumption

Source code in faststream/broker/middlewares.py
async def after_consume(self, err: Optional[Exception]) -> None:\n    \"\"\"A function to handle the result of consuming a resource asynchronously.\n\n    Args:\n        err : Optional exception that occurred during consumption\n\n    Raises:\n        err : If an exception occurred during consumption\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.after_processed","title":"after_processed async","text":"
after_processed(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> bool\n

Asynchronously called after processing.

PARAMETER DESCRIPTION exc_type

Type of the exception raised during processing.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

Value of the exception raised during processing.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

Traceback of the exception raised during processing.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION bool

True if the method is successfully executed.

TYPE: bool

Source code in faststream/broker/middlewares.py
async def after_processed(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> bool:\n    \"\"\"Asynchronously called after processing.\n\n    Args:\n        exc_type (Optional[Type[BaseException]]): Type of the exception raised during processing.\n        exc_val (Optional[BaseException]): Value of the exception raised during processing.\n        exec_tb (Optional[TracebackType]): Traceback of the exception raised during processing.\n\n    Returns:\n        bool: True if the method is successfully executed.\n    \"\"\"\n    if self.logger is not None:\n        c = context.get_local(\"log_context\")\n\n        if exc_type and exc_val:\n            self.logger.error(\n                f\"{exc_type.__name__}: {exc_val}\",\n                exc_info=exc_val,\n                extra=c,\n            )\n\n        self.logger.log(self.log_level, \"Processed\", extra=c)\n    return True\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.after_publish","title":"after_publish async","text":"
after_publish(err: Optional[Exception]) -> None\n

Asynchronous function to handle the after publish event.

PARAMETER DESCRIPTION err

Optional exception that occurred during the publish

TYPE: Optional[Exception]

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION Exception

If an error occurred during the publish

Source code in faststream/broker/middlewares.py
async def after_publish(self, err: Optional[Exception]) -> None:\n    \"\"\"Asynchronous function to handle the after publish event.\n\n    Args:\n        err: Optional exception that occurred during the publish\n\n    Returns:\n        None\n\n    Raises:\n        Exception: If an error occurred during the publish\n    \"\"\"\n    if err is not None:\n        raise err\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.consume_scope","title":"consume_scope async","text":"
consume_scope(\n    msg: DecodedMessage,\n) -> AsyncIterator[DecodedMessage]\n

Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.

PARAMETER DESCRIPTION msg

The decoded message to consume.

TYPE: DecodedMessage

YIELDS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RETURNS DESCRIPTION AsyncIterator[DecodedMessage]

An asynchronous iterator of decoded messages.

RAISES DESCRIPTION Exception

If an error occurs while consuming the message.

AsyncIterator

An asynchronous iterator that yields decoded messages.

Note

This function is an async function.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def consume_scope(self, msg: DecodedMessage) -> AsyncIterator[DecodedMessage]:\n    \"\"\"Asynchronously consumes a message and returns an asynchronous iterator of decoded messages.\n\n    Args:\n        msg: The decoded message to consume.\n\n    Yields:\n        An asynchronous iterator of decoded messages.\n\n    Returns:\n        An asynchronous iterator of decoded messages.\n\n    Raises:\n        Exception: If an error occurs while consuming the message.\n\n    AsyncIterator:\n        An asynchronous iterator that yields decoded messages.\n\n    Note:\n        This function is an async function.\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_consume(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_consume(err)\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.on_consume","title":"on_consume async","text":"
on_consume(msg: DecodedMessage) -> DecodedMessage\n
Source code in faststream/broker/middlewares.py
async def on_consume(self, msg: DecodedMessage) -> DecodedMessage:\n    if self.logger is not None:\n        c = context.get_local(\"log_context\")\n        self.logger.log(self.log_level, \"Received\", extra=c)\n\n    return await super().on_consume(msg)\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.on_publish","title":"on_publish async","text":"
on_publish(msg: SendableMessage) -> SendableMessage\n

Asynchronously handle a publish event.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

RETURNS DESCRIPTION SendableMessage

The published message.

Source code in faststream/broker/middlewares.py
async def on_publish(self, msg: SendableMessage) -> SendableMessage:\n    \"\"\"Asynchronously handle a publish event.\n\n    Args:\n        msg: The message to be published.\n\n    Returns:\n        The published message.\n    \"\"\"\n    return msg\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.on_receive","title":"on_receive async","text":"
on_receive() -> None\n
Source code in faststream/broker/middlewares.py
async def on_receive(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/middlewares/CriticalLogMiddleware/#faststream.broker.middlewares.CriticalLogMiddleware.publish_scope","title":"publish_scope async","text":"
publish_scope(\n    msg: SendableMessage,\n) -> AsyncIterator[SendableMessage]\n

Publish a message and return an async iterator.

PARAMETER DESCRIPTION msg

The message to be published.

TYPE: SendableMessage

YIELDS DESCRIPTION AsyncIterator[SendableMessage]

A sendable message.

RETURNS DESCRIPTION AsyncIterator[SendableMessage]

An async iterator of sendable messages.

RAISES DESCRIPTION Exception

If an error occurs during publishing.

Source code in faststream/broker/middlewares.py
@asynccontextmanager\nasync def publish_scope(\n    self, msg: SendableMessage\n) -> AsyncIterator[SendableMessage]:\n    \"\"\"Publish a message and return an async iterator.\n\n    Args:\n        msg: The message to be published.\n\n    Yields:\n        A sendable message.\n\n    Returns:\n        An async iterator of sendable messages.\n\n    Raises:\n        Exception: If an error occurs during publishing.\n\n    \"\"\"\n    err: Optional[Exception]\n    try:\n        yield await self.on_publish(msg)\n    except Exception as e:\n        err = e\n    else:\n        err = None\n    await self.after_publish(err)\n
","boost":0.5},{"location":"api/faststream/broker/parsers/decode_message/","title":"decode_message","text":"","boost":0.5},{"location":"api/faststream/broker/parsers/decode_message/#faststream.broker.parsers.decode_message","title":"faststream.broker.parsers.decode_message","text":"
decode_message(\n    message: StreamMessage[Any],\n) -> DecodedMessage\n

Decodes a message.

PARAMETER DESCRIPTION message

The message to decode.

TYPE: StreamMessage[Any]

RETURNS DESCRIPTION DecodedMessage

The decoded message.

RAISES DESCRIPTION JSONDecodeError

If the message body cannot be decoded as JSON.

Source code in faststream/broker/parsers.py
def decode_message(message: StreamMessage[Any]) -> DecodedMessage:\n    \"\"\"Decodes a message.\n\n    Args:\n        message: The message to decode.\n\n    Returns:\n        The decoded message.\n\n    Raises:\n        JSONDecodeError: If the message body cannot be decoded as JSON.\n\n    \"\"\"\n    body: Any = getattr(message, \"body\", message)\n    m: DecodedMessage = body\n\n    if content_type := getattr(message, \"content_type\", None):\n        if ContentTypes.text.value in content_type:\n            m = body.decode()\n        elif ContentTypes.json.value in content_type:  # pragma: no branch\n            m = json.loads(body)\n\n    else:\n        with suppress(json.JSONDecodeError):\n            m = json.loads(body)\n\n    return m\n
","boost":0.5},{"location":"api/faststream/broker/parsers/encode_message/","title":"encode_message","text":"","boost":0.5},{"location":"api/faststream/broker/parsers/encode_message/#faststream.broker.parsers.encode_message","title":"faststream.broker.parsers.encode_message","text":"
encode_message(\n    msg: SendableMessage,\n) -> Tuple[bytes, Optional[ContentType]]\n

Encodes a message.

PARAMETER DESCRIPTION msg

The message to be encoded.

TYPE: SendableMessage

RETURNS DESCRIPTION Tuple[bytes, Optional[ContentType]]

A tuple containing the encoded message as bytes and the content type of the message.

Source code in faststream/broker/parsers.py
def encode_message(msg: SendableMessage) -> Tuple[bytes, Optional[ContentType]]:\n    \"\"\"Encodes a message.\n\n    Args:\n        msg: The message to be encoded.\n\n    Returns:\n        A tuple containing the encoded message as bytes and the content type of the message.\n\n    \"\"\"\n    if msg is None:\n        return b\"\", None\n\n    if isinstance(msg, bytes):\n        return msg, None\n\n    if isinstance(msg, str):\n        return msg.encode(), ContentTypes.text.value\n\n    return (\n        dump_json(msg).encode(),\n        ContentTypes.json.value,\n    )\n
","boost":0.5},{"location":"api/faststream/broker/parsers/resolve_custom_func/","title":"resolve_custom_func","text":"","boost":0.5},{"location":"api/faststream/broker/parsers/resolve_custom_func/#faststream.broker.parsers.resolve_custom_func","title":"faststream.broker.parsers.resolve_custom_func","text":"
resolve_custom_func(\n    custom_func: Optional[\n        Union[\n            CustomDecoder[StreamMsg],\n            CustomParser[MsgType, StreamMsg],\n        ]\n    ],\n    default_func: Union[\n        Decoder[StreamMsg], Parser[MsgType, StreamMsg]\n    ],\n) -> Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]]\n

Resolve a custom function.

PARAMETER DESCRIPTION custom_func

Optional custom function of type CustomDecoder or CustomParser.

TYPE: Optional[Union[CustomDecoder[StreamMsg], CustomParser[MsgType, StreamMsg]]]

default_func

Default function of type Decoder or Parser.

TYPE: Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]]

RETURNS DESCRIPTION Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]]

The resolved function of type Decoder or Parser.

Source code in faststream/broker/parsers.py
def resolve_custom_func(  # type: ignore[misc]\n    custom_func: Optional[\n        Union[CustomDecoder[StreamMsg], CustomParser[MsgType, StreamMsg]]\n    ],\n    default_func: Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]],\n) -> Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]]:\n    \"\"\"Resolve a custom function.\n\n    Args:\n        custom_func: Optional custom function of type CustomDecoder or CustomParser.\n        default_func: Default function of type Decoder or Parser.\n\n    Returns:\n        The resolved function of type Decoder or Parser.\n\n    \"\"\"\n    if custom_func is None:\n        return default_func\n\n    original_params = inspect.signature(custom_func).parameters\n    if len(original_params) == 1:\n        return cast(Union[Decoder[StreamMsg], Parser[MsgType, StreamMsg]], custom_func)\n\n    else:\n        name = tuple(original_params.items())[1][0]\n        return partial(custom_func, **{name: default_func})  # type: ignore\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/","title":"BasePublisher","text":"","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher","title":"faststream.broker.publisher.BasePublisher dataclass","text":"

Bases: AsyncAPIOperation, Generic[MsgType]

A base class for publishers in an asynchronous API.

METHOD DESCRIPTION description

returns the description of the publisher

__call__

decorator to register a function as a handler for the publisher

publish

publishes a message with optional correlation ID

RAISES DESCRIPTION NotImplementedError

if the publish method is not implemented.

","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.publish","title":"publish abstractmethod async","text":"
publish(\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

correlation_id

Optional correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/publisher.py
@abstractmethod\nasync def publish(\n    self,\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        correlation_id: Optional correlation ID for the message.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/broker/publisher/BasePublisher/#faststream.broker.publisher.BasePublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/","title":"BaseWatcher","text":"","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher","title":"faststream.broker.push_back_watcher.BaseWatcher","text":"
BaseWatcher(\n    max_tries: int = 0, logger: Optional[Logger] = None\n)\n

Bases: ABC

A base class for a watcher.

PARAMETER DESCRIPTION max_tries

maximum number of tries allowed (default=0)

DEFAULT: 0

logger

logger object (optional)

DEFAULT: None

METHOD DESCRIPTION add

add a message to the watcher

is_max

check if the maximum number of tries has been reached for a message

remove

remove a message from the watcher

Initialize the class.

PARAMETER DESCRIPTION max_tries

Maximum number of tries allowed

TYPE: int DEFAULT: 0

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented in the subclass.

Source code in faststream/broker/push_back_watcher.py
def __init__(\n    self,\n    max_tries: int = 0,\n    logger: Optional[Logger] = None,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        max_tries: Maximum number of tries allowed\n        logger: Optional logger object\n\n    Raises:\n        NotImplementedError: If the method is not implemented in the subclass.\n\n    \"\"\"\n    self.logger = logger\n    self.max_tries = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher.max_tries","title":"max_tries instance-attribute","text":"
max_tries: int = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher.add","title":"add abstractmethod","text":"
add(message_id: str) -> None\n

Add a message.

PARAMETER DESCRIPTION message_id

ID of the message to be added

TYPE: str

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/push_back_watcher.py
@abstractmethod\ndef add(self, message_id: str) -> None:\n    \"\"\"Add a message.\n\n    Args:\n        message_id: ID of the message to be added\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher.is_max","title":"is_max abstractmethod","text":"
is_max(message_id: str) -> bool\n

Check if the given message ID is the maximum.

PARAMETER DESCRIPTION message_id

The ID of the message to check.

TYPE: str

RETURNS DESCRIPTION bool

True if the given message ID is the maximum, False otherwise.

RAISES DESCRIPTION NotImplementedError

This method is meant to be overridden by subclasses.

Source code in faststream/broker/push_back_watcher.py
@abstractmethod\ndef is_max(self, message_id: str) -> bool:\n    \"\"\"Check if the given message ID is the maximum.\n\n    Args:\n        message_id: The ID of the message to check.\n\n    Returns:\n        True if the given message ID is the maximum, False otherwise.\n\n    Raises:\n        NotImplementedError: This method is meant to be overridden by subclasses.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/BaseWatcher/#faststream.broker.push_back_watcher.BaseWatcher.remove","title":"remove abstractmethod","text":"
remove(message_id: str) -> None\n

Remove a message.

PARAMETER DESCRIPTION message_id

ID of the message to be removed

TYPE: str

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/push_back_watcher.py
@abstractmethod\ndef remove(self, message_id: str) -> None:\n    \"\"\"Remove a message.\n\n    Args:\n        message_id: ID of the message to be removed\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/","title":"CounterWatcher","text":"","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher","title":"faststream.broker.push_back_watcher.CounterWatcher","text":"
CounterWatcher(\n    max_tries: int = 3, logger: Optional[Logger] = None\n)\n

Bases: BaseWatcher

A class to watch and track the count of messages.

PARAMETER DESCRIPTION max_tries

int - maximum number of tries allowed

DEFAULT: 3

logger

Optional[Logger] - logger object for logging messages

DEFAULT: None

METHOD DESCRIPTION add

str) -> None - adds a message to the counter

is_max

str) -> bool - checks if the count of a message has reached the maximum tries

remove

str) -> None - removes a message from the counter

Initialize the class.

PARAMETER DESCRIPTION max_tries

maximum number of tries

TYPE: int DEFAULT: 3

logger

logger object (default: None)

TYPE: Optional[Logger] DEFAULT: None

Source code in faststream/broker/push_back_watcher.py
def __init__(\n    self,\n    max_tries: int = 3,\n    logger: Optional[Logger] = None,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        max_tries (int): maximum number of tries\n        logger (Optional[Logger]): logger object (default: None)\n\n    \"\"\"\n    super().__init__(logger=logger, max_tries=max_tries)\n    self.memory = Counter()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.max_tries","title":"max_tries instance-attribute","text":"
max_tries: int = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.memory","title":"memory instance-attribute","text":"
memory: CounterType[str] = Counter()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.add","title":"add","text":"
add(message_id: str) -> None\n

Increments the count of a message in the memory.

PARAMETER DESCRIPTION message_id

The ID of the message to be incremented.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def add(self, message_id: str) -> None:\n    \"\"\"Increments the count of a message in the memory.\n\n    Args:\n        message_id: The ID of the message to be incremented.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.memory[message_id] += 1\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.is_max","title":"is_max","text":"
is_max(message_id: str) -> bool\n

Check if the number of tries for a message has exceeded the maximum allowed tries.

PARAMETER DESCRIPTION message_id

The ID of the message

TYPE: str

RETURNS DESCRIPTION bool

True if the number of tries has exceeded the maximum allowed tries, False otherwise

Source code in faststream/broker/push_back_watcher.py
def is_max(self, message_id: str) -> bool:\n    \"\"\"Check if the number of tries for a message has exceeded the maximum allowed tries.\n\n    Args:\n        message_id: The ID of the message\n\n    Returns:\n        True if the number of tries has exceeded the maximum allowed tries, False otherwise\n\n    \"\"\"\n    is_max = self.memory[message_id] > self.max_tries\n    if self.logger is not None:\n        if is_max:\n            self.logger.error(f\"Already retried {self.max_tries} times. Skipped.\")\n        else:\n            self.logger.error(\"Error is occured. Pushing back to queue.\")\n    return is_max\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/CounterWatcher/#faststream.broker.push_back_watcher.CounterWatcher.remove","title":"remove","text":"
remove(message: str) -> None\n

Remove a message from memory.

PARAMETER DESCRIPTION message

The message to be removed.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def remove(self, message: str) -> None:\n    \"\"\"Remove a message from memory.\n\n    Args:\n        message: The message to be removed.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.memory[message] = 0\n    self.memory += Counter()\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/","title":"EndlessWatcher","text":"","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher","title":"faststream.broker.push_back_watcher.EndlessWatcher","text":"
EndlessWatcher(\n    max_tries: int = 0, logger: Optional[Logger] = None\n)\n

Bases: BaseWatcher

Initialize the class.

PARAMETER DESCRIPTION max_tries

Maximum number of tries allowed

TYPE: int DEFAULT: 0

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented in the subclass.

Source code in faststream/broker/push_back_watcher.py
def __init__(\n    self,\n    max_tries: int = 0,\n    logger: Optional[Logger] = None,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        max_tries: Maximum number of tries allowed\n        logger: Optional logger object\n\n    Raises:\n        NotImplementedError: If the method is not implemented in the subclass.\n\n    \"\"\"\n    self.logger = logger\n    self.max_tries = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher.max_tries","title":"max_tries instance-attribute","text":"
max_tries: int = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher.add","title":"add","text":"
add(message_id: str) -> None\n

Add a message to the list.

PARAMETER DESCRIPTION message_id

ID of the message to be added

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def add(self, message_id: str) -> None:\n    \"\"\"Add a message to the list.\n\n    Args:\n        message_id: ID of the message to be added\n\n    Returns:\n        None\n\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher.is_max","title":"is_max","text":"
is_max(message_id: str) -> bool\n

Check if a message is the maximum.

PARAMETER DESCRIPTION message_id

ID of the message to check

TYPE: str

RETURNS DESCRIPTION bool

True if the message is the maximum, False otherwise

Source code in faststream/broker/push_back_watcher.py
def is_max(self, message_id: str) -> bool:\n    \"\"\"Check if a message is the maximum.\n\n    Args:\n        message_id: ID of the message to check\n\n    Returns:\n        True if the message is the maximum, False otherwise\n\n    \"\"\"\n    return False\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/EndlessWatcher/#faststream.broker.push_back_watcher.EndlessWatcher.remove","title":"remove","text":"
remove(message_id: str) -> None\n

Remove a message.

PARAMETER DESCRIPTION message_id

The ID of the message to be removed.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def remove(self, message_id: str) -> None:\n    \"\"\"Remove a message.\n\n    Args:\n        message_id: The ID of the message to be removed.\n\n    Returns:\n        None\n\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/","title":"OneTryWatcher","text":"","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher","title":"faststream.broker.push_back_watcher.OneTryWatcher","text":"
OneTryWatcher(\n    max_tries: int = 0, logger: Optional[Logger] = None\n)\n

Bases: BaseWatcher

Initialize the class.

PARAMETER DESCRIPTION max_tries

Maximum number of tries allowed

TYPE: int DEFAULT: 0

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented in the subclass.

Source code in faststream/broker/push_back_watcher.py
def __init__(\n    self,\n    max_tries: int = 0,\n    logger: Optional[Logger] = None,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        max_tries: Maximum number of tries allowed\n        logger: Optional logger object\n\n    Raises:\n        NotImplementedError: If the method is not implemented in the subclass.\n\n    \"\"\"\n    self.logger = logger\n    self.max_tries = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher.max_tries","title":"max_tries instance-attribute","text":"
max_tries: int = max_tries\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher.add","title":"add","text":"
add(message_id: str) -> None\n

Add a message.

PARAMETER DESCRIPTION message_id

ID of the message to be added

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def add(self, message_id: str) -> None:\n    \"\"\"Add a message.\n\n    Args:\n        message_id: ID of the message to be added\n\n    Returns:\n        None\n\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher.is_max","title":"is_max","text":"
is_max(message_id: str) -> bool\n

Check if the given message ID is the maximum.

PARAMETER DESCRIPTION message_id

The ID of the message to check.

TYPE: str

RETURNS DESCRIPTION bool

True if the given message ID is the maximum, False otherwise.

Source code in faststream/broker/push_back_watcher.py
def is_max(self, message_id: str) -> bool:\n    \"\"\"Check if the given message ID is the maximum.\n\n    Args:\n        message_id: The ID of the message to check.\n\n    Returns:\n        True if the given message ID is the maximum, False otherwise.\n\n    \"\"\"\n    return True\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/OneTryWatcher/#faststream.broker.push_back_watcher.OneTryWatcher.remove","title":"remove","text":"
remove(message_id: str) -> None\n

Remove a message.

PARAMETER DESCRIPTION message_id

ID of the message to be removed

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/push_back_watcher.py
def remove(self, message_id: str) -> None:\n    \"\"\"Remove a message.\n\n    Args:\n        message_id: ID of the message to be removed\n\n    Returns:\n        None\n\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/WatcherContext/","title":"WatcherContext","text":"","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/WatcherContext/#faststream.broker.push_back_watcher.WatcherContext","title":"faststream.broker.push_back_watcher.WatcherContext","text":"
WatcherContext(\n    message: Union[\n        SyncStreamMessage[MsgType], StreamMessage[MsgType]\n    ],\n    watcher: BaseWatcher,\n    **extra_ack_args: Any\n)\n

A class representing a context for a watcher.

METHOD DESCRIPTION __aenter__

called when entering the context

__aexit__

called when exiting the context

__ack

acknowledges the message

__nack

negatively acknowledges the message

__reject

rejects the message

Initialize a new instance of the class.

PARAMETER DESCRIPTION watcher

An instance of BaseWatcher.

TYPE: BaseWatcher

message

An instance of SyncStreamMessage or StreamMessage.

TYPE: Union[SyncStreamMessage[MsgType], StreamMessage[MsgType]]

**extra_ack_args

Additional arguments for acknowledgement.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/push_back_watcher.py
def __init__(\n    self,\n    message: Union[SyncStreamMessage[MsgType], StreamMessage[MsgType]],\n    watcher: BaseWatcher,\n    **extra_ack_args: Any,\n) -> None:\n    \"\"\"Initialize a new instance of the class.\n\n    Args:\n        watcher: An instance of BaseWatcher.\n        message: An instance of SyncStreamMessage or StreamMessage.\n        **extra_ack_args: Additional arguments for acknowledgement.\n\n    Attributes:\n        watcher: An instance of BaseWatcher.\n        message: An instance of SyncStreamMessage or StreamMessage.\n        extra_ack_args: Additional arguments for acknowledgement.\n\n    \"\"\"\n    self.watcher = watcher\n    self.message = message\n    self.extra_ack_args = extra_ack_args or {}\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/WatcherContext/#faststream.broker.push_back_watcher.WatcherContext.extra_ack_args","title":"extra_ack_args instance-attribute","text":"
extra_ack_args = extra_ack_args or {}\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/WatcherContext/#faststream.broker.push_back_watcher.WatcherContext.message","title":"message instance-attribute","text":"
message = message\n
","boost":0.5},{"location":"api/faststream/broker/push_back_watcher/WatcherContext/#faststream.broker.push_back_watcher.WatcherContext.watcher","title":"watcher instance-attribute","text":"
watcher = watcher\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRoute/","title":"BrokerRoute","text":"","boost":0.5},{"location":"api/faststream/broker/router/BrokerRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/","title":"BrokerRouter","text":"","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter","title":"faststream.broker.router.BrokerRouter","text":"
BrokerRouter(\n    prefix: str = \"\",\n    handlers: Sequence[\n        BrokerRoute[MsgType, SendableMessage]\n    ] = (),\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    include_in_schema: Optional[bool] = None,\n)\n

Bases: Generic[PublisherKeyType, MsgType]

A generic class representing a broker router.

METHOD DESCRIPTION _get_publisher_key

abstract method to get the publisher key

_update_publisher_prefix

abstract method to update the publisher prefix

__init__

constructor method

subscriber

abstract method to define a subscriber

_wrap_subscriber

method to wrap a subscriber function

publisher

abstract method to define a publisher

include_router

method to include a router

include_routers

method to include multiple routers

Initialize a class object.

PARAMETER DESCRIPTION prefix

Prefix for the object.

TYPE: str DEFAULT: ''

handlers

Handlers for the object.

TYPE: Sequence[BrokerRoute[MsgType, SendableMessage]] DEFAULT: ()

dependencies

Dependencies for the object.

TYPE: Sequence[Depends] DEFAULT: ()

middlewares

Middlewares for the object.

TYPE: Optional[Sequence[Callable[[StreamMessage[MsgType]], AsyncContextManager[None]]]] DEFAULT: None

parser

Parser for the object.

TYPE: Optional[CustomParser[MsgType]] DEFAULT: None

decoder

Decoder for the object.

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

Source code in faststream/broker/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[BrokerRoute[MsgType, SendableMessage]] = (),\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    include_in_schema: Optional[bool] = None,\n) -> None:\n    \"\"\"Initialize a class object.\n\n    Args:\n        prefix (str): Prefix for the object.\n        handlers (Sequence[BrokerRoute[MsgType, SendableMessage]]): Handlers for the object.\n        dependencies (Sequence[Depends]): Dependencies for the object.\n        middlewares (Optional[Sequence[Callable[[StreamMessage[MsgType]], AsyncContextManager[None]]]]): Middlewares for the object.\n        parser (Optional[CustomParser[MsgType]]): Parser for the object.\n        decoder (Optional[CustomDecoder[StreamMessage[MsgType]]]): Decoder for the object.\n\n    \"\"\"\n    self.prefix = prefix\n    self.include_in_schema = include_in_schema\n    self._handlers = list(handlers)\n    self._publishers = {}\n    self._dependencies = dependencies\n    self._middlewares = middlewares\n    self._parser = parser\n    self._decoder = decoder\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/router/BrokerRouter/#faststream.broker.router.BrokerRouter.subscriber","title":"subscriber abstractmethod","text":"
subscriber(\n    subj: str,\n    *args: Any,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    include_in_schema: Optional[bool] = None,\n    **kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function to subscribe to a subject.

PARAMETER DESCRIPTION subj

subject to subscribe to

*args

additional arguments

DEFAULT: ()

dependencies

sequence of dependencies

DEFAULT: ()

middlewares

optional sequence of middlewares

DEFAULT: None

parser

optional custom parser

DEFAULT: None

decoder

optional custom decoder

DEFAULT: None

**kwargs

additional keyword arguments

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable handler function

RAISES DESCRIPTION NotImplementedError

If the function is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef subscriber(\n    self,\n    subj: str,\n    *args: Any,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    include_in_schema: Optional[bool] = None,\n    **kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function to subscribe to a subject.\n\n    Args:\n        subj : subject to subscribe to\n        *args : additional arguments\n        dependencies : sequence of dependencies\n        middlewares : optional sequence of middlewares\n        parser : optional custom parser\n        decoder : optional custom decoder\n        **kwargs : additional keyword arguments\n\n    Returns:\n        A callable handler function\n\n    Raises:\n        NotImplementedError: If the function is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/schemas/NameRequired/","title":"NameRequired","text":"","boost":0.5},{"location":"api/faststream/broker/schemas/NameRequired/#faststream.broker.schemas.NameRequired","title":"faststream.broker.schemas.NameRequired","text":"
NameRequired(name: str, **kwargs: Any)\n

Bases: BaseModel

A class to represent a required name.

METHOD DESCRIPTION __eq__

object) -> bool: Check if the given value is equal to the current instance.

validate

Type[NameRequiredCls], value: Union[str, NameRequiredCls]) -> NameRequiredCls: Validate the given value and return a NameRequiredCls instance.

validate

Type[NameRequiredCls], value: None) -> None: Validate the given value and return None.

validate

Type[NameRequiredCls], value: Union[str, NameRequiredCls, None]) -> Optional[NameRequiredCls]: Validate the given value and return an optional NameRequiredCls instance.

This is a Python function.

PARAMETER DESCRIPTION name

The name of the object.

TYPE: str

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None.

Source code in faststream/broker/schemas.py
def __init__(self, name: str, **kwargs: Any) -> None:\n    \"\"\"This is a Python function.\n\n    Args:\n        name (str): The name of the object.\n        **kwargs (Any): Additional keyword arguments.\n\n    Returns:\n        None.\n\n    \"\"\"\n    super().__init__(name=name, **kwargs)\n
","boost":0.5},{"location":"api/faststream/broker/schemas/NameRequired/#faststream.broker.schemas.NameRequired.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/broker/schemas/NameRequired/#faststream.broker.schemas.NameRequired.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/broker/schemas/RawDecoced/","title":"RawDecoced","text":"","boost":0.5},{"location":"api/faststream/broker/schemas/RawDecoced/#faststream.broker.schemas.RawDecoced","title":"faststream.broker.schemas.RawDecoced","text":"

Bases: BaseModel

A class to represent a raw decoded message.

","boost":0.5},{"location":"api/faststream/broker/schemas/RawDecoced/#faststream.broker.schemas.RawDecoced.message","title":"message instance-attribute","text":"
message: Union[Json[Any], str]\n
","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/","title":"BaseSecurity","text":"","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/#faststream.security.BaseSecurity","title":"faststream.security.BaseSecurity","text":"
BaseSecurity(\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Base class for defining security configurations.

This class provides a base for defining security configurations for communication with a broker. It allows setting SSL encryption and provides methods to retrieve security requirements and schemas.

PARAMETER DESCRIPTION ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements in the form of a list of dictionaries.

get_schema

Get the security schema as a dictionary.

Source code in faststream/security.py
def __init__(\n    self,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    if ssl_context is not None:\n        use_ssl = True\n\n    self.use_ssl = use_ssl\n    self.ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/#faststream.security.BaseSecurity.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/#faststream.security.BaseSecurity.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/#faststream.security.BaseSecurity.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return []\n
","boost":0.5},{"location":"api/faststream/broker/security/BaseSecurity/#faststream.security.BaseSecurity.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {}\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/","title":"SASLPlaintext","text":"","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext","title":"faststream.security.SASLPlaintext","text":"
SASLPlaintext(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/PLAINTEXT authentication.

This class defines security configuration for SASL/PLAINTEXT authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/PLAINTEXT authentication.

get_schema

Get the security schema for SASL/PLAINTEXT authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/PLAINTEXT authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/PLAINTEXT authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"user-password\": []}]\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLPlaintext/#faststream.security.SASLPlaintext.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/PLAINTEXT authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/PLAINTEXT authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"user-password\": {\"type\": \"userPassword\"}}\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/","title":"SASLScram256","text":"","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256","title":"faststream.security.SASLScram256","text":"
SASLScram256(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/SCRAM-SHA-256 authentication.

This class defines security configuration for SASL/SCRAM-SHA-256 authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/SCRAM-SHA-256 authentication.

get_schema

Get the security schema for SASL/SCRAM-SHA-256 authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/SCRAM-SHA-256 authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/SCRAM-SHA-256 authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"scram256\": []}]\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram256/#faststream.security.SASLScram256.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/SCRAM-SHA-256 authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/SCRAM-SHA-256 authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"scram256\": {\"type\": \"scramSha256\"}}\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/","title":"SASLScram512","text":"","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512","title":"faststream.security.SASLScram512","text":"
SASLScram512(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/SCRAM-SHA-512 authentication.

This class defines security configuration for SASL/SCRAM-SHA-512 authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/SCRAM-SHA-512 authentication.

get_schema

Get the security schema for SASL/SCRAM-SHA-512 authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/SCRAM-SHA-512 authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/SCRAM-SHA-512 authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"scram512\": []}]\n
","boost":0.5},{"location":"api/faststream/broker/security/SASLScram512/#faststream.security.SASLScram512.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/SCRAM-SHA-512 authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/SCRAM-SHA-512 authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"scram512\": {\"type\": \"scramSha512\"}}\n
","boost":0.5},{"location":"api/faststream/broker/test/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/broker/test/TestApp/#faststream.broker.test.TestApp","title":"faststream.broker.test.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/broker/test/TestApp/#faststream.broker.test.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/","title":"TestBroker","text":"","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker","title":"faststream.broker.test.TestBroker","text":"
TestBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: Generic[Broker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber abstractmethod staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: Broker, publisher: Any\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/broker/test.py
@staticmethod\n@abstractmethod\ndef create_publisher_fake_subscriber(\n    broker: Broker, publisher: Any\n) -> HandlerCallWrapper[Any, Any, Any]:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.patch_publisher","title":"patch_publisher abstractmethod staticmethod","text":"
patch_publisher(broker: Broker, publisher: Any) -> None\n
Source code in faststream/broker/test.py
@staticmethod\n@abstractmethod\ndef patch_publisher(broker: Broker, publisher: Any) -> None:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/test/TestBroker/#faststream.broker.test.TestBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber abstractmethod staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: Broker, publisher: Any\n) -> None\n
Source code in faststream/broker/test.py
@staticmethod\n@abstractmethod\ndef remove_publisher_fake_subscriber(broker: Broker, publisher: Any) -> None:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/broker/test/call_handler/","title":"call_handler","text":"","boost":0.5},{"location":"api/faststream/broker/test/call_handler/#faststream.broker.test.call_handler","title":"faststream.broker.test.call_handler async","text":"
call_handler(\n    handler: AsyncHandler[Any],\n    message: Any,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[SendableMessage]\n

Asynchronously call a handler function.

PARAMETER DESCRIPTION handler

The handler function to be called.

TYPE: AsyncHandler[Any]

message

The message to be passed to the handler function.

TYPE: Any

rpc

Whether the call is a remote procedure call (RPC).

TYPE: bool DEFAULT: False

rpc_timeout

The timeout for the RPC, in seconds.

TYPE: Optional[float] DEFAULT: 30.0

raise_timeout

Whether to raise a timeout error if the RPC times out.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION Optional[SendableMessage]

The result of the handler function if rpc is True, otherwise None.

RAISES DESCRIPTION TimeoutError

If the RPC times out and raise_timeout is True.

Source code in faststream/broker/test.py
async def call_handler(\n    handler: AsyncHandler[Any],\n    message: Any,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[SendableMessage]:\n    \"\"\"Asynchronously call a handler function.\n\n    Args:\n        handler: The handler function to be called.\n        message: The message to be passed to the handler function.\n        rpc: Whether the call is a remote procedure call (RPC).\n        rpc_timeout: The timeout for the RPC, in seconds.\n        raise_timeout: Whether to raise a timeout error if the RPC times out.\n\n    Returns:\n        The result of the handler function if `rpc` is True, otherwise None.\n\n    Raises:\n        TimeoutError: If the RPC times out and `raise_timeout` is True.\n\n    \"\"\"\n    with timeout_scope(rpc_timeout, raise_timeout):\n        result = await handler.consume(message)\n\n        if rpc is True:\n            return result\n\n    return None\n
","boost":0.5},{"location":"api/faststream/broker/test/patch_broker_calls/","title":"patch_broker_calls","text":"","boost":0.5},{"location":"api/faststream/broker/test/patch_broker_calls/#faststream.broker.test.patch_broker_calls","title":"faststream.broker.test.patch_broker_calls","text":"
patch_broker_calls(broker: BrokerUsecase[Any, Any]) -> None\n

Patch broker calls.

PARAMETER DESCRIPTION broker

The broker to patch.

TYPE: BrokerUsecase[Any, Any]

RETURNS DESCRIPTION None

None.

Source code in faststream/broker/test.py
def patch_broker_calls(broker: BrokerUsecase[Any, Any]) -> None:\n    \"\"\"Patch broker calls.\n\n    Args:\n        broker: The broker to patch.\n\n    Returns:\n        None.\n\n    \"\"\"\n    broker.middlewares = tuple(\n        filter(  # type: ignore[assignment]\n            lambda x: not isinstance(x, CriticalLogMiddleware),\n            broker.middlewares,\n        )\n    )\n    broker._abc_start()\n\n    for handler in broker.handlers.values():\n        for f, _, _, _, _, _ in handler.calls:\n            f.set_test()\n
","boost":0.5},{"location":"api/faststream/broker/types/AsyncPublisherProtocol/","title":"AsyncPublisherProtocol","text":"","boost":0.5},{"location":"api/faststream/broker/types/AsyncPublisherProtocol/#faststream.broker.types.AsyncPublisherProtocol","title":"faststream.broker.types.AsyncPublisherProtocol","text":"

Bases: Protocol

A protocol for an asynchronous publisher.

METHOD DESCRIPTION publish

SendableMessage, correlation_id: Optional[str] = None, **kwargs: Any) -> Optional[SendableMessage]: Publishes a message asynchronously.

Args: message: The message to be published. correlation_id: The correlation ID for the message (optional). **kwargs: Additional keyword arguments.

Returns: The published message (optional).

","boost":0.5},{"location":"api/faststream/broker/types/AsyncPublisherProtocol/#faststream.broker.types.AsyncPublisherProtocol.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publishes a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

correlation_id

Optional correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message, or None if the message was not published.

Source code in faststream/broker/types.py
async def publish(\n    self,\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publishes a message.\n\n    Args:\n        message: The message to be published.\n        correlation_id: Optional correlation ID for the message.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message, or None if the message was not published.\n\n    \"\"\"\n    ...\n
","boost":0.5},{"location":"api/faststream/broker/utils/change_logger_handlers/","title":"change_logger_handlers","text":"","boost":0.5},{"location":"api/faststream/broker/utils/change_logger_handlers/#faststream.broker.utils.change_logger_handlers","title":"faststream.broker.utils.change_logger_handlers","text":"
change_logger_handlers(\n    logger: logging.Logger, fmt: str\n) -> None\n

Change the formatter of the logger handlers.

PARAMETER DESCRIPTION logger

The logger object.

TYPE: Logger

fmt

The format string for the formatter.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/broker/utils.py
def change_logger_handlers(logger: logging.Logger, fmt: str) -> None:\n    \"\"\"Change the formatter of the logger handlers.\n\n    Args:\n        logger (logging.Logger): The logger object.\n        fmt (str): The format string for the formatter.\n\n    Returns:\n        None\n\n    \"\"\"\n    for handler in getattr(logger, \"handlers\", ()):\n        formatter = handler.formatter\n        if formatter is not None:  # pragma: no branch\n            use_colors = getattr(formatter, \"use_colors\", None)\n            if use_colors is not None:  # pragma: no branch\n                kwargs = {\"use_colors\": use_colors}\n            else:  # pragma: no cover\n                kwargs = {}\n            handler.setFormatter(type(formatter)(fmt, **kwargs))\n
","boost":0.5},{"location":"api/faststream/broker/utils/get_watcher/","title":"get_watcher","text":"","boost":0.5},{"location":"api/faststream/broker/utils/get_watcher/#faststream.broker.utils.get_watcher","title":"faststream.broker.utils.get_watcher","text":"
get_watcher(\n    logger: Optional[logging.Logger],\n    try_number: Union[bool, int] = True,\n) -> BaseWatcher\n

Get a watcher object based on the provided parameters.

PARAMETER DESCRIPTION logger

Optional logger object for logging messages.

TYPE: Optional[Logger]

try_number

Optional parameter to specify the type of watcher. - If set to True, an EndlessWatcher object will be returned. - If set to False, a OneTryWatcher object will be returned. - If set to an integer, a CounterWatcher object with the specified maximum number of tries will be returned.

TYPE: Union[bool, int] DEFAULT: True

RETURNS DESCRIPTION BaseWatcher

A watcher object based on the provided parameters.

Source code in faststream/broker/utils.py
def get_watcher(\n    logger: Optional[logging.Logger],\n    try_number: Union[bool, int] = True,\n) -> BaseWatcher:\n    \"\"\"Get a watcher object based on the provided parameters.\n\n    Args:\n        logger: Optional logger object for logging messages.\n        try_number: Optional parameter to specify the type of watcher.\n            - If set to True, an EndlessWatcher object will be returned.\n            - If set to False, a OneTryWatcher object will be returned.\n            - If set to an integer, a CounterWatcher object with the specified maximum number of tries will be returned.\n\n    Returns:\n        A watcher object based on the provided parameters.\n\n    \"\"\"\n    watcher: Optional[BaseWatcher]\n    if try_number is True:\n        watcher = EndlessWatcher()\n    elif try_number is False:\n        watcher = OneTryWatcher()\n    else:\n        watcher = CounterWatcher(logger=logger, max_tries=try_number)\n    return watcher\n
","boost":0.5},{"location":"api/faststream/broker/utils/set_message_context/","title":"set_message_context","text":"","boost":0.5},{"location":"api/faststream/broker/utils/set_message_context/#faststream.broker.utils.set_message_context","title":"faststream.broker.utils.set_message_context","text":"
set_message_context(\n    func: Callable[\n        [StreamMessage[MsgType]],\n        Awaitable[WrappedReturn[T_HandlerReturn]],\n    ]\n) -> Callable[\n    [StreamMessage[MsgType]],\n    Awaitable[WrappedReturn[T_HandlerReturn]],\n]\n

Sets the message context for a function.

PARAMETER DESCRIPTION func

The function to set the message context for.

TYPE: Callable[[StreamMessage[MsgType]], Awaitable[WrappedReturn[T_HandlerReturn]]]

RETURNS DESCRIPTION Callable[[StreamMessage[MsgType]], Awaitable[WrappedReturn[T_HandlerReturn]]]

The function with the message context set.

Source code in faststream/broker/utils.py
def set_message_context(\n    func: Callable[\n        [StreamMessage[MsgType]],\n        Awaitable[WrappedReturn[T_HandlerReturn]],\n    ],\n) -> Callable[[StreamMessage[MsgType]], Awaitable[WrappedReturn[T_HandlerReturn]]]:\n    \"\"\"Sets the message context for a function.\n\n    Args:\n        func: The function to set the message context for.\n\n    Returns:\n        The function with the message context set.\n\n    \"\"\"\n\n    @wraps(func)\n    async def set_message_wrapper(\n        message: StreamMessage[MsgType],\n    ) -> WrappedReturn[T_HandlerReturn]:\n        \"\"\"Wraps a function that handles a stream message.\n\n        Args:\n            message: The stream message to be handled.\n\n        Returns:\n            The wrapped return value of the handler function.\n\n        \"\"\"\n        with context.scope(\"message\", message):\n            return await func(message)\n\n    return set_message_wrapper\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/FakePublisher/","title":"FakePublisher","text":"","boost":0.5},{"location":"api/faststream/broker/wrapper/FakePublisher/#faststream.broker.wrapper.FakePublisher","title":"faststream.broker.wrapper.FakePublisher","text":"
FakePublisher(\n    method: Callable[..., Awaitable[SendableMessage]]\n)\n

A class to represent a fake publisher.

METHOD DESCRIPTION publish

asynchronously publishes a message with optional correlation ID and additional keyword arguments

Initialize an object.

PARAMETER DESCRIPTION method

A callable that takes any number of arguments and returns an awaitable sendable message.

TYPE: Callable[..., Awaitable[SendableMessage]]

Source code in faststream/broker/wrapper.py
def __init__(self, method: Callable[..., Awaitable[SendableMessage]]) -> None:\n    \"\"\"Initialize an object.\n\n    Args:\n        method: A callable that takes any number of arguments and returns an awaitable sendable message.\n\n    \"\"\"\n    self.method = method\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/FakePublisher/#faststream.broker.wrapper.FakePublisher.method","title":"method instance-attribute","text":"
method = method\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/FakePublisher/#faststream.broker.wrapper.FakePublisher.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

correlation_id

Optional correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message.

Source code in faststream/broker/wrapper.py
async def publish(\n    self,\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        correlation_id: Optional correlation ID for the message.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message.\n\n    \"\"\"\n    return await self.method(message, correlation_id=correlation_id, **kwargs)\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/","title":"HandlerCallWrapper","text":"","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper","title":"faststream.broker.wrapper.HandlerCallWrapper","text":"
HandlerCallWrapper(\n    call: Callable[P_HandlerParams, T_HandlerReturn]\n)\n

Bases: Generic[MsgType, P_HandlerParams, T_HandlerReturn]

A generic class to wrap handler calls.

METHOD DESCRIPTION __new__

Create a new instance of the class

__init__

Initialize the instance

__call__

Call the wrapped handler

set_wrapped

Set the wrapped handler call

call_wrapped

Call the wrapped handler

wait_call

Wait for the handler call to complete

Initialize a handler.

PARAMETER DESCRIPTION call

A callable object that represents the handler function.

TYPE: Callable[P_HandlerParams, T_HandlerReturn]

Source code in faststream/broker/wrapper.py
def __init__(\n    self,\n    call: Callable[P_HandlerParams, T_HandlerReturn],\n) -> None:\n    \"\"\"Initialize a handler.\n\n    Args:\n        call: A callable object that represents the handler function.\n\n    Attributes:\n        _original_call: The original handler function.\n        _wrapped_call: The wrapped handler function.\n        _publishers: A list of publishers.\n        mock: A MagicMock object.\n        __name__: The name of the handler function.\n\n    \"\"\"\n    if not isinstance(call, HandlerCallWrapper):\n        self._original_call = call\n        self._wrapped_call = None\n        self._publishers = []\n\n        self.mock = None\n        self.future = None\n        self.is_test = False\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.future","title":"future instance-attribute","text":"
future: Optional[asyncio.Future[Any]]\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.is_test","title":"is_test instance-attribute","text":"
is_test: bool\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.mock","title":"mock instance-attribute","text":"
mock: Optional[MagicMock]\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.call_wrapped","title":"call_wrapped","text":"
call_wrapped(\n    message: StreamMessage[MsgType],\n) -> Union[\n    Optional[WrappedReturn[T_HandlerReturn]],\n    Awaitable[Optional[WrappedReturn[T_HandlerReturn]]],\n]\n

Calls the wrapped function with the given message.

PARAMETER DESCRIPTION message

The message to be passed to the wrapped function.

TYPE: StreamMessage[MsgType]

RETURNS DESCRIPTION Union[Optional[WrappedReturn[T_HandlerReturn]], Awaitable[Optional[WrappedReturn[T_HandlerReturn]]]]

The result of the wrapped function call.

RAISES DESCRIPTION AssertionError

If set_wrapped has not been called before calling this function.

AssertionError

If the broker has not been started before calling this function.

Source code in faststream/broker/wrapper.py
def call_wrapped(\n    self,\n    message: StreamMessage[MsgType],\n) -> Union[\n    Optional[WrappedReturn[T_HandlerReturn]],\n    Awaitable[Optional[WrappedReturn[T_HandlerReturn]]],\n]:\n    \"\"\"Calls the wrapped function with the given message.\n\n    Args:\n        message: The message to be passed to the wrapped function.\n\n    Returns:\n        The result of the wrapped function call.\n\n    Raises:\n        AssertionError: If `set_wrapped` has not been called before calling this function.\n        AssertionError: If the broker has not been started before calling this function.\n\n    \"\"\"\n    assert self._wrapped_call, \"You should use `set_wrapped` first\"  # nosec B101\n    if self.is_test:\n        assert self.mock  # nosec B101\n        self.mock(message.decoded_body)\n    return self._wrapped_call(message)\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.refresh","title":"refresh","text":"
refresh(with_mock: bool = False) -> None\n
Source code in faststream/broker/wrapper.py
def refresh(self, with_mock: bool = False) -> None:\n    self.future = asyncio.Future()\n    if with_mock and self.mock is not None:\n        self.mock.reset_mock()\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/wrapper.py
def reset_test(self) -> None:\n    self.is_test = False\n    self.mock = None\n    self.future = None\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.set_test","title":"set_test","text":"
set_test() -> None\n
Source code in faststream/broker/wrapper.py
def set_test(self) -> None:\n    self.is_test = True\n    if self.mock is None:\n        self.mock = MagicMock()\n    self.refresh(with_mock=True)\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.set_wrapped","title":"set_wrapped","text":"
set_wrapped(\n    wrapped: WrappedHandlerCall[MsgType, T_HandlerReturn]\n) -> None\n

Set the wrapped handler call.

PARAMETER DESCRIPTION wrapped

The wrapped handler call to set

TYPE: WrappedHandlerCall[MsgType, T_HandlerReturn]

Source code in faststream/broker/wrapper.py
def set_wrapped(\n    self, wrapped: WrappedHandlerCall[MsgType, T_HandlerReturn]\n) -> None:\n    \"\"\"Set the wrapped handler call.\n\n    Args:\n        wrapped: The wrapped handler call to set\n\n    \"\"\"\n    self._wrapped_call = wrapped\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.trigger","title":"trigger","text":"
trigger(\n    result: Any = None,\n    error: Optional[BaseException] = None,\n) -> None\n
Source code in faststream/broker/wrapper.py
def trigger(\n    self,\n    result: Any = None,\n    error: Optional[BaseException] = None,\n) -> None:\n    if not self.is_test:\n        return\n\n    assert (  # nosec B101\n        self.future is not None\n    ), \"You can use this method only with TestClient\"\n\n    if self.future.done():\n        self.future = asyncio.Future()\n\n    if error:\n        self.future.set_exception(error)\n    else:\n        self.future.set_result(result)\n
","boost":0.5},{"location":"api/faststream/broker/wrapper/HandlerCallWrapper/#faststream.broker.wrapper.HandlerCallWrapper.wait_call","title":"wait_call async","text":"
wait_call(timeout: Optional[float] = None) -> None\n

Waits for a call with an optional timeout.

PARAMETER DESCRIPTION timeout

Optional timeout in seconds

TYPE: Optional[float] DEFAULT: None

RAISES DESCRIPTION AssertionError

If the broker is not started

RETURNS DESCRIPTION None

None

Source code in faststream/broker/wrapper.py
async def wait_call(self, timeout: Optional[float] = None) -> None:\n    \"\"\"Waits for a call with an optional timeout.\n\n    Args:\n        timeout: Optional timeout in seconds\n\n    Raises:\n        AssertionError: If the broker is not started\n\n    Returns:\n        None\n\n    \"\"\"\n    assert (  # nosec B101\n        self.future is not None\n    ), \"You can use this method only with TestClient\"\n    with anyio.fail_after(timeout):\n        await self.future\n
","boost":0.5},{"location":"api/faststream/cli/docs/app/gen/","title":"gen","text":"","boost":0.5},{"location":"api/faststream/cli/docs/app/gen/#faststream.cli.docs.app.gen","title":"faststream.cli.docs.app.gen","text":"
gen(\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] - path to your application\",\n    ),\n    yaml: bool = typer.Option(\n        False,\n        \"--yaml\",\n        is_flag=True,\n        help=\"generate `asyncapi.yaml` schema\",\n    ),\n    out: Optional[str] = typer.Option(\n        None, help=\"output filename\"\n    ),\n) -> None\n

Generate project AsyncAPI schema

Source code in faststream/cli/docs/app.py
@docs_app.command(name=\"gen\")\ndef gen(\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] - path to your application\",\n    ),\n    yaml: bool = typer.Option(\n        False,\n        \"--yaml\",\n        is_flag=True,\n        help=\"generate `asyncapi.yaml` schema\",\n    ),\n    out: Optional[str] = typer.Option(\n        None,\n        help=\"output filename\",\n    ),\n) -> None:\n    \"\"\"Generate project AsyncAPI schema\"\"\"\n    _, app_obj = import_from_string(app)\n    raw_schema = get_app_schema(app_obj)\n\n    if yaml:\n        try:\n            schema = raw_schema.to_yaml()\n        except ImportError as e:  # pragma: no cover\n            typer.echo(INSTALL_YAML, err=True)\n            raise typer.Exit(1) from e\n\n        name = out or \"asyncapi.yaml\"\n\n        with open(name, \"w\") as f:\n            f.write(schema)\n\n    else:\n        schema = raw_schema.to_jsonable()\n        name = out or \"asyncapi.json\"\n\n        with open(name, \"w\") as f:\n            json.dump(schema, f, indent=2)\n\n    typer.echo(f\"Your project AsyncAPI scheme was placed to `{name}`\")\n
","boost":0.5},{"location":"api/faststream/cli/docs/app/serve/","title":"serve","text":"","boost":0.5},{"location":"api/faststream/cli/docs/app/serve/#faststream.cli.docs.app.serve","title":"faststream.cli.docs.app.serve","text":"
serve(\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] or [asyncapi.yaml/.json] - path to your application or documentation\",\n    ),\n    host: str = typer.Option(\n        \"localhost\", help=\"documentation hosting address\"\n    ),\n    port: int = typer.Option(\n        8000, help=\"documentation hosting port\"\n    ),\n    reload: bool = typer.Option(\n        False,\n        \"--reload\",\n        is_flag=True,\n        help=\"Restart documentation at directory files changes\",\n    ),\n) -> None\n

Serve project AsyncAPI schema

Source code in faststream/cli/docs/app.py
@docs_app.command(name=\"serve\")\ndef serve(\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] or [asyncapi.yaml/.json] - path to your application or documentation\",\n    ),\n    host: str = typer.Option(\n        \"localhost\",\n        help=\"documentation hosting address\",\n    ),\n    port: int = typer.Option(\n        8000,\n        help=\"documentation hosting port\",\n    ),\n    reload: bool = typer.Option(\n        False,\n        \"--reload\",\n        is_flag=True,\n        help=\"Restart documentation at directory files changes\",\n    ),\n) -> None:\n    \"\"\"Serve project AsyncAPI schema\"\"\"\n\n    if \":\" in app:\n        module, _ = import_from_string(app)\n\n        module_parent = module.parent\n        extra_extensions: Sequence[str] = ()\n\n    else:\n        module_parent = Path.cwd()\n        schema_filepath = module_parent / app\n        extra_extensions = (schema_filepath.suffix,)\n\n    if reload is True:\n        try:\n            from faststream.cli.supervisors.watchfiles import WatchReloader\n\n        except ImportError:\n            warnings.warn(INSTALL_WATCHFILES, category=ImportWarning, stacklevel=1)\n            _parse_and_serve(app, host, port)\n\n        else:\n            WatchReloader(\n                target=_parse_and_serve,\n                args=(app, host, port),\n                reload_dirs=(str(module_parent),),\n                extra_extensions=extra_extensions,\n            ).run()\n\n    else:\n        _parse_and_serve(app, host, port)\n
","boost":0.5},{"location":"api/faststream/cli/main/main/","title":"main","text":"","boost":0.5},{"location":"api/faststream/cli/main/main/#faststream.cli.main.main","title":"faststream.cli.main.main","text":"
main(\n    version: Optional[bool] = typer.Option(\n        False,\n        \"-v\",\n        \"--version\",\n        callback=version_callback,\n        is_eager=True,\n        help=\"Show current platform, python and FastStream version\",\n    )\n) -> None\n

Generate, run and manage FastStream apps to greater development experience

Source code in faststream/cli/main.py
@cli.callback()\ndef main(\n    version: Optional[bool] = typer.Option(\n        False,\n        \"-v\",\n        \"--version\",\n        callback=version_callback,\n        is_eager=True,\n        help=\"Show current platform, python and FastStream version\",\n    ),\n) -> None:\n    \"\"\"\n    Generate, run and manage FastStream apps to greater development experience\n    \"\"\"\n
","boost":0.5},{"location":"api/faststream/cli/main/run/","title":"run","text":"","boost":0.5},{"location":"api/faststream/cli/main/run/#faststream.cli.main.run","title":"faststream.cli.main.run","text":"
run(\n    ctx: typer.Context,\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] - path to your application\",\n    ),\n    workers: int = typer.Option(\n        1,\n        show_default=False,\n        help=\"Run [workers] applications with process spawning\",\n    ),\n    log_level: LogLevels = typer.Option(\n        LogLevels.info,\n        case_sensitive=False,\n        show_default=False,\n        help=\"[INFO] default\",\n    ),\n    reload: bool = typer.Option(\n        False,\n        \"--reload\",\n        is_flag=True,\n        help=\"Restart app at directory files changes\",\n    ),\n    watch_extensions: List[str] = typer.Option(\n        (),\n        \"--extension\",\n        \"--reload-extension\",\n        \"--reload-ext\",\n        \"--ext\",\n        help=\"List of file extensions to watch by\",\n    ),\n    app_dir: str = typer.Option(\n        \".\",\n        \"--app-dir\",\n        help=\"Look for APP in the specified directory, by adding this to the PYTHONPATH. Defaults to the current working directory.\",\n    ),\n) -> None\n

Run [MODULE:APP] FastStream application

Source code in faststream/cli/main.py
@cli.command(\n    context_settings={\"allow_extra_args\": True, \"ignore_unknown_options\": True}\n)\ndef run(\n    ctx: typer.Context,\n    app: str = typer.Argument(\n        ...,\n        help=\"[python_module:FastStream] - path to your application\",\n    ),\n    workers: int = typer.Option(\n        1,\n        show_default=False,\n        help=\"Run [workers] applications with process spawning\",\n    ),\n    log_level: LogLevels = typer.Option(\n        LogLevels.info,\n        case_sensitive=False,\n        show_default=False,\n        help=\"[INFO] default\",\n    ),\n    reload: bool = typer.Option(\n        False,\n        \"--reload\",\n        is_flag=True,\n        help=\"Restart app at directory files changes\",\n    ),\n    watch_extensions: List[str] = typer.Option(\n        (),\n        \"--extension\",\n        \"--reload-extension\",\n        \"--reload-ext\",\n        \"--ext\",\n        help=\"List of file extensions to watch by\",\n    ),\n    app_dir: str = typer.Option(\n        \".\",\n        \"--app-dir\",\n        help=(\n            \"Look for APP in the specified directory, by adding this to the PYTHONPATH.\"\n            \" Defaults to the current working directory.\"\n        ),\n    ),\n) -> None:\n    \"\"\"Run [MODULE:APP] FastStream application\"\"\"\n    if watch_extensions and not reload:\n        typer.echo(\n            \"Extra reload extensions has no effect without `--reload` flag.\"\n            \"\\nProbably, you forgot it?\"\n        )\n\n    app, extra = parse_cli_args(app, *ctx.args)\n    casted_log_level = get_log_level(log_level)\n\n    if app_dir:  # pragma: no branch\n        sys.path.insert(0, app_dir)\n\n    args = (app, extra, casted_log_level)\n\n    if reload and workers > 1:\n        raise ValueError(\"You can't use reload option with multiprocessing\")\n\n    if reload is True:\n        try:\n            from faststream.cli.supervisors.watchfiles import WatchReloader\n        except ImportError:\n            warnings.warn(INSTALL_WATCHFILES, category=ImportWarning, stacklevel=1)\n            _run(*args)\n\n        else:\n            module_path, _ = import_from_string(app)\n\n            WatchReloader(\n                target=_run,\n                args=args,\n                reload_dirs=[str(module_path)] + ([app_dir] if app_dir else []),\n            ).run()\n\n    elif workers > 1:\n        from faststream.cli.supervisors.multiprocess import Multiprocess\n\n        Multiprocess(\n            target=_run,\n            args=(*args, logging.DEBUG),\n            workers=workers,\n        ).run()\n\n    else:\n        _run(*args)\n
","boost":0.5},{"location":"api/faststream/cli/main/version_callback/","title":"version_callback","text":"","boost":0.5},{"location":"api/faststream/cli/main/version_callback/#faststream.cli.main.version_callback","title":"faststream.cli.main.version_callback","text":"
version_callback(version: bool) -> None\n

Callback function for displaying version information.

PARAMETER DESCRIPTION version

If True, display version information

TYPE: bool

RETURNS DESCRIPTION None

None

Source code in faststream/cli/main.py
def version_callback(version: bool) -> None:\n    \"\"\"Callback function for displaying version information.\n\n    Args:\n        version: If True, display version information\n\n    Returns:\n        None\n\n    \"\"\"\n    if version is True:\n        import platform\n\n        typer.echo(\n            \"Running FastStream %s with %s %s on %s\"\n            % (\n                __version__,\n                platform.python_implementation(),\n                platform.python_version(),\n                platform.system(),\n            )\n        )\n\n        raise typer.Exit()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/","title":"BaseReload","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload","title":"faststream.cli.supervisors.basereload.BaseReload","text":"
BaseReload(\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    reload_delay: Optional[float] = 0.5,\n)\n

A base class for implementing a reloader process.

METHOD DESCRIPTION run

Runs the reloader process.

startup

Performs startup operations for the reloader process.

restart

Restarts the process.

shutdown

Shuts down the reloader process.

_stop_process

Stops the spawned process.

_start_process

Starts the spawned process.

should_restart

Determines whether the process should be restarted.

Initialize a class instance.

PARAMETER DESCRIPTION target

The target callable object

TYPE: DecoratedCallable

args

Tuple of arguments to be passed to the target callable

TYPE: Tuple[Any, ...]

reload_delay

Optional delay in seconds before reloading the target callable (default is 0.5 seconds)

TYPE: Optional[float] DEFAULT: 0.5

RETURNS DESCRIPTION None

None

Source code in faststream/cli/supervisors/basereload.py
def __init__(\n    self,\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    reload_delay: Optional[float] = 0.5,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        target: The target callable object\n        args: Tuple of arguments to be passed to the target callable\n        reload_delay: Optional delay in seconds before reloading the target callable (default is 0.5 seconds)\n\n    Returns:\n        None\n\n    \"\"\"\n    self._target = target\n    self._args = args\n\n    self.should_exit = threading.Event()\n    self.pid = os.getpid()\n    self.reload_delay = reload_delay\n\n    set_exit(lambda *_: self.should_exit.set())\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.pid","title":"pid instance-attribute","text":"
pid: int = os.getpid()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.reload_delay","title":"reload_delay instance-attribute","text":"
reload_delay: Optional[float] = reload_delay\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.reloader_name","title":"reloader_name class-attribute instance-attribute","text":"
reloader_name: str = ''\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.should_exit","title":"should_exit instance-attribute","text":"
should_exit: threading.Event = threading.Event()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.restart","title":"restart","text":"
restart() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def restart(self) -> None:\n    self._stop_process()\n    logger.info(\"Process successfully reloaded\")\n    self._process = self._start_process()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.run","title":"run","text":"
run() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def run(self) -> None:\n    self.startup()\n    while not self.should_exit.wait(self.reload_delay):\n        if self.should_restart():  # pragma: no branch\n            self.restart()\n    self.shutdown()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.should_restart","title":"should_restart","text":"
should_restart() -> bool\n
Source code in faststream/cli/supervisors/basereload.py
def should_restart(self) -> bool:\n    raise NotImplementedError(\"Reload strategies should override should_restart()\")\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.shutdown","title":"shutdown","text":"
shutdown() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def shutdown(self) -> None:\n    self._stop_process()\n    logger.info(f\"Stopping reloader process [{self.pid}]\")\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/basereload/BaseReload/#faststream.cli.supervisors.basereload.BaseReload.startup","title":"startup","text":"
startup() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def startup(self) -> None:\n    logger.info(f\"Started reloader process [{self.pid}] using {self.reloader_name}\")\n    self._process = self._start_process()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/","title":"Multiprocess","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess","title":"faststream.cli.supervisors.multiprocess.Multiprocess","text":"
Multiprocess(\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    workers: int,\n)\n

Bases: BaseReload

A class to represent a multiprocess.

METHOD DESCRIPTION startup

starts the parent process and creates worker processes

shutdown

terminates and joins all worker processes, and stops the parent process

Initialize a new instance of the class.

PARAMETER DESCRIPTION target

The target callable object to be executed.

TYPE: DecoratedCallable

args

The arguments to be passed to the target callable.

TYPE: Tuple[Any, ...]

workers

The number of workers to be used.

TYPE: int

RETURNS DESCRIPTION None

None.

Source code in faststream/cli/supervisors/multiprocess.py
def __init__(\n    self,\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    workers: int,\n) -> None:\n    \"\"\"Initialize a new instance of the class.\n\n    Args:\n        target: The target callable object to be executed.\n        args: The arguments to be passed to the target callable.\n        workers: The number of workers to be used.\n\n    Returns:\n        None.\n\n    \"\"\"\n    super().__init__(target, args, None)\n\n    self.workers = workers\n    self.processes: List[SpawnProcess] = []\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.pid","title":"pid instance-attribute","text":"
pid: int = os.getpid()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.processes","title":"processes instance-attribute","text":"
processes: List[SpawnProcess] = []\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.reload_delay","title":"reload_delay instance-attribute","text":"
reload_delay: Optional[float] = reload_delay\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.reloader_name","title":"reloader_name class-attribute instance-attribute","text":"
reloader_name: str = ''\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.should_exit","title":"should_exit instance-attribute","text":"
should_exit: threading.Event = threading.Event()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.workers","title":"workers instance-attribute","text":"
workers = workers\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.restart","title":"restart","text":"
restart() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def restart(self) -> None:\n    self._stop_process()\n    logger.info(\"Process successfully reloaded\")\n    self._process = self._start_process()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.run","title":"run","text":"
run() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def run(self) -> None:\n    self.startup()\n    while not self.should_exit.wait(self.reload_delay):\n        if self.should_restart():  # pragma: no branch\n            self.restart()\n    self.shutdown()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.should_restart","title":"should_restart","text":"
should_restart() -> bool\n
Source code in faststream/cli/supervisors/basereload.py
def should_restart(self) -> bool:\n    raise NotImplementedError(\"Reload strategies should override should_restart()\")\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.shutdown","title":"shutdown","text":"
shutdown() -> None\n
Source code in faststream/cli/supervisors/multiprocess.py
def shutdown(self) -> None:\n    for process in self.processes:\n        process.terminate()\n        logger.info(f\"Stopping child process [{process.pid}]\")\n        process.join()\n\n    logger.info(f\"Stopping parent process [{self.pid}]\")\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/multiprocess/Multiprocess/#faststream.cli.supervisors.multiprocess.Multiprocess.startup","title":"startup","text":"
startup() -> None\n
Source code in faststream/cli/supervisors/multiprocess.py
def startup(self) -> None:\n    logger.info(f\"Started parent process [{self.pid}]\")\n\n    for _ in range(self.workers):\n        process = self._start_process()\n        logger.info(f\"Started child process [{process.pid}]\")\n        self.processes.append(process)\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/get_subprocess/","title":"get_subprocess","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/get_subprocess/#faststream.cli.supervisors.utils.get_subprocess","title":"faststream.cli.supervisors.utils.get_subprocess","text":"
get_subprocess(\n    target: DecoratedCallableNone, args: Any\n) -> SpawnProcess\n

Spawn a subprocess.

PARAMETER DESCRIPTION target

The target function to be executed in the subprocess.

TYPE: DecoratedCallableNone

args

The arguments to be passed to the target function.

TYPE: Any

RETURNS DESCRIPTION SpawnProcess

The spawned subprocess.

RAISES DESCRIPTION OSError

If there is an error getting the file descriptor of sys.stdin.

Source code in faststream/cli/supervisors/utils.py
def get_subprocess(target: DecoratedCallableNone, args: Any) -> SpawnProcess:\n    \"\"\"Spawn a subprocess.\n\n    Args:\n        target: The target function to be executed in the subprocess.\n        args: The arguments to be passed to the target function.\n\n    Returns:\n        The spawned subprocess.\n\n    Raises:\n        OSError: If there is an error getting the file descriptor of sys.stdin.\n\n    \"\"\"\n    stdin_fileno: Optional[int]\n    try:\n        stdin_fileno = sys.stdin.fileno()\n    except OSError:\n        stdin_fileno = None\n\n    return spawn.Process(\n        target=subprocess_started,\n        args=args,\n        kwargs={\"t\": target, \"stdin_fileno\": stdin_fileno},\n    )\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/set_exit/","title":"set_exit","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/set_exit/#faststream.cli.supervisors.utils.set_exit","title":"faststream.cli.supervisors.utils.set_exit","text":"
set_exit(\n    func: Callable[[int, Optional[FrameType]], Any]\n) -> None\n

Set exit handler for signals.

PARAMETER DESCRIPTION func

A callable object that takes an integer and an optional frame type as arguments and returns any value.

TYPE: Callable[[int, Optional[FrameType]], Any]

RETURNS DESCRIPTION None

None

Source code in faststream/cli/supervisors/utils.py
def set_exit(func: Callable[[int, Optional[FrameType]], Any]) -> None:\n    \"\"\"Set exit handler for signals.\n\n    Args:\n        func: A callable object that takes an integer and an optional frame type as arguments and returns any value.\n\n    Returns:\n        None\n\n    \"\"\"\n    for sig in HANDLED_SIGNALS:\n        signal.signal(sig, func)\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/subprocess_started/","title":"subprocess_started","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/utils/subprocess_started/#faststream.cli.supervisors.utils.subprocess_started","title":"faststream.cli.supervisors.utils.subprocess_started","text":"
subprocess_started(\n    *args: Any,\n    t: DecoratedCallableNone,\n    stdin_fileno: Optional[int]\n) -> None\n

Start a subprocess.

PARAMETER DESCRIPTION *args

Arguments to be passed to the subprocess.

TYPE: Any DEFAULT: ()

t

The decorated callable function.

TYPE: DecoratedCallableNone

stdin_fileno

File descriptor for the standard input of the subprocess.

TYPE: Optional[int]

RETURNS DESCRIPTION None

None

Source code in faststream/cli/supervisors/utils.py
def subprocess_started(\n    *args: Any,\n    t: DecoratedCallableNone,\n    stdin_fileno: Optional[int],\n) -> None:\n    \"\"\"Start a subprocess.\n\n    Args:\n        *args: Arguments to be passed to the subprocess.\n        t: The decorated callable function.\n        stdin_fileno: File descriptor for the standard input of the subprocess.\n\n    Returns:\n        None\n\n    \"\"\"\n    if stdin_fileno is not None:  # pragma: no cover\n        sys.stdin = os.fdopen(stdin_fileno)\n    t(*args)\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/ExtendedFilter/","title":"ExtendedFilter","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/ExtendedFilter/#faststream.cli.supervisors.watchfiles.ExtendedFilter","title":"faststream.cli.supervisors.watchfiles.ExtendedFilter","text":"
ExtendedFilter(\n    *,\n    ignore_paths: Optional[\n        Sequence[Union[str, Path]]\n    ] = None,\n    extra_extensions: Sequence[str] = ()\n)\n

Bases: PythonFilter

A class that extends the watchfiles.PythonFilter class.

METHOD DESCRIPTION __init__

Initializes the ExtendedFilter object Args: ignore_paths : Optional sequence of paths to ignore extra_extensions : Sequence of extra extensions to include

Returns: None

Initialize the class.

PARAMETER DESCRIPTION ignore_paths

Optional sequence of paths to ignore.

TYPE: Optional[Sequence[Union[str, Path]]] DEFAULT: None

extra_extensions

Sequence of extra extensions.

TYPE: Sequence[str] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/cli/supervisors/watchfiles.py
def __init__(\n    self,\n    *,\n    ignore_paths: Optional[Sequence[Union[str, Path]]] = None,\n    extra_extensions: Sequence[str] = (),\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        ignore_paths: Optional sequence of paths to ignore.\n        extra_extensions: Sequence of extra extensions.\n\n    Returns:\n        None\n\n    \"\"\"\n    super().__init__(ignore_paths=ignore_paths, extra_extensions=extra_extensions)\n    self.ignore_dirs = self.ignore_dirs + (\n        \"venv\",\n        \"env\",\n        \".github\",\n        \".mypy_cache\",\n        \".pytest_cache\",\n        \".ruff_cache\",\n        \"__pycache__\",\n    )\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/ExtendedFilter/#faststream.cli.supervisors.watchfiles.ExtendedFilter.ignore_dirs","title":"ignore_dirs instance-attribute","text":"
ignore_dirs: Tuple[str, ...] = self.ignore_dirs + (\n    \"venv\",\n    \"env\",\n    \".github\",\n    \".mypy_cache\",\n    \".pytest_cache\",\n    \".ruff_cache\",\n    \"__pycache__\",\n)\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/","title":"WatchReloader","text":"","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader","title":"faststream.cli.supervisors.watchfiles.WatchReloader","text":"
WatchReloader(\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    reload_dirs: Sequence[Union[Path, str]],\n    reload_delay: float = 0.3,\n    extra_extensions: Sequence[str] = (),\n)\n

Bases: BaseReload

A class to reload a target function when files in specified directories change.

METHOD DESCRIPTION should_restart

Checks if any files in the watched directories have changed and returns True if a change is detected, False otherwise.

Initialize a WatchFilesReloader object.

PARAMETER DESCRIPTION target

The target callable to be executed.

TYPE: DecoratedCallable

args

The arguments to be passed to the target callable.

TYPE: Tuple[Any, ...]

reload_dirs

A sequence of directories to watch for changes.

TYPE: Sequence[Union[Path, str]]

reload_delay

The delay in seconds between checking for changes. Default is 0.3.

TYPE: float DEFAULT: 0.3

RETURNS DESCRIPTION None

None.

Source code in faststream/cli/supervisors/watchfiles.py
def __init__(\n    self,\n    target: DecoratedCallable,\n    args: Tuple[Any, ...],\n    reload_dirs: Sequence[Union[Path, str]],\n    reload_delay: float = 0.3,\n    extra_extensions: Sequence[str] = (),\n) -> None:\n    \"\"\"Initialize a WatchFilesReloader object.\n\n    Args:\n        target: The target callable to be executed.\n        args: The arguments to be passed to the target callable.\n        reload_dirs: A sequence of directories to watch for changes.\n        reload_delay: The delay in seconds between checking for changes. Default is 0.3.\n\n    Returns:\n        None.\n\n    \"\"\"\n    super().__init__(target, args, reload_delay)\n    self.reloader_name = \"WatchFiles\"\n    self.reload_dirs = reload_dirs\n    self.watcher = watchfiles.watch(\n        *reload_dirs,\n        step=int(reload_delay * 1000),\n        watch_filter=ExtendedFilter(extra_extensions=extra_extensions),\n        stop_event=self.should_exit,\n        yield_on_timeout=True,\n    )\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.pid","title":"pid instance-attribute","text":"
pid: int = os.getpid()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.reload_delay","title":"reload_delay instance-attribute","text":"
reload_delay: Optional[float] = reload_delay\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.reload_dirs","title":"reload_dirs instance-attribute","text":"
reload_dirs = reload_dirs\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.reloader_name","title":"reloader_name instance-attribute","text":"
reloader_name = 'WatchFiles'\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.should_exit","title":"should_exit instance-attribute","text":"
should_exit: threading.Event = threading.Event()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.watcher","title":"watcher instance-attribute","text":"
watcher = watchfiles.watch(\n    *reload_dirs,\n    step=int(reload_delay * 1000),\n    watch_filter=ExtendedFilter(\n        extra_extensions=extra_extensions\n    ),\n    stop_event=self.should_exit,\n    yield_on_timeout=True\n)\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.restart","title":"restart","text":"
restart() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def restart(self) -> None:\n    self._stop_process()\n    logger.info(\"Process successfully reloaded\")\n    self._process = self._start_process()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.run","title":"run","text":"
run() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def run(self) -> None:\n    self.startup()\n    while not self.should_exit.wait(self.reload_delay):\n        if self.should_restart():  # pragma: no branch\n            self.restart()\n    self.shutdown()\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.should_restart","title":"should_restart","text":"
should_restart() -> bool\n
Source code in faststream/cli/supervisors/watchfiles.py
def should_restart(self) -> bool:\n    for changes in self.watcher:  # pragma: no branch\n        if changes:  # pragma: no branch\n            unique_paths = {Path(c[1]).name for c in changes}\n            message = \"WatchReloader detected file change in '%s'. Reloading...\"\n            logger.info(message % tuple(unique_paths))\n            return True\n    return False  # pragma: no cover\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.shutdown","title":"shutdown","text":"
shutdown() -> None\n
Source code in faststream/cli/supervisors/basereload.py
def shutdown(self) -> None:\n    self._stop_process()\n    logger.info(f\"Stopping reloader process [{self.pid}]\")\n
","boost":0.5},{"location":"api/faststream/cli/supervisors/watchfiles/WatchReloader/#faststream.cli.supervisors.watchfiles.WatchReloader.startup","title":"startup","text":"
startup() -> None\n
Source code in faststream/cli/supervisors/watchfiles.py
def startup(self) -> None:\n    logger.info(f\"Will watch for changes in these directories: {self.reload_dirs}\")\n    super().startup()\n
","boost":0.5},{"location":"api/faststream/cli/utils/imports/get_app_path/","title":"get_app_path","text":"","boost":0.5},{"location":"api/faststream/cli/utils/imports/get_app_path/#faststream.cli.utils.imports.get_app_path","title":"faststream.cli.utils.imports.get_app_path","text":"
get_app_path(app: str) -> Tuple[Path, str]\n

Get the application path.

PARAMETER DESCRIPTION app

The name of the application in the format \"module:app_name\".

TYPE: str

RETURNS DESCRIPTION Tuple[Path, str]

Tuple[Path, str]: A tuple containing the path to the module and the name of the application.

RAISES DESCRIPTION ValueError

If the given app is not in the format \"module:app_name\".

Source code in faststream/cli/utils/imports.py
def get_app_path(app: str) -> Tuple[Path, str]:\n    \"\"\"Get the application path.\n\n    Args:\n        app (str): The name of the application in the format \"module:app_name\".\n\n    Returns:\n        Tuple[Path, str]: A tuple containing the path to the module and the name of the application.\n\n    Raises:\n        ValueError: If the given app is not in the format \"module:app_name\".\n\n    \"\"\"\n    if \":\" not in app:\n        raise ValueError(f\"{app} is not a FastStream\")\n\n    module, app_name = app.split(\":\", 2)\n\n    mod_path = Path.cwd()\n    for i in module.split(\".\"):\n        mod_path = mod_path / i\n\n    return mod_path, app_name\n
","boost":0.5},{"location":"api/faststream/cli/utils/imports/import_from_string/","title":"import_from_string","text":"","boost":0.5},{"location":"api/faststream/cli/utils/imports/import_from_string/#faststream.cli.utils.imports.import_from_string","title":"faststream.cli.utils.imports.import_from_string","text":"
import_from_string(\n    import_str: str,\n) -> Tuple[Path, FastStream]\n

Import FastStream application from module specified by a string.

PARAMETER DESCRIPTION import_str

A string in the format \":\" specifying the module and faststream application to import.

TYPE: str

RETURNS DESCRIPTION Tuple[Path, FastStream]

Tuple[ModuleType, FastStream]: A tuple containing the imported module and the faststream application.

RAISES DESCRIPTION BadParameter

Raised if the given value is not of type string, if the import string is not in the format \":\", if the module is not found, or if the faststream appliation is not found in the module. Source code in faststream/cli/utils/imports.py

def import_from_string(import_str: str) -> Tuple[Path, FastStream]:\n    \"\"\"\n    Import FastStream application from module specified by a string.\n\n    Parameters:\n        import_str (str): A string in the format \"<module>:<attribute>\" specifying the module and faststream application to import.\n\n    Returns:\n        Tuple[ModuleType, FastStream]: A tuple containing the imported module and the faststream application.\n\n    Raises:\n        typer.BadParameter: Raised if the given value is not of type string, if the import string is not in the format\n            \"<module>:<attribute>\", if the module is not found, or if the faststream appliation is not found in the module.\n    \"\"\"\n    if not isinstance(import_str, str):\n        raise typer.BadParameter(\"Given value is not of type string\")\n\n    module_str, _, attrs_str = import_str.partition(\":\")\n    if not module_str or not attrs_str:\n        raise typer.BadParameter(\n            f'Import string \"{import_str}\" must be in format \"<module>:<attribute>\"'\n        )\n\n    try:\n        module = importlib.import_module(  # nosemgrep: python.lang.security.audit.non-literal-import.non-literal-import\n            module_str\n        )\n\n    except ModuleNotFoundError:\n        module_path, app_name = get_app_path(import_str)\n        instance = try_import_app(module_path, app_name)\n\n    else:\n        attr = module\n        try:\n            for attr_str in attrs_str.split(\".\"):\n                attr = getattr(attr, attr_str)\n            instance = attr  # type: ignore[assignment]\n\n        except AttributeError as e:\n            typer.echo(e, err=True)\n            raise typer.BadParameter(\n                f'Attribute \"{attrs_str}\" not found in module \"{module_str}\".'\n            ) from e\n\n        if module.__file__:\n            module_path = Path(module.__file__).resolve().parent\n        else:\n            module_path = Path.cwd()\n\n    return module_path, instance\n
","boost":0.5},{"location":"api/faststream/cli/utils/imports/import_object/","title":"import_object","text":"","boost":0.5},{"location":"api/faststream/cli/utils/imports/import_object/#faststream.cli.utils.imports.import_object","title":"faststream.cli.utils.imports.import_object","text":"
import_object(module: Path, app: str) -> object\n

Import an object from a module.

PARAMETER DESCRIPTION module

The path to the module file.

TYPE: Path

app

The name of the object to import.

TYPE: str

RETURNS DESCRIPTION object

The imported object.

RAISES DESCRIPTION FileNotFoundError

If the module file is not found.

ValueError

If the module has no loader.

AttributeError

If the object is not found in the module.

Source code in faststream/cli/utils/imports.py
def import_object(module: Path, app: str) -> object:\n    \"\"\"Import an object from a module.\n\n    Args:\n        module: The path to the module file.\n        app: The name of the object to import.\n\n    Returns:\n        The imported object.\n\n    Raises:\n        FileNotFoundError: If the module file is not found.\n        ValueError: If the module has no loader.\n        AttributeError: If the object is not found in the module.\n\n    \"\"\"\n    spec = spec_from_file_location(\n        \"mode\",\n        f\"{module}.py\",\n        submodule_search_locations=[str(module.parent.absolute())],\n    )\n\n    if spec is None:  # pragma: no cover\n        raise FileNotFoundError(module)\n\n    mod = module_from_spec(spec)\n    loader = spec.loader\n\n    if loader is None:  # pragma: no cover\n        raise ValueError(f\"{spec} has no loader\")\n\n    loader.exec_module(mod)\n\n    try:\n        obj = getattr(mod, app)\n    except AttributeError as e:\n        raise FileNotFoundError(module) from e\n\n    return obj\n
","boost":0.5},{"location":"api/faststream/cli/utils/imports/try_import_app/","title":"try_import_app","text":"","boost":0.5},{"location":"api/faststream/cli/utils/imports/try_import_app/#faststream.cli.utils.imports.try_import_app","title":"faststream.cli.utils.imports.try_import_app","text":"
try_import_app(module: Path, app: str) -> FastStream\n

Tries to import a FastStream app from a module.

PARAMETER DESCRIPTION module

Path to the module containing the app.

TYPE: Path

app

Name of the FastStream app.

TYPE: str

RETURNS DESCRIPTION FastStream

The imported FastStream app object.

RAISES DESCRIPTION FileNotFoundError

If the module file is not found.

BadParameter

If the module or app name is not provided correctly.

Source code in faststream/cli/utils/imports.py
def try_import_app(module: Path, app: str) -> FastStream:\n    \"\"\"Tries to import a FastStream app from a module.\n\n    Args:\n        module: Path to the module containing the app.\n        app: Name of the FastStream app.\n\n    Returns:\n        The imported FastStream app object.\n\n    Raises:\n        FileNotFoundError: If the module file is not found.\n        typer.BadParameter: If the module or app name is not provided correctly.\n\n    \"\"\"\n    try:\n        app_object = import_object(module, app)\n\n    except FileNotFoundError as e:\n        typer.echo(e, err=True)\n        raise typer.BadParameter(\n            \"Please, input module like [python_file:faststream_app_name] or [module:attribute]\"\n        ) from e\n\n    else:\n        return app_object  # type: ignore\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/","title":"LogLevels","text":"","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels","title":"faststream.cli.utils.logs.LogLevels","text":"

Bases: str, Enum

A class to represent log levels.

","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels.critical","title":"critical class-attribute instance-attribute","text":"
critical = 'critical'\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels.debug","title":"debug class-attribute instance-attribute","text":"
debug = 'debug'\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels.error","title":"error class-attribute instance-attribute","text":"
error = 'error'\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels.info","title":"info class-attribute instance-attribute","text":"
info = 'info'\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/LogLevels/#faststream.cli.utils.logs.LogLevels.warning","title":"warning class-attribute instance-attribute","text":"
warning = 'warning'\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/get_log_level/","title":"get_log_level","text":"","boost":0.5},{"location":"api/faststream/cli/utils/logs/get_log_level/#faststream.cli.utils.logs.get_log_level","title":"faststream.cli.utils.logs.get_log_level","text":"
get_log_level(level: Union[LogLevels, str, int]) -> int\n

Get the log level.

PARAMETER DESCRIPTION level

The log level to get. Can be an integer, a LogLevels enum value, or a string.

TYPE: Union[LogLevels, str, int]

RETURNS DESCRIPTION int

The log level as an integer.

Source code in faststream/cli/utils/logs.py
def get_log_level(level: Union[LogLevels, str, int]) -> int:\n    \"\"\"Get the log level.\n\n    Args:\n        level: The log level to get. Can be an integer, a LogLevels enum value, or a string.\n\n    Returns:\n        The log level as an integer.\n\n    \"\"\"\n    if isinstance(level, int):\n        return level\n\n    if isinstance(level, LogLevels):\n        return LOG_LEVELS[level.value]\n\n    if isinstance(level, str):  # pragma: no branch\n        return LOG_LEVELS[level.lower()]\n
","boost":0.5},{"location":"api/faststream/cli/utils/logs/set_log_level/","title":"set_log_level","text":"","boost":0.5},{"location":"api/faststream/cli/utils/logs/set_log_level/#faststream.cli.utils.logs.set_log_level","title":"faststream.cli.utils.logs.set_log_level","text":"
set_log_level(level: int, app: FastStream) -> None\n

Sets the log level for an application.

PARAMETER DESCRIPTION level

The log level to set.

TYPE: int

app

The application object.

TYPE: FastStream

RETURNS DESCRIPTION None

None

Source code in faststream/cli/utils/logs.py
def set_log_level(level: int, app: FastStream) -> None:\n    \"\"\"Sets the log level for an application.\n\n    Args:\n        level (int): The log level to set.\n        app (FastStream): The application object.\n\n    Returns:\n        None\n\n    \"\"\"\n    if app.logger and isinstance(app.logger, logging.Logger):\n        app.logger.setLevel(level)\n\n    broker_logger: Optional[logging.Logger] = getattr(app.broker, \"logger\", None)\n    if broker_logger is not None and isinstance(broker_logger, logging.Logger):\n        broker_logger.setLevel(level)\n
","boost":0.5},{"location":"api/faststream/cli/utils/parser/parse_cli_args/","title":"parse_cli_args","text":"","boost":0.5},{"location":"api/faststream/cli/utils/parser/parse_cli_args/#faststream.cli.utils.parser.parse_cli_args","title":"faststream.cli.utils.parser.parse_cli_args","text":"
parse_cli_args(\n    *args: str,\n) -> Tuple[str, Dict[str, SettingField]]\n

Parses command line arguments.

PARAMETER DESCRIPTION *args

Command line arguments as strings.

TYPE: str DEFAULT: ()

RETURNS DESCRIPTION Tuple[str, Dict[str, SettingField]]

A tuple containing the application name and a dictionary of additional keyword arguments.

Source code in faststream/cli/utils/parser.py
def parse_cli_args(*args: str) -> Tuple[str, Dict[str, SettingField]]:\n    \"\"\"Parses command line arguments.\n\n    Args:\n        *args: Command line arguments as strings.\n\n    Returns:\n        A tuple containing the application name and a dictionary of additional keyword arguments.\n    \"\"\"\n    extra_kwargs: Dict[str, SettingField] = {}\n\n    k: str = \"\"\n    v: SettingField\n\n    field_args: List[str] = []\n    app = \"\"\n    for item in reduce(\n        lambda acc, x: acc + x.split(\"=\"),  # type: ignore\n        args,\n        [],\n    ) + [\"-\"]:\n        if \":\" in item:\n            app = item\n\n        else:\n            if \"-\" in item:\n                if k:\n                    k = k.strip().lstrip(\"-\").replace(\"-\", \"_\")\n\n                    if len(field_args) == 0:\n                        v = not k.startswith(\"no_\")\n                    elif len(field_args) == 1:\n                        v = field_args[0]\n                    else:\n                        v = field_args\n\n                    key = remove_prefix(k, \"no_\")\n                    if (exists := extra_kwargs.get(key)) is not None:\n                        if not isinstance(exists, list):\n                            v = [exists, v]\n                        else:\n                            v = exists + [v]\n\n                    extra_kwargs[key] = v\n                    field_args = []\n\n                k = item\n\n            else:\n                field_args.append(item)\n\n    return app, extra_kwargs\n
","boost":0.5},{"location":"api/faststream/cli/utils/parser/remove_prefix/","title":"remove_prefix","text":"","boost":0.5},{"location":"api/faststream/cli/utils/parser/remove_prefix/#faststream.cli.utils.parser.remove_prefix","title":"faststream.cli.utils.parser.remove_prefix","text":"
remove_prefix(text: str, prefix: str) -> str\n

Removes a prefix from a given text.

Python 3.8 compatibility function

PARAMETER DESCRIPTION text

The text from which the prefix will be removed.

TYPE: str

prefix

The prefix to be removed from the text.

TYPE: str

RETURNS DESCRIPTION str

The text with the prefix removed. If the text does not start with the prefix, the original text is returned.

TYPE: str

Source code in faststream/cli/utils/parser.py
def remove_prefix(text: str, prefix: str) -> str:\n    \"\"\"Removes a prefix from a given text.\n\n    Python 3.8 compatibility function\n\n    Args:\n        text (str): The text from which the prefix will be removed.\n        prefix (str): The prefix to be removed from the text.\n\n    Returns:\n        str: The text with the prefix removed. If the text does not start with the prefix, the original text is returned.\n    \"\"\"\n    if text.startswith(prefix):\n        return text[len(prefix) :]\n    return text\n
","boost":0.5},{"location":"api/faststream/constants/ContentTypes/","title":"ContentTypes","text":"","boost":0.5},{"location":"api/faststream/constants/ContentTypes/#faststream.constants.ContentTypes","title":"faststream.constants.ContentTypes","text":"

Bases: str, Enum

A class to represent content types.

","boost":0.5},{"location":"api/faststream/constants/ContentTypes/#faststream.constants.ContentTypes.json","title":"json class-attribute instance-attribute","text":"
json = 'application/json'\n
","boost":0.5},{"location":"api/faststream/constants/ContentTypes/#faststream.constants.ContentTypes.text","title":"text class-attribute instance-attribute","text":"
text = 'text/plain'\n
","boost":0.5},{"location":"api/faststream/exceptions/AckMessage/","title":"AckMessage","text":"","boost":0.5},{"location":"api/faststream/exceptions/AckMessage/#faststream.exceptions.AckMessage","title":"faststream.exceptions.AckMessage","text":"

Bases: HandlerException

Raise it to ack a message immediately

","boost":0.5},{"location":"api/faststream/exceptions/HandlerException/","title":"HandlerException","text":"","boost":0.5},{"location":"api/faststream/exceptions/HandlerException/#faststream.exceptions.HandlerException","title":"faststream.exceptions.HandlerException","text":"

Bases: Exception

Base Handler Exception

","boost":0.5},{"location":"api/faststream/exceptions/NackMessage/","title":"NackMessage","text":"","boost":0.5},{"location":"api/faststream/exceptions/NackMessage/#faststream.exceptions.NackMessage","title":"faststream.exceptions.NackMessage","text":"

Bases: HandlerException

Raise it to nack a message immediately

","boost":0.5},{"location":"api/faststream/exceptions/RejectMessage/","title":"RejectMessage","text":"","boost":0.5},{"location":"api/faststream/exceptions/RejectMessage/#faststream.exceptions.RejectMessage","title":"faststream.exceptions.RejectMessage","text":"

Bases: HandlerException

Raise it to reject a message immediately

","boost":0.5},{"location":"api/faststream/exceptions/SkipMessage/","title":"SkipMessage","text":"","boost":0.5},{"location":"api/faststream/exceptions/SkipMessage/#faststream.exceptions.SkipMessage","title":"faststream.exceptions.SkipMessage","text":"

Bases: Exception

Watcher Instruction to skip message

","boost":0.5},{"location":"api/faststream/exceptions/StopConsume/","title":"StopConsume","text":"","boost":0.5},{"location":"api/faststream/exceptions/StopConsume/#faststream.exceptions.StopConsume","title":"faststream.exceptions.StopConsume","text":"

Bases: Exception

Raise it to stop Handler consuming

","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/","title":"KafkaBroker","text":"","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker","title":"faststream.kafka.KafkaBroker","text":"
KafkaBroker(\n    bootstrap_servers: Union[\n        str, Iterable[str]\n    ] = \"localhost\",\n    *,\n    protocol: str = None,\n    protocol_version: str = \"auto\",\n    client_id: str = \"faststream-\" + __version__,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: KafkaLoggingMixin, BrokerAsyncUsecase[ConsumerRecord, ConsumerConnectionParams]

KafkaBroker is a class for managing Kafka message consumption and publishing. It extends BrokerAsyncUsecase to handle asynchronous operations.

PARAMETER DESCRIPTION bootstrap_servers

Kafka bootstrap server(s).

TYPE: Union[str, Iterable[str]] DEFAULT: 'localhost'

protocol

The protocol used (default is \"kafka\").

TYPE: str DEFAULT: None

protocol_version

The Kafka protocol version (default is \"auto\").

TYPE: str DEFAULT: 'auto'

client_id

The client ID for the Kafka client.

TYPE: str DEFAULT: 'faststream-' + __version__

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

METHOD DESCRIPTION connect

Establishes a connection to Kafka.

start

Starts the KafkaBroker and message handlers.

publish

Publishes a message to Kafka.

Initialize a KafkaBroker instance.

PARAMETER DESCRIPTION bootstrap_servers

Kafka bootstrap server(s).

TYPE: Union[str, Iterable[str]] DEFAULT: 'localhost'

protocol

The protocol used (default is \"kafka\").

TYPE: str DEFAULT: None

protocol_version

The Kafka protocol version (default is \"auto\").

TYPE: str DEFAULT: 'auto'

client_id

The client ID for the Kafka client.

TYPE: str DEFAULT: 'faststream-' + __version__

security

Security protocol to use in communication with the broker (default is None).

TYPE: Optional[BaseSecurity] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/kafka/broker.py
def __init__(\n    self,\n    bootstrap_servers: Union[str, Iterable[str]] = \"localhost\",\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: str = \"auto\",\n    client_id: str = \"faststream-\" + __version__,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Initialize a KafkaBroker instance.\n\n    Args:\n        bootstrap_servers (Union[str, Iterable[str]]): Kafka bootstrap server(s).\n        protocol (str): The protocol used (default is \"kafka\").\n        protocol_version (str): The Kafka protocol version (default is \"auto\").\n        client_id (str): The client ID for the Kafka client.\n        security (Optional[BaseSecurity]): Security protocol to use in communication with the broker (default is None).\n        **kwargs: Additional keyword arguments.\n    \"\"\"\n    if protocol is None:\n        if security is not None and security.use_ssl:\n            protocol = \"kafka-secure\"\n        else:\n            protocol = \"kafka\"\n\n    super().__init__(\n        url=[bootstrap_servers]\n        if isinstance(bootstrap_servers, str)\n        else list(bootstrap_servers),\n        protocol=protocol,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n        client_id=client_id,\n        bootstrap_servers=bootstrap_servers,\n    )\n    self.client_id = client_id\n    self._producer = None\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.client_id","title":"client_id instance-attribute","text":"
client_id = client_id\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[str, Handler]\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.url","title":"url instance-attribute","text":"
url: List[str]\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.connect","title":"connect async","text":"
connect(\n    *args: Any, **kwargs: Any\n) -> ConsumerConnectionParams\n

Establishes a connection to Kafka and returns connection parameters.

PARAMETER DESCRIPTION *args

Additional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION ConsumerConnectionParams

The connection parameters.

TYPE: ConsumerConnectionParams

Source code in faststream/kafka/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> ConsumerConnectionParams:\n    \"\"\"\n    Establishes a connection to Kafka and returns connection parameters.\n\n    Args:\n        *args: Additional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        ConsumerConnectionParams: The connection parameters.\n    \"\"\"\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.publish","title":"publish async","text":"
publish(*args: Any, **kwargs: Any) -> None\n

Publish a message to Kafka.

PARAMETER DESCRIPTION *args

Positional arguments for message publishing.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments for message publishing.

TYPE: Any DEFAULT: {}

RAISES DESCRIPTION RuntimeError

If KafkaBroker is not started yet.

Source code in faststream/kafka/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Publish a message to Kafka.\n\n    Args:\n        *args: Positional arguments for message publishing.\n        **kwargs: Keyword arguments for message publishing.\n\n    Raises:\n        RuntimeError: If KafkaBroker is not started yet.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.publish_batch","title":"publish_batch async","text":"
publish_batch(*args: Any, **kwargs: Any) -> None\n

Publish a batch of messages to Kafka.

PARAMETER DESCRIPTION *args

Positional arguments for message publishing.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments for message publishing.

TYPE: Any DEFAULT: {}

RAISES DESCRIPTION RuntimeError

If KafkaBroker is not started yet.

Source code in faststream/kafka/broker.py
async def publish_batch(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Publish a batch of messages to Kafka.\n\n    Args:\n        *args: Positional arguments for message publishing.\n        **kwargs: Keyword arguments for message publishing.\n\n    Raises:\n        RuntimeError: If KafkaBroker is not started yet.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    await self._producer.publish_batch(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.publisher","title":"publisher","text":"
publisher(\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n

Create a message publisher for the specified topic.

PARAMETER DESCRIPTION topic

The topic to publish messages to.

TYPE: str

key

Message key.

TYPE: Optional[bytes] DEFAULT: None

partition

Partition to send the message to.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

Message timestamp in milliseconds.

TYPE: Optional[int] DEFAULT: None

headers

Message headers.

TYPE: Optional[Dict[str, str]] DEFAULT: None

reply_to

The topic to which responses should be sent.

TYPE: str DEFAULT: ''

batch

Whether to publish messages in batches.

TYPE: bool DEFAULT: False

title

AsyncAPI title.

TYPE: Optional[str] DEFAULT: None

description

AsyncAPI description.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION Publisher

A message publisher.

TYPE: Publisher

Source code in faststream/kafka/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"\n    Create a message publisher for the specified topic.\n\n    Args:\n        topic (str): The topic to publish messages to.\n        key (Optional[bytes]): Message key.\n        partition (Optional[int]): Partition to send the message to.\n        timestamp_ms (Optional[int]): Message timestamp in milliseconds.\n        headers (Optional[Dict[str, str]]): Message headers.\n        reply_to (str): The topic to which responses should be sent.\n        batch (bool): Whether to publish messages in batches.\n        title (Optional[str]): AsyncAPI title.\n        description (Optional[str]): AsyncAPI description.\n\n    Returns:\n        Publisher: A message publisher.\n    \"\"\"\n    publisher = self._publishers.get(\n        topic,\n        Publisher(\n            topic=topic,\n            client_id=self.client_id,\n            key=key,\n            batch=batch,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(topic, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.start","title":"start async","text":"
start() -> None\n

Start the KafkaBroker and message handlers.

Source code in faststream/kafka/broker.py
async def start(self) -> None:\n    \"\"\"\n    Start the KafkaBroker and message handlers.\n    \"\"\"\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n\n    for handler in self.handlers.values():\n        c = self._get_log_context(None, handler.topics, handler.group_id)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(**(self._connection or {}))\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaBroker/#faststream.kafka.KafkaBroker.subscriber","title":"subscriber","text":"
subscriber(\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    value_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\", \"earliest\", \"none\"\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[\n        AbstractPartitionAssignor\n    ] = (RoundRobinPartitionAssignor),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\", \"read_committed\"\n    ] = \"read_uncommitted\",\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        Union[\n            CustomParser[\n                aiokafka.ConsumerRecord, KafkaMessage\n            ],\n            CustomParser[\n                Tuple[aiokafka.ConsumerRecord, ...],\n                KafkaMessage,\n            ],\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[\n            StreamMessage[\n                Tuple[aiokafka.ConsumerRecord, ...]\n            ]\n        ],\n    ] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    Union[\n        HandlerCallWrapper[\n            aiokafka.ConsumerRecord,\n            P_HandlerParams,\n            T_HandlerReturn,\n        ],\n        HandlerCallWrapper[\n            Tuple[aiokafka.ConsumerRecord, ...],\n            P_HandlerParams,\n            T_HandlerReturn,\n        ],\n    ],\n]\n

Create a message subscriber for the specified topics.

PARAMETER DESCRIPTION *topics

The topics to subscribe to.

TYPE: str DEFAULT: ()

group_id

The Kafka consumer group ID.

TYPE: Optional[str] DEFAULT: None

key_deserializer

Key deserializer function.

TYPE: Optional[Callable[[bytes], Any]] DEFAULT: None

value_deserializer

Value deserializer function.

TYPE: Optional[Callable[[bytes], Any]] DEFAULT: None

fetch_max_wait_ms

The maximum time to wait for data.

TYPE: int DEFAULT: 500

fetch_max_bytes

The maximum number of bytes to fetch.

TYPE: int DEFAULT: 52428800

fetch_min_bytes

The minimum number of bytes to fetch.

TYPE: int DEFAULT: 1

max_partition_fetch_bytes

The maximum bytes to fetch for a partition.

TYPE: int DEFAULT: 1 * 1024 * 1024

auto_offset_reset

Auto offset reset policy.

TYPE: Literal['latest', 'earliest', 'none'] DEFAULT: 'latest'

auto_commit

Whether to enable auto-commit.

TYPE: bool DEFAULT: True

auto_commit_interval_ms

Auto-commit interval in milliseconds.

TYPE: int DEFAULT: 5000

check_crcs

Whether to check CRCs.

TYPE: bool DEFAULT: True

partition_assignment_strategy

Partition assignment strategy.

TYPE: Sequence[AbstractPartitionAssignor] DEFAULT: (RoundRobinPartitionAssignor)

max_poll_interval_ms

Maximum poll interval in milliseconds.

TYPE: int DEFAULT: 300000

rebalance_timeout_ms

Rebalance timeout in milliseconds.

TYPE: Optional[int] DEFAULT: None

session_timeout_ms

Session timeout in milliseconds.

TYPE: int DEFAULT: 10000

heartbeat_interval_ms

Heartbeat interval in milliseconds.

TYPE: int DEFAULT: 3000

consumer_timeout_ms

Consumer timeout in milliseconds.

TYPE: int DEFAULT: 200

max_poll_records

Maximum number of records to poll.

TYPE: Optional[int] DEFAULT: None

exclude_internal_topics

Whether to exclude internal topics.

TYPE: bool DEFAULT: True

isolation_level

Isolation level.

TYPE: Literal['read_uncommitted', 'read_committed'] DEFAULT: 'read_uncommitted'

dependencies

Additional dependencies for message handling.

TYPE: Sequence[Depends] DEFAULT: ()

parser

Message parser.

TYPE: Optional[Union[CustomParser[ConsumerRecord], CustomParser[Tuple[ConsumerRecord, ...]]]] DEFAULT: None

decoder

Message decoder.

TYPE: Optional[CustomDecoder] DEFAULT: None

middlewares

Message middlewares.

TYPE: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]] DEFAULT: None

filter

Message filter.

TYPE: Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[ConsumerRecord, ...]]]] DEFAULT: default_filter

batch

Whether to process messages in batches.

TYPE: bool DEFAULT: False

max_records

Maximum number of records to process in each batch.

TYPE: Optional[int] DEFAULT: None

batch_timeout_ms

Batch timeout in milliseconds.

TYPE: int DEFAULT: 200

no_ack

Whether not to ack/nack/reject messages.

TYPE: bool DEFAULT: False

title

AsyncAPI title.

TYPE: Optional[str] DEFAULT: None

description

AsyncAPI description.

TYPE: Optional[str] DEFAULT: None

**original_kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Callable

A decorator that wraps a message handler function.

TYPE: Callable[[Callable[P_HandlerParams, T_HandlerReturn]], Union[HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[Tuple[ConsumerRecord, ...], P_HandlerParams, T_HandlerReturn]]]

Source code in faststream/kafka/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[Callable[[bytes], Any]] = None,\n    value_deserializer: Optional[Callable[[bytes], Any]] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\",\n        \"earliest\",\n        \"none\",\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[AbstractPartitionAssignor] = (\n        RoundRobinPartitionAssignor,\n    ),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\",\n        \"read_committed\",\n    ] = \"read_uncommitted\",\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        Union[\n            CustomParser[aiokafka.ConsumerRecord, KafkaMessage],\n            CustomParser[Tuple[aiokafka.ConsumerRecord, ...], KafkaMessage],\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord],\n                BaseMiddleware,\n            ]\n        ]\n    ] = None,\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[aiokafka.ConsumerRecord, ...]]],\n    ] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    Union[\n        HandlerCallWrapper[\n            aiokafka.ConsumerRecord, P_HandlerParams, T_HandlerReturn\n        ],\n        HandlerCallWrapper[\n            Tuple[aiokafka.ConsumerRecord, ...], P_HandlerParams, T_HandlerReturn\n        ],\n    ],\n]:\n    \"\"\"\n    Create a message subscriber for the specified topics.\n\n    Args:\n        *topics (str): The topics to subscribe to.\n        group_id (Optional[str]): The Kafka consumer group ID.\n        key_deserializer (Optional[Callable[[bytes], Any]]): Key deserializer function.\n        value_deserializer (Optional[Callable[[bytes], Any]]): Value deserializer function.\n        fetch_max_wait_ms (int): The maximum time to wait for data.\n        fetch_max_bytes (int): The maximum number of bytes to fetch.\n        fetch_min_bytes (int): The minimum number of bytes to fetch.\n        max_partition_fetch_bytes (int): The maximum bytes to fetch for a partition.\n        auto_offset_reset (Literal[\"latest\", \"earliest\", \"none\"]): Auto offset reset policy.\n        auto_commit (bool): Whether to enable auto-commit.\n        auto_commit_interval_ms (int): Auto-commit interval in milliseconds.\n        check_crcs (bool): Whether to check CRCs.\n        partition_assignment_strategy (Sequence[AbstractPartitionAssignor]): Partition assignment strategy.\n        max_poll_interval_ms (int): Maximum poll interval in milliseconds.\n        rebalance_timeout_ms (Optional[int]): Rebalance timeout in milliseconds.\n        session_timeout_ms (int): Session timeout in milliseconds.\n        heartbeat_interval_ms (int): Heartbeat interval in milliseconds.\n        consumer_timeout_ms (int): Consumer timeout in milliseconds.\n        max_poll_records (Optional[int]): Maximum number of records to poll.\n        exclude_internal_topics (bool): Whether to exclude internal topics.\n        isolation_level (Literal[\"read_uncommitted\", \"read_committed\"]): Isolation level.\n        dependencies (Sequence[Depends]): Additional dependencies for message handling.\n        parser (Optional[Union[CustomParser[aiokafka.ConsumerRecord], CustomParser[Tuple[aiokafka.ConsumerRecord, ...]]]]): Message parser.\n        decoder (Optional[CustomDecoder]): Message decoder.\n        middlewares (Optional[Sequence[Callable[[aiokafka.ConsumerRecord], BaseMiddleware]]]): Message middlewares.\n        filter (Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[aiokafka.ConsumerRecord, ...]]]]): Message filter.\n        batch (bool): Whether to process messages in batches.\n        max_records (Optional[int]): Maximum number of records to process in each batch.\n        batch_timeout_ms (int): Batch timeout in milliseconds.\n        no_ack (bool): Whether not to ack/nack/reject messages.\n        title (Optional[str]): AsyncAPI title.\n        description (Optional[str]): AsyncAPI description.\n        **original_kwargs: Additional keyword arguments.\n\n    Returns:\n        Callable: A decorator that wraps a message handler function.\n    \"\"\"\n    super().subscriber()\n\n    self._setup_log_context(topics, group_id)\n\n    if not auto_commit and not group_id:\n        raise ValueError(\"You should install `group_id` with manual commit mode\")\n\n    key = Handler.get_routing_hash(topics, group_id)\n    builder = partial(\n        aiokafka.AIOKafkaConsumer,\n        key_deserializer=key_deserializer,\n        value_deserializer=value_deserializer,\n        fetch_max_wait_ms=fetch_max_wait_ms,\n        fetch_max_bytes=fetch_max_bytes,\n        fetch_min_bytes=fetch_min_bytes,\n        max_partition_fetch_bytes=max_partition_fetch_bytes,\n        auto_offset_reset=auto_offset_reset,\n        enable_auto_commit=auto_commit,\n        auto_commit_interval_ms=auto_commit_interval_ms,\n        check_crcs=check_crcs,\n        partition_assignment_strategy=partition_assignment_strategy,\n        max_poll_interval_ms=max_poll_interval_ms,\n        rebalance_timeout_ms=rebalance_timeout_ms,\n        session_timeout_ms=session_timeout_ms,\n        heartbeat_interval_ms=heartbeat_interval_ms,\n        consumer_timeout_ms=consumer_timeout_ms,\n        max_poll_records=max_poll_records,\n        exclude_internal_topics=exclude_internal_topics,\n        isolation_level=isolation_level,\n    )\n    handler = self.handlers.get(\n        key,\n        Handler(\n            *topics,\n            log_context_builder=partial(\n                self._get_log_context,\n                topics=topics,\n                group_id=group_id,\n            ),\n            is_manual=not auto_commit,\n            group_id=group_id,\n            client_id=self.client_id,\n            builder=builder,\n            description=description,\n            title=title,\n            batch=batch,\n            batch_timeout_ms=batch_timeout_ms,\n            max_records=max_records,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n        ),\n    )\n\n    self.handlers[key] = handler\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[\n        aiokafka.ConsumerRecord, P_HandlerParams, T_HandlerReturn\n    ]:\n        \"\"\"A wrapper function for a consumer handler.\n\n        Args:\n            func : The consumer handler function to be wrapped.\n\n        Returns:\n            The wrapped handler call.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        handler_call, dependant = self._wrap_handler(\n            func=func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRoute/","title":"KafkaRoute","text":"","boost":0.5},{"location":"api/faststream/kafka/KafkaRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/","title":"KafkaRouter","text":"","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter","title":"faststream.kafka.KafkaRouter","text":"
KafkaRouter(\n    prefix: str = \"\",\n    handlers: Sequence[KafkaRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[aiokafka.ConsumerRecord, KafkaMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[KafkaMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: KafkaRouter

A class to represent a Kafka router.

METHOD DESCRIPTION _get_publisher_key

Get the key for a publisher

_update_publisher_prefix

Update the prefix of a publisher

publisher

Create a new publisher

Source code in faststream/kafka/router.py
        publisher: The publisher object.\n\n    Returns:\n        The publisher key.\n\n    \"\"\"\n    return publisher.topic\n\n@override\n@staticmethod\ndef _update_publisher_prefix(  # type: ignore[override]\n    prefix: str,\n    publisher: Publisher,\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.publisher","title":"publisher","text":"
publisher(\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n

Publishes a message to a topic.

PARAMETER DESCRIPTION topic

The topic to publish the message to.

TYPE: str

key

The key associated with the message.

TYPE: bytes DEFAULT: None

partition

The partition to publish the message to.

TYPE: int DEFAULT: None

timestamp_ms

The timestamp of the message in milliseconds.

TYPE: int DEFAULT: None

headers

Additional headers for the message.

TYPE: Dict[str, str] DEFAULT: None

reply_to

The topic to reply to.

TYPE: str DEFAULT: ''

batch

Whether to publish the message as part of a batch.

TYPE: bool DEFAULT: False

title

The title of the message.

TYPE: str DEFAULT: None

description

The description of the message.

TYPE: str DEFAULT: None

RETURNS DESCRIPTION Publisher

The publisher object used to publish the message.

TYPE: Publisher

Source code in faststream/kafka/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"Publishes a message to a topic.\n\n    Args:\n        topic (str): The topic to publish the message to.\n        key (bytes, optional): The key associated with the message.\n        partition (int, optional): The partition to publish the message to.\n        timestamp_ms (int, optional): The timestamp of the message in milliseconds.\n        headers (Dict[str, str], optional): Additional headers for the message.\n        reply_to (str, optional): The topic to reply to.\n        batch (bool, optional): Whether to publish the message as part of a batch.\n        title (str, optional): The title of the message.\n        description (str, optional): The description of the message.\n\n    Returns:\n        Publisher: The publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            topic=topic,\n            key=key,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            batch=batch,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/KafkaRouter/#faststream.kafka.KafkaRouter.subscriber","title":"subscriber","text":"
subscriber(\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    value_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\", \"earliest\", \"none\"\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[\n        AbstractPartitionAssignor\n    ] = (RoundRobinPartitionAssignor),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\", \"read_committed\"\n    ] = \"read_uncommitted\",\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[aiokafka.ConsumerRecord, KafkaMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[KafkaMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Filter[KafkaMessage] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    retry: Union[bool, int] = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aiokafka.ConsumerRecord,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n
Source code in faststream/kafka/router.py
    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"Publishes a message to a topic.\n\n    Args:\n        topic (str): The topic to publish the message to.\n        key (bytes, optional): The key associated with the message.\n        partition (int, optional): The partition to publish the message to.\n        timestamp_ms (int, optional): The timestamp of the message in milliseconds.\n        headers (Dict[str, str], optional): Additional headers for the message.\n        reply_to (str, optional): The topic to reply to.\n        batch (bool, optional): Whether to publish the message as part of a batch.\n        title (str, optional): The title of the message.\n        description (str, optional): The description of the message.\n\n    Returns:\n        Publisher: The publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            topic=topic,\n            key=key,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            batch=batch,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/kafka/TestApp/#faststream.broker.test.TestApp","title":"faststream.broker.test.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/kafka/TestApp/#faststream.broker.test.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/","title":"TestKafkaBroker","text":"","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker","title":"faststream.kafka.TestKafkaBroker","text":"
TestKafkaBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[KafkaBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/kafka/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: KafkaBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(  # type: ignore[call-overload,misc]\n        publisher.topic,\n        batch=publisher.batch,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f  # type: ignore[no-any-return]\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: KafkaBroker, publisher: Any\n) -> None\n
Source code in faststream/kafka/test.py
@staticmethod\ndef patch_publisher(broker: KafkaBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/kafka/TestKafkaBroker/#faststream.kafka.TestKafkaBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> None\n
Source code in faststream/kafka/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> None:\n    broker.handlers.pop(publisher.topic, None)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/","title":"Handler","text":"","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler","title":"faststream.kafka.asyncapi.Handler","text":"
Handler(\n    *topics: str,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    group_id: Optional[str] = None,\n    client_id: str = \"faststream-\" + __version__,\n    builder: Callable[..., AIOKafkaConsumer],\n    is_manual: bool = False,\n    batch: bool = False,\n    batch_timeout_ms: int = 200,\n    max_records: Optional[int] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True\n)\n

Bases: LogicHandler, AsyncAPIOperation

A class to handle logic and async API operations.

METHOD DESCRIPTION schema

Returns a dictionary of channels.

Initialize a Kafka consumer for the specified topics.

PARAMETER DESCRIPTION *topics

Variable length argument list of topics to consume from.

TYPE: str DEFAULT: ()

group_id

Optional group ID for the consumer.

TYPE: Optional[str] DEFAULT: None

client_id

Client ID for the consumer.

TYPE: str DEFAULT: 'faststream-' + __version__

builder

Callable that constructs an AIOKafkaConsumer instance.

TYPE: Callable[..., AIOKafkaConsumer]

batch

Flag indicating whether to consume messages in batches.

TYPE: bool DEFAULT: False

batch_timeout_ms

Timeout in milliseconds for batch consumption.

TYPE: int DEFAULT: 200

max_records

Maximum number of records to consume in a batch.

TYPE: Optional[int] DEFAULT: None

title

Optional title for the consumer.

TYPE: Optional[str] DEFAULT: None

description

Optional description for the consumer.

TYPE: Optional[str] DEFAULT: None

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/kafka/handler.py
@override\ndef __init__(\n    self,\n    *topics: str,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # Kafka information\n    group_id: Optional[str] = None,\n    client_id: str = \"faststream-\" + __version__,\n    builder: Callable[..., AIOKafkaConsumer],\n    is_manual: bool = False,\n    batch: bool = False,\n    batch_timeout_ms: int = 200,\n    max_records: Optional[int] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    \"\"\"Initialize a Kafka consumer for the specified topics.\n\n    Args:\n        *topics: Variable length argument list of topics to consume from.\n        group_id: Optional group ID for the consumer.\n        client_id: Client ID for the consumer.\n        builder: Callable that constructs an AIOKafkaConsumer instance.\n        batch: Flag indicating whether to consume messages in batches.\n        batch_timeout_ms: Timeout in milliseconds for batch consumption.\n        max_records: Maximum number of records to consume in a batch.\n        title: Optional title for the consumer.\n        description: Optional description for the consumer.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.group_id = group_id\n    self.client_id = client_id\n    self.topics = topics\n\n    self.batch = batch\n    self.batch_timeout_ms = batch_timeout_ms\n    self.max_records = max_records\n    self.is_manual = is_manual\n\n    self.builder = builder\n    self.task = None\n    self.consumer = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = batch\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.batch_timeout_ms","title":"batch_timeout_ms instance-attribute","text":"
batch_timeout_ms = batch_timeout_ms\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.builder","title":"builder instance-attribute","text":"
builder = builder\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.client_id","title":"client_id instance-attribute","text":"
client_id = client_id\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.consumer","title":"consumer class-attribute instance-attribute","text":"
consumer: Optional[AIOKafkaConsumer] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.group_id","title":"group_id class-attribute instance-attribute","text":"
group_id: Optional[str] = group_id\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.is_manual","title":"is_manual instance-attribute","text":"
is_manual = is_manual\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.max_records","title":"max_records instance-attribute","text":"
max_records = max_records\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.task","title":"task class-attribute instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.topics","title":"topics instance-attribute","text":"
topics: Sequence[str] = topics\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        ConsumerRecord, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: CustomParser[\n        Union[ConsumerRecord, Tuple[ConsumerRecord, ...]],\n        KafkaMessage,\n    ],\n    decoder: Optional[CustomDecoder[KafkaMessage]],\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[ConsumerRecord, ...]]],\n    ],\n    middlewares: Optional[\n        Sequence[Callable[[ConsumerRecord], BaseMiddleware]]\n    ]\n) -> None\n

Adds a call to the handler.

PARAMETER DESCRIPTION handler

The handler function to be called.

TYPE: HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn]

dependant

The dependant model.

TYPE: CallModel[P_HandlerParams, T_HandlerReturn]

parser

Optional custom parser for parsing the input.

TYPE: CustomParser[Union[ConsumerRecord, Tuple[ConsumerRecord, ...]], KafkaMessage]

decoder

Optional custom decoder for decoding the input.

TYPE: Optional[CustomDecoder[KafkaMessage]]

filter

The filter for filtering the input.

TYPE: Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[ConsumerRecord, ...]]]]

middlewares

Optional sequence of middlewares to be applied.

TYPE: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]]

RETURNS DESCRIPTION None

None

Source code in faststream/kafka/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: CustomParser[\n        Union[ConsumerRecord, Tuple[ConsumerRecord, ...]], KafkaMessage\n    ],\n    decoder: Optional[CustomDecoder[KafkaMessage]],\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[ConsumerRecord, ...]]],\n    ],\n    middlewares: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]],\n) -> None:\n    \"\"\"Adds a call to the handler.\n\n    Args:\n        handler: The handler function to be called.\n        dependant: The dependant model.\n        parser: Optional custom parser for parsing the input.\n        decoder: Optional custom decoder for decoding the input.\n        filter: The filter for filtering the input.\n        middlewares: Optional sequence of middlewares to be applied.\n\n    Returns:\n        None\n\n    \"\"\"\n    parser_ = resolve_custom_func(  # type: ignore[type-var]\n        parser,  # type: ignore[arg-type]\n        (\n            AioKafkaParser.parse_message_batch  # type: ignore[arg-type]\n            if self.batch\n            else AioKafkaParser.parse_message\n        ),\n    )\n    decoder_ = resolve_custom_func(\n        decoder,  # type: ignore[arg-type]\n        (\n            AioKafkaParser.decode_message_batch  # type: ignore[arg-type]\n            if self.batch\n            else AioKafkaParser.decode_message\n        ),\n    )\n    super().add_call(\n        handler=handler,\n        parser=parser_,\n        decoder=decoder_,\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/kafka/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.consumer is not None:\n        await self.consumer.stop()\n        self.consumer = None\n\n    if self.task is not None:\n        self.task.cancel()\n        self.task = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(\n    topics: Sequence[str], group_id: Optional[str] = None\n) -> str\n
Source code in faststream/kafka/handler.py
@staticmethod\ndef get_routing_hash(topics: Sequence[str], group_id: Optional[str] = None) -> str:\n    return \"\".join((*topics, group_id or \"\"))\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/kafka/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    channels = {}\n\n    payloads = self.get_payloads()\n\n    for t in self.topics:\n        handler_name = self._title or f\"{t}:{self.call_name}\"\n        channels[handler_name] = Channel(\n            description=self.description,\n            subscribe=Operation(\n                message=Message(\n                    title=f\"{handler_name}:Message\",\n                    payload=resolve_payloads(payloads),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(kafka=kafka.ChannelBinding(topic=t)),\n        )\n\n    return channels\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Handler/#faststream.kafka.asyncapi.Handler.start","title":"start async","text":"
start(\n    **consumer_kwargs: Unpack[ConsumerConnectionParams],\n) -> None\n

Start the consumer.

PARAMETER DESCRIPTION **consumer_kwargs

Additional keyword arguments to pass to the consumer.

TYPE: Unpack[ConsumerConnectionParams] DEFAULT: {}

RETURNS DESCRIPTION None

None

Source code in faststream/kafka/handler.py
@override\nasync def start(  # type: ignore[override]\n    self,\n    **consumer_kwargs: Unpack[ConsumerConnectionParams],\n) -> None:\n    \"\"\"Start the consumer.\n\n    Args:\n        **consumer_kwargs: Additional keyword arguments to pass to the consumer.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.consumer = consumer = self.builder(\n        *self.topics,\n        group_id=self.group_id,\n        client_id=self.client_id,\n        **consumer_kwargs,\n    )\n    await consumer.start()\n    self.task = asyncio.create_task(self._consume())\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/","title":"Publisher","text":"","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher","title":"faststream.kafka.asyncapi.Publisher","text":"

Bases: LogicPublisher, AsyncAPIOperation

A class representing a publisher.

METHOD DESCRIPTION schema

returns the schema for the publisher

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported

","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = field(default=False)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.client_id","title":"client_id class-attribute instance-attribute","text":"
client_id: str = field(default='faststream-' + __version__)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.key","title":"key class-attribute instance-attribute","text":"
key: Optional[bytes] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.name","title":"name property","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.partition","title":"partition class-attribute instance-attribute","text":"
partition: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = ''\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.timestamp_ms","title":"timestamp_ms class-attribute instance-attribute","text":"
timestamp_ms: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.topic","title":"topic class-attribute instance-attribute","text":"
topic: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.publish","title":"publish async","text":"
publish(\n    *messages: SendableMessage,\n    message: SendableMessage = \"\",\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None\n) -> None\n

Publish messages to a topic.

PARAMETER DESCRIPTION *messages

Variable length argument list of SendableMessage objects.

TYPE: SendableMessage DEFAULT: ()

message

A SendableMessage object. Default is an empty string.

TYPE: SendableMessage DEFAULT: ''

key

Optional bytes object representing the message key.

TYPE: Optional[bytes] DEFAULT: None

partition

Optional integer representing the partition to publish the message to.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

Optional integer representing the timestamp of the message in milliseconds.

TYPE: Optional[int] DEFAULT: None

headers

Optional dictionary of header key-value pairs.

TYPE: Optional[Dict[str, str]] DEFAULT: None

correlation_id

Optional string representing the correlation ID of the message.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION AssertionError

If _producer is not set up.

AssertionError

If batch flag is not set and there are multiple messages.

ValueError

If message is not a sequence when messages is empty.

Source code in faststream/kafka/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *messages: SendableMessage,\n    message: SendableMessage = \"\",\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n) -> None:\n    \"\"\"Publish messages to a topic.\n\n    Args:\n        *messages: Variable length argument list of SendableMessage objects.\n        message: A SendableMessage object. Default is an empty string.\n        key: Optional bytes object representing the message key.\n        partition: Optional integer representing the partition to publish the message to.\n        timestamp_ms: Optional integer representing the timestamp of the message in milliseconds.\n        headers: Optional dictionary of header key-value pairs.\n        correlation_id: Optional string representing the correlation ID of the message.\n\n    Returns:\n        None\n\n    Raises:\n        AssertionError: If `_producer` is not set up.\n        AssertionError: If `batch` flag is not set and there are multiple messages.\n        ValueError: If `message` is not a sequence when `messages` is empty.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    assert (  # nosec B101\n        self.batch or len(messages) < 2\n    ), \"You can't send multiple messages without `batch` flag\"\n    assert self.topic, \"You have to specify outgoing topic\"  # nosec B101\n\n    if not self.batch:\n        return await self._producer.publish(\n            message=next(iter(messages), message),\n            topic=self.topic,\n            key=key or self.key,\n            partition=partition or self.partition,\n            timestamp_ms=timestamp_ms or self.timestamp_ms,\n            correlation_id=correlation_id,\n            headers=headers or self.headers,\n            reply_to=self.reply_to or \"\",\n        )\n    else:\n        to_send: Sequence[SendableMessage]\n        if not messages:\n            if not isinstance(message, Sequence):\n                raise ValueError(\n                    f\"Message: {message} should be Sequence type to send in batch\"\n                )\n            else:\n                to_send = message\n        else:\n            to_send = messages\n\n        await self._producer.publish_batch(\n            *to_send,\n            topic=self.topic,\n            partition=partition or self.partition,\n            timestamp_ms=timestamp_ms or self.timestamp_ms,\n            headers=headers or self.headers,\n        )\n        return None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/kafka/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    return {\n        self.name: Channel(\n            description=self.description,\n            publish=Operation(\n                message=Message(\n                    title=f\"{self.name}:Message\",\n                    payload=resolve_payloads(payloads, \"Publisher\"),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(kafka=kafka.ChannelBinding(topic=self.topic)),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/kafka/asyncapi/Publisher/#faststream.kafka.asyncapi.Publisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/","title":"KafkaBroker","text":"","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker","title":"faststream.kafka.broker.KafkaBroker","text":"
KafkaBroker(\n    bootstrap_servers: Union[\n        str, Iterable[str]\n    ] = \"localhost\",\n    *,\n    protocol: str = None,\n    protocol_version: str = \"auto\",\n    client_id: str = \"faststream-\" + __version__,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: KafkaLoggingMixin, BrokerAsyncUsecase[ConsumerRecord, ConsumerConnectionParams]

KafkaBroker is a class for managing Kafka message consumption and publishing. It extends BrokerAsyncUsecase to handle asynchronous operations.

PARAMETER DESCRIPTION bootstrap_servers

Kafka bootstrap server(s).

TYPE: Union[str, Iterable[str]] DEFAULT: 'localhost'

protocol

The protocol used (default is \"kafka\").

TYPE: str DEFAULT: None

protocol_version

The Kafka protocol version (default is \"auto\").

TYPE: str DEFAULT: 'auto'

client_id

The client ID for the Kafka client.

TYPE: str DEFAULT: 'faststream-' + __version__

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

METHOD DESCRIPTION connect

Establishes a connection to Kafka.

start

Starts the KafkaBroker and message handlers.

publish

Publishes a message to Kafka.

Initialize a KafkaBroker instance.

PARAMETER DESCRIPTION bootstrap_servers

Kafka bootstrap server(s).

TYPE: Union[str, Iterable[str]] DEFAULT: 'localhost'

protocol

The protocol used (default is \"kafka\").

TYPE: str DEFAULT: None

protocol_version

The Kafka protocol version (default is \"auto\").

TYPE: str DEFAULT: 'auto'

client_id

The client ID for the Kafka client.

TYPE: str DEFAULT: 'faststream-' + __version__

security

Security protocol to use in communication with the broker (default is None).

TYPE: Optional[BaseSecurity] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/kafka/broker.py
def __init__(\n    self,\n    bootstrap_servers: Union[str, Iterable[str]] = \"localhost\",\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: str = \"auto\",\n    client_id: str = \"faststream-\" + __version__,\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Initialize a KafkaBroker instance.\n\n    Args:\n        bootstrap_servers (Union[str, Iterable[str]]): Kafka bootstrap server(s).\n        protocol (str): The protocol used (default is \"kafka\").\n        protocol_version (str): The Kafka protocol version (default is \"auto\").\n        client_id (str): The client ID for the Kafka client.\n        security (Optional[BaseSecurity]): Security protocol to use in communication with the broker (default is None).\n        **kwargs: Additional keyword arguments.\n    \"\"\"\n    if protocol is None:\n        if security is not None and security.use_ssl:\n            protocol = \"kafka-secure\"\n        else:\n            protocol = \"kafka\"\n\n    super().__init__(\n        url=[bootstrap_servers]\n        if isinstance(bootstrap_servers, str)\n        else list(bootstrap_servers),\n        protocol=protocol,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n        client_id=client_id,\n        bootstrap_servers=bootstrap_servers,\n    )\n    self.client_id = client_id\n    self._producer = None\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.client_id","title":"client_id instance-attribute","text":"
client_id = client_id\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[str, Handler]\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.url","title":"url instance-attribute","text":"
url: List[str]\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.connect","title":"connect async","text":"
connect(\n    *args: Any, **kwargs: Any\n) -> ConsumerConnectionParams\n

Establishes a connection to Kafka and returns connection parameters.

PARAMETER DESCRIPTION *args

Additional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION ConsumerConnectionParams

The connection parameters.

TYPE: ConsumerConnectionParams

Source code in faststream/kafka/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> ConsumerConnectionParams:\n    \"\"\"\n    Establishes a connection to Kafka and returns connection parameters.\n\n    Args:\n        *args: Additional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        ConsumerConnectionParams: The connection parameters.\n    \"\"\"\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.publish","title":"publish async","text":"
publish(*args: Any, **kwargs: Any) -> None\n

Publish a message to Kafka.

PARAMETER DESCRIPTION *args

Positional arguments for message publishing.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments for message publishing.

TYPE: Any DEFAULT: {}

RAISES DESCRIPTION RuntimeError

If KafkaBroker is not started yet.

Source code in faststream/kafka/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Publish a message to Kafka.\n\n    Args:\n        *args: Positional arguments for message publishing.\n        **kwargs: Keyword arguments for message publishing.\n\n    Raises:\n        RuntimeError: If KafkaBroker is not started yet.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.publish_batch","title":"publish_batch async","text":"
publish_batch(*args: Any, **kwargs: Any) -> None\n

Publish a batch of messages to Kafka.

PARAMETER DESCRIPTION *args

Positional arguments for message publishing.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments for message publishing.

TYPE: Any DEFAULT: {}

RAISES DESCRIPTION RuntimeError

If KafkaBroker is not started yet.

Source code in faststream/kafka/broker.py
async def publish_batch(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Publish a batch of messages to Kafka.\n\n    Args:\n        *args: Positional arguments for message publishing.\n        **kwargs: Keyword arguments for message publishing.\n\n    Raises:\n        RuntimeError: If KafkaBroker is not started yet.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    await self._producer.publish_batch(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.publisher","title":"publisher","text":"
publisher(\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n

Create a message publisher for the specified topic.

PARAMETER DESCRIPTION topic

The topic to publish messages to.

TYPE: str

key

Message key.

TYPE: Optional[bytes] DEFAULT: None

partition

Partition to send the message to.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

Message timestamp in milliseconds.

TYPE: Optional[int] DEFAULT: None

headers

Message headers.

TYPE: Optional[Dict[str, str]] DEFAULT: None

reply_to

The topic to which responses should be sent.

TYPE: str DEFAULT: ''

batch

Whether to publish messages in batches.

TYPE: bool DEFAULT: False

title

AsyncAPI title.

TYPE: Optional[str] DEFAULT: None

description

AsyncAPI description.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION Publisher

A message publisher.

TYPE: Publisher

Source code in faststream/kafka/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"\n    Create a message publisher for the specified topic.\n\n    Args:\n        topic (str): The topic to publish messages to.\n        key (Optional[bytes]): Message key.\n        partition (Optional[int]): Partition to send the message to.\n        timestamp_ms (Optional[int]): Message timestamp in milliseconds.\n        headers (Optional[Dict[str, str]]): Message headers.\n        reply_to (str): The topic to which responses should be sent.\n        batch (bool): Whether to publish messages in batches.\n        title (Optional[str]): AsyncAPI title.\n        description (Optional[str]): AsyncAPI description.\n\n    Returns:\n        Publisher: A message publisher.\n    \"\"\"\n    publisher = self._publishers.get(\n        topic,\n        Publisher(\n            topic=topic,\n            client_id=self.client_id,\n            key=key,\n            batch=batch,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(topic, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.start","title":"start async","text":"
start() -> None\n

Start the KafkaBroker and message handlers.

Source code in faststream/kafka/broker.py
async def start(self) -> None:\n    \"\"\"\n    Start the KafkaBroker and message handlers.\n    \"\"\"\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n\n    for handler in self.handlers.values():\n        c = self._get_log_context(None, handler.topics, handler.group_id)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(**(self._connection or {}))\n
","boost":0.5},{"location":"api/faststream/kafka/broker/KafkaBroker/#faststream.kafka.broker.KafkaBroker.subscriber","title":"subscriber","text":"
subscriber(\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    value_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\", \"earliest\", \"none\"\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[\n        AbstractPartitionAssignor\n    ] = (RoundRobinPartitionAssignor),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\", \"read_committed\"\n    ] = \"read_uncommitted\",\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        Union[\n            CustomParser[\n                aiokafka.ConsumerRecord, KafkaMessage\n            ],\n            CustomParser[\n                Tuple[aiokafka.ConsumerRecord, ...],\n                KafkaMessage,\n            ],\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[\n            StreamMessage[\n                Tuple[aiokafka.ConsumerRecord, ...]\n            ]\n        ],\n    ] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    Union[\n        HandlerCallWrapper[\n            aiokafka.ConsumerRecord,\n            P_HandlerParams,\n            T_HandlerReturn,\n        ],\n        HandlerCallWrapper[\n            Tuple[aiokafka.ConsumerRecord, ...],\n            P_HandlerParams,\n            T_HandlerReturn,\n        ],\n    ],\n]\n

Create a message subscriber for the specified topics.

PARAMETER DESCRIPTION *topics

The topics to subscribe to.

TYPE: str DEFAULT: ()

group_id

The Kafka consumer group ID.

TYPE: Optional[str] DEFAULT: None

key_deserializer

Key deserializer function.

TYPE: Optional[Callable[[bytes], Any]] DEFAULT: None

value_deserializer

Value deserializer function.

TYPE: Optional[Callable[[bytes], Any]] DEFAULT: None

fetch_max_wait_ms

The maximum time to wait for data.

TYPE: int DEFAULT: 500

fetch_max_bytes

The maximum number of bytes to fetch.

TYPE: int DEFAULT: 52428800

fetch_min_bytes

The minimum number of bytes to fetch.

TYPE: int DEFAULT: 1

max_partition_fetch_bytes

The maximum bytes to fetch for a partition.

TYPE: int DEFAULT: 1 * 1024 * 1024

auto_offset_reset

Auto offset reset policy.

TYPE: Literal['latest', 'earliest', 'none'] DEFAULT: 'latest'

auto_commit

Whether to enable auto-commit.

TYPE: bool DEFAULT: True

auto_commit_interval_ms

Auto-commit interval in milliseconds.

TYPE: int DEFAULT: 5000

check_crcs

Whether to check CRCs.

TYPE: bool DEFAULT: True

partition_assignment_strategy

Partition assignment strategy.

TYPE: Sequence[AbstractPartitionAssignor] DEFAULT: (RoundRobinPartitionAssignor)

max_poll_interval_ms

Maximum poll interval in milliseconds.

TYPE: int DEFAULT: 300000

rebalance_timeout_ms

Rebalance timeout in milliseconds.

TYPE: Optional[int] DEFAULT: None

session_timeout_ms

Session timeout in milliseconds.

TYPE: int DEFAULT: 10000

heartbeat_interval_ms

Heartbeat interval in milliseconds.

TYPE: int DEFAULT: 3000

consumer_timeout_ms

Consumer timeout in milliseconds.

TYPE: int DEFAULT: 200

max_poll_records

Maximum number of records to poll.

TYPE: Optional[int] DEFAULT: None

exclude_internal_topics

Whether to exclude internal topics.

TYPE: bool DEFAULT: True

isolation_level

Isolation level.

TYPE: Literal['read_uncommitted', 'read_committed'] DEFAULT: 'read_uncommitted'

dependencies

Additional dependencies for message handling.

TYPE: Sequence[Depends] DEFAULT: ()

parser

Message parser.

TYPE: Optional[Union[CustomParser[ConsumerRecord], CustomParser[Tuple[ConsumerRecord, ...]]]] DEFAULT: None

decoder

Message decoder.

TYPE: Optional[CustomDecoder] DEFAULT: None

middlewares

Message middlewares.

TYPE: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]] DEFAULT: None

filter

Message filter.

TYPE: Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[ConsumerRecord, ...]]]] DEFAULT: default_filter

batch

Whether to process messages in batches.

TYPE: bool DEFAULT: False

max_records

Maximum number of records to process in each batch.

TYPE: Optional[int] DEFAULT: None

batch_timeout_ms

Batch timeout in milliseconds.

TYPE: int DEFAULT: 200

no_ack

Whether not to ack/nack/reject messages.

TYPE: bool DEFAULT: False

title

AsyncAPI title.

TYPE: Optional[str] DEFAULT: None

description

AsyncAPI description.

TYPE: Optional[str] DEFAULT: None

**original_kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Callable

A decorator that wraps a message handler function.

TYPE: Callable[[Callable[P_HandlerParams, T_HandlerReturn]], Union[HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn], HandlerCallWrapper[Tuple[ConsumerRecord, ...], P_HandlerParams, T_HandlerReturn]]]

Source code in faststream/kafka/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[Callable[[bytes], Any]] = None,\n    value_deserializer: Optional[Callable[[bytes], Any]] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\",\n        \"earliest\",\n        \"none\",\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[AbstractPartitionAssignor] = (\n        RoundRobinPartitionAssignor,\n    ),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\",\n        \"read_committed\",\n    ] = \"read_uncommitted\",\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        Union[\n            CustomParser[aiokafka.ConsumerRecord, KafkaMessage],\n            CustomParser[Tuple[aiokafka.ConsumerRecord, ...], KafkaMessage],\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord],\n                BaseMiddleware,\n            ]\n        ]\n    ] = None,\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[aiokafka.ConsumerRecord, ...]]],\n    ] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    Union[\n        HandlerCallWrapper[\n            aiokafka.ConsumerRecord, P_HandlerParams, T_HandlerReturn\n        ],\n        HandlerCallWrapper[\n            Tuple[aiokafka.ConsumerRecord, ...], P_HandlerParams, T_HandlerReturn\n        ],\n    ],\n]:\n    \"\"\"\n    Create a message subscriber for the specified topics.\n\n    Args:\n        *topics (str): The topics to subscribe to.\n        group_id (Optional[str]): The Kafka consumer group ID.\n        key_deserializer (Optional[Callable[[bytes], Any]]): Key deserializer function.\n        value_deserializer (Optional[Callable[[bytes], Any]]): Value deserializer function.\n        fetch_max_wait_ms (int): The maximum time to wait for data.\n        fetch_max_bytes (int): The maximum number of bytes to fetch.\n        fetch_min_bytes (int): The minimum number of bytes to fetch.\n        max_partition_fetch_bytes (int): The maximum bytes to fetch for a partition.\n        auto_offset_reset (Literal[\"latest\", \"earliest\", \"none\"]): Auto offset reset policy.\n        auto_commit (bool): Whether to enable auto-commit.\n        auto_commit_interval_ms (int): Auto-commit interval in milliseconds.\n        check_crcs (bool): Whether to check CRCs.\n        partition_assignment_strategy (Sequence[AbstractPartitionAssignor]): Partition assignment strategy.\n        max_poll_interval_ms (int): Maximum poll interval in milliseconds.\n        rebalance_timeout_ms (Optional[int]): Rebalance timeout in milliseconds.\n        session_timeout_ms (int): Session timeout in milliseconds.\n        heartbeat_interval_ms (int): Heartbeat interval in milliseconds.\n        consumer_timeout_ms (int): Consumer timeout in milliseconds.\n        max_poll_records (Optional[int]): Maximum number of records to poll.\n        exclude_internal_topics (bool): Whether to exclude internal topics.\n        isolation_level (Literal[\"read_uncommitted\", \"read_committed\"]): Isolation level.\n        dependencies (Sequence[Depends]): Additional dependencies for message handling.\n        parser (Optional[Union[CustomParser[aiokafka.ConsumerRecord], CustomParser[Tuple[aiokafka.ConsumerRecord, ...]]]]): Message parser.\n        decoder (Optional[CustomDecoder]): Message decoder.\n        middlewares (Optional[Sequence[Callable[[aiokafka.ConsumerRecord], BaseMiddleware]]]): Message middlewares.\n        filter (Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[aiokafka.ConsumerRecord, ...]]]]): Message filter.\n        batch (bool): Whether to process messages in batches.\n        max_records (Optional[int]): Maximum number of records to process in each batch.\n        batch_timeout_ms (int): Batch timeout in milliseconds.\n        no_ack (bool): Whether not to ack/nack/reject messages.\n        title (Optional[str]): AsyncAPI title.\n        description (Optional[str]): AsyncAPI description.\n        **original_kwargs: Additional keyword arguments.\n\n    Returns:\n        Callable: A decorator that wraps a message handler function.\n    \"\"\"\n    super().subscriber()\n\n    self._setup_log_context(topics, group_id)\n\n    if not auto_commit and not group_id:\n        raise ValueError(\"You should install `group_id` with manual commit mode\")\n\n    key = Handler.get_routing_hash(topics, group_id)\n    builder = partial(\n        aiokafka.AIOKafkaConsumer,\n        key_deserializer=key_deserializer,\n        value_deserializer=value_deserializer,\n        fetch_max_wait_ms=fetch_max_wait_ms,\n        fetch_max_bytes=fetch_max_bytes,\n        fetch_min_bytes=fetch_min_bytes,\n        max_partition_fetch_bytes=max_partition_fetch_bytes,\n        auto_offset_reset=auto_offset_reset,\n        enable_auto_commit=auto_commit,\n        auto_commit_interval_ms=auto_commit_interval_ms,\n        check_crcs=check_crcs,\n        partition_assignment_strategy=partition_assignment_strategy,\n        max_poll_interval_ms=max_poll_interval_ms,\n        rebalance_timeout_ms=rebalance_timeout_ms,\n        session_timeout_ms=session_timeout_ms,\n        heartbeat_interval_ms=heartbeat_interval_ms,\n        consumer_timeout_ms=consumer_timeout_ms,\n        max_poll_records=max_poll_records,\n        exclude_internal_topics=exclude_internal_topics,\n        isolation_level=isolation_level,\n    )\n    handler = self.handlers.get(\n        key,\n        Handler(\n            *topics,\n            log_context_builder=partial(\n                self._get_log_context,\n                topics=topics,\n                group_id=group_id,\n            ),\n            is_manual=not auto_commit,\n            group_id=group_id,\n            client_id=self.client_id,\n            builder=builder,\n            description=description,\n            title=title,\n            batch=batch,\n            batch_timeout_ms=batch_timeout_ms,\n            max_records=max_records,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n        ),\n    )\n\n    self.handlers[key] = handler\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[\n        aiokafka.ConsumerRecord, P_HandlerParams, T_HandlerReturn\n    ]:\n        \"\"\"A wrapper function for a consumer handler.\n\n        Args:\n            func : The consumer handler function to be wrapped.\n\n        Returns:\n            The wrapped handler call.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        handler_call, dependant = self._wrap_handler(\n            func=func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/kafka/fastapi/Context/#faststream.broker.fastapi.context.Context","title":"faststream.broker.fastapi.context.Context","text":"
Context(name: str) -> Any\n
Source code in faststream/broker/fastapi/context.py
def Context(name: str) -> Any:\n    return params.Depends(\n        lambda: context.resolve(name),\n        use_cache=True,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/","title":"KafkaRouter","text":"","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter","title":"faststream.kafka.fastapi.KafkaRouter","text":"
KafkaRouter(\n    bootstrap_servers: Union[\n        str, Iterable[str]\n    ] = \"localhost\",\n    *,\n    client_id: str = \"faststream-\" + __version__,\n    request_timeout_ms: int = 40 * 1000,\n    retry_backoff_ms: int = 100,\n    metadata_max_age_ms: int = 5 * 60 * 1000,\n    api_version: str = \"auto\",\n    connections_max_idle_ms: int = 540000,\n    security: Optional[BaseSecurity] = None,\n    acks: Union[\n        Literal[0, 1, -1, \"all\"], object\n    ] = _missing,\n    key_serializer: Optional[Callable[[Any], bytes]] = None,\n    value_serializer: Optional[\n        Callable[[Any], bytes]\n    ] = None,\n    compression_type: Optional[\n        Literal[\"gzip\", \"snappy\", \"lz4\", \"zstd\"]\n    ] = None,\n    max_batch_size: int = 16384,\n    partitioner: Callable[\n        [bytes, List[Partition], List[Partition]], Partition\n    ] = DefaultPartitioner(),\n    max_request_size: int = 1048576,\n    linger_ms: int = 0,\n    send_backoff_ms: int = 100,\n    enable_idempotence: bool = False,\n    transactional_id: Optional[str] = None,\n    transaction_timeout_ms: int = 60000,\n    loop: Optional[AbstractEventLoop] = None,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id),\n    graceful_timeout: Optional[float] = None,\n    apply_types: bool = True,\n    validate: bool = True,\n    decoder: Optional[CustomDecoder[KafkaMessage]] = None,\n    parser: Optional[\n        CustomParser[aiokafka.ConsumerRecord, KafkaMessage]\n    ] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    asyncapi_url: Union[str, List[str], None] = None,\n    protocol: str = \"kafka\",\n    protocol_version: str = \"auto\",\n    description: Optional[str] = None,\n    asyncapi_tags: Optional[Sequence[asyncapi.Tag]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    setup_state: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any\n)\n

Bases: StreamRouter[ConsumerRecord]

A class to route Kafka streams.

METHOD DESCRIPTION _setup_log_context

sets up the log context for the main broker and including broker

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.broker","title":"broker instance-attribute","text":"
broker: KafkaBroker\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.broker_class","title":"broker_class class-attribute instance-attribute","text":"
broker_class: Type[KafkaBroker] = KB\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any\n) -> HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n]\n

Add an API message queue route.

PARAMETER DESCRIPTION path

The path of the route.

TYPE: Union[NameRequired, str]

*extra

Additional path segments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint function to be called for this route.

TYPE: Callable[P_HandlerParams, T_HandlerReturn]

dependencies

The dependencies required by the endpoint function.

TYPE: Sequence[Depends]

**broker_kwargs

Additional keyword arguments to be passed to the broker.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]

The handler call wrapper for the route.

Source code in faststream/broker/fastapi/router.py
def add_api_mq_route(\n    self,\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any,\n) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n    \"\"\"Add an API message queue route.\n\n    Args:\n        path: The path of the route.\n        *extra: Additional path segments.\n        endpoint: The endpoint function to be called for this route.\n        dependencies: The dependencies required by the endpoint function.\n        **broker_kwargs: Additional keyword arguments to be passed to the broker.\n\n    Returns:\n        The handler call wrapper for the route.\n\n    \"\"\"\n    route: StreamRoute[MsgType, P_HandlerParams, T_HandlerReturn] = StreamRoute(\n        path,\n        *extra,\n        endpoint=endpoint,\n        dependencies=dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        broker=self.broker,\n        **broker_kwargs,\n    )\n    self.routes.append(route)\n    return route.handler\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.publisher","title":"publisher","text":"
publisher(\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.subscriber","title":"subscriber","text":"
subscriber(\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function decorator for subscribing to a message queue.

PARAMETER DESCRIPTION path

The path to subscribe to. Can be a string or a NameRequired object.

*extra

Additional path segments. Can be a NameRequired object or a string.

DEFAULT: ()

dependencies

Optional sequence of dependencies.

DEFAULT: None

**broker_kwargs

Additional keyword arguments for the broker.

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable decorator that adds the decorated function as an endpoint for the specified path.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def subscriber(\n    self,\n    path: Union[str, NameRequired],\n    *extra: Union[NameRequired, str],\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function decorator for subscribing to a message queue.\n\n    Args:\n        path : The path to subscribe to. Can be a string or a `NameRequired` object.\n        *extra : Additional path segments. Can be a `NameRequired` object or a string.\n        dependencies : Optional sequence of dependencies.\n        **broker_kwargs : Additional keyword arguments for the broker.\n\n    Returns:\n        A callable decorator that adds the decorated function as an endpoint for the specified path.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    def decorator(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n        \"\"\"A decorator function.\n\n        Args:\n            func: The function to be decorated.\n\n        Returns:\n            The decorated function.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        return self.add_api_mq_route(\n            path,\n            *extra,\n            endpoint=func,\n            dependencies=current_dependencies,\n            **broker_kwargs,\n        )\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/kafka/fastapi/KafkaRouter/#faststream.kafka.fastapi.KafkaRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/","title":"LogicHandler","text":"","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler","title":"faststream.kafka.handler.LogicHandler","text":"
LogicHandler(\n    *topics: str,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    group_id: Optional[str] = None,\n    client_id: str = \"faststream-\" + __version__,\n    builder: Callable[..., AIOKafkaConsumer],\n    is_manual: bool = False,\n    batch: bool = False,\n    batch_timeout_ms: int = 200,\n    max_records: Optional[int] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True\n)\n

Bases: AsyncHandler[ConsumerRecord]

A class to handle logic for consuming messages from Kafka.

METHOD DESCRIPTION __init__

constructor method for the LogicHandler class

start

method to start consuming messages from Kafka

close

method to close the Kafka consumer and cancel the consuming task

add_call

method to add a handler call for processing consumed messages

_consume

method to consume messages from Kafka and call the appropriate handler

Initialize a Kafka consumer for the specified topics.

PARAMETER DESCRIPTION *topics

Variable length argument list of topics to consume from.

TYPE: str DEFAULT: ()

group_id

Optional group ID for the consumer.

TYPE: Optional[str] DEFAULT: None

client_id

Client ID for the consumer.

TYPE: str DEFAULT: 'faststream-' + __version__

builder

Callable that constructs an AIOKafkaConsumer instance.

TYPE: Callable[..., AIOKafkaConsumer]

batch

Flag indicating whether to consume messages in batches.

TYPE: bool DEFAULT: False

batch_timeout_ms

Timeout in milliseconds for batch consumption.

TYPE: int DEFAULT: 200

max_records

Maximum number of records to consume in a batch.

TYPE: Optional[int] DEFAULT: None

title

Optional title for the consumer.

TYPE: Optional[str] DEFAULT: None

description

Optional description for the consumer.

TYPE: Optional[str] DEFAULT: None

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/kafka/handler.py
@override\ndef __init__(\n    self,\n    *topics: str,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # Kafka information\n    group_id: Optional[str] = None,\n    client_id: str = \"faststream-\" + __version__,\n    builder: Callable[..., AIOKafkaConsumer],\n    is_manual: bool = False,\n    batch: bool = False,\n    batch_timeout_ms: int = 200,\n    max_records: Optional[int] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    \"\"\"Initialize a Kafka consumer for the specified topics.\n\n    Args:\n        *topics: Variable length argument list of topics to consume from.\n        group_id: Optional group ID for the consumer.\n        client_id: Client ID for the consumer.\n        builder: Callable that constructs an AIOKafkaConsumer instance.\n        batch: Flag indicating whether to consume messages in batches.\n        batch_timeout_ms: Timeout in milliseconds for batch consumption.\n        max_records: Maximum number of records to consume in a batch.\n        title: Optional title for the consumer.\n        description: Optional description for the consumer.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.group_id = group_id\n    self.client_id = client_id\n    self.topics = topics\n\n    self.batch = batch\n    self.batch_timeout_ms = batch_timeout_ms\n    self.max_records = max_records\n    self.is_manual = is_manual\n\n    self.builder = builder\n    self.task = None\n    self.consumer = None\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = batch\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.batch_timeout_ms","title":"batch_timeout_ms instance-attribute","text":"
batch_timeout_ms = batch_timeout_ms\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.builder","title":"builder instance-attribute","text":"
builder = builder\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.client_id","title":"client_id instance-attribute","text":"
client_id = client_id\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.consumer","title":"consumer class-attribute instance-attribute","text":"
consumer: Optional[AIOKafkaConsumer] = None\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.group_id","title":"group_id class-attribute instance-attribute","text":"
group_id: Optional[str] = group_id\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.is_manual","title":"is_manual instance-attribute","text":"
is_manual = is_manual\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.max_records","title":"max_records instance-attribute","text":"
max_records = max_records\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.task","title":"task class-attribute instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.topics","title":"topics instance-attribute","text":"
topics: Sequence[str] = topics\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        ConsumerRecord, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: CustomParser[\n        Union[ConsumerRecord, Tuple[ConsumerRecord, ...]],\n        KafkaMessage,\n    ],\n    decoder: Optional[CustomDecoder[KafkaMessage]],\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[ConsumerRecord, ...]]],\n    ],\n    middlewares: Optional[\n        Sequence[Callable[[ConsumerRecord], BaseMiddleware]]\n    ]\n) -> None\n

Adds a call to the handler.

PARAMETER DESCRIPTION handler

The handler function to be called.

TYPE: HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn]

dependant

The dependant model.

TYPE: CallModel[P_HandlerParams, T_HandlerReturn]

parser

Optional custom parser for parsing the input.

TYPE: CustomParser[Union[ConsumerRecord, Tuple[ConsumerRecord, ...]], KafkaMessage]

decoder

Optional custom decoder for decoding the input.

TYPE: Optional[CustomDecoder[KafkaMessage]]

filter

The filter for filtering the input.

TYPE: Union[Filter[KafkaMessage], Filter[StreamMessage[Tuple[ConsumerRecord, ...]]]]

middlewares

Optional sequence of middlewares to be applied.

TYPE: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]]

RETURNS DESCRIPTION None

None

Source code in faststream/kafka/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: CustomParser[\n        Union[ConsumerRecord, Tuple[ConsumerRecord, ...]], KafkaMessage\n    ],\n    decoder: Optional[CustomDecoder[KafkaMessage]],\n    filter: Union[\n        Filter[KafkaMessage],\n        Filter[StreamMessage[Tuple[ConsumerRecord, ...]]],\n    ],\n    middlewares: Optional[Sequence[Callable[[ConsumerRecord], BaseMiddleware]]],\n) -> None:\n    \"\"\"Adds a call to the handler.\n\n    Args:\n        handler: The handler function to be called.\n        dependant: The dependant model.\n        parser: Optional custom parser for parsing the input.\n        decoder: Optional custom decoder for decoding the input.\n        filter: The filter for filtering the input.\n        middlewares: Optional sequence of middlewares to be applied.\n\n    Returns:\n        None\n\n    \"\"\"\n    parser_ = resolve_custom_func(  # type: ignore[type-var]\n        parser,  # type: ignore[arg-type]\n        (\n            AioKafkaParser.parse_message_batch  # type: ignore[arg-type]\n            if self.batch\n            else AioKafkaParser.parse_message\n        ),\n    )\n    decoder_ = resolve_custom_func(\n        decoder,  # type: ignore[arg-type]\n        (\n            AioKafkaParser.decode_message_batch  # type: ignore[arg-type]\n            if self.batch\n            else AioKafkaParser.decode_message\n        ),\n    )\n    super().add_call(\n        handler=handler,\n        parser=parser_,\n        decoder=decoder_,\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/kafka/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.consumer is not None:\n        await self.consumer.stop()\n        self.consumer = None\n\n    if self.task is not None:\n        self.task.cancel()\n        self.task = None\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(\n    topics: Sequence[str], group_id: Optional[str] = None\n) -> str\n
Source code in faststream/kafka/handler.py
@staticmethod\ndef get_routing_hash(topics: Sequence[str], group_id: Optional[str] = None) -> str:\n    return \"\".join((*topics, group_id or \"\"))\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/kafka/handler/LogicHandler/#faststream.kafka.handler.LogicHandler.start","title":"start async","text":"
start(\n    **consumer_kwargs: Unpack[ConsumerConnectionParams],\n) -> None\n

Start the consumer.

PARAMETER DESCRIPTION **consumer_kwargs

Additional keyword arguments to pass to the consumer.

TYPE: Unpack[ConsumerConnectionParams] DEFAULT: {}

RETURNS DESCRIPTION None

None

Source code in faststream/kafka/handler.py
@override\nasync def start(  # type: ignore[override]\n    self,\n    **consumer_kwargs: Unpack[ConsumerConnectionParams],\n) -> None:\n    \"\"\"Start the consumer.\n\n    Args:\n        **consumer_kwargs: Additional keyword arguments to pass to the consumer.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.consumer = consumer = self.builder(\n        *self.topics,\n        group_id=self.group_id,\n        client_id=self.client_id,\n        **consumer_kwargs,\n    )\n    await consumer.start()\n    self.task = asyncio.create_task(self._consume())\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/","title":"KafkaMessage","text":"","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage","title":"faststream.kafka.message.KafkaMessage","text":"
KafkaMessage(\n    *args: Any,\n    consumer: aiokafka.AIOKafkaConsumer,\n    is_manual: bool = False,\n    **kwargs: Any\n)\n

Bases: StreamMessage[ConsumerRecord]

Represents a Kafka message in the FastStream framework.

This class extends StreamMessage and is specialized for handling Kafka ConsumerRecord objects.

METHOD DESCRIPTION ack

Acknowledge the Kafka message.

nack

Negative acknowledgment of the Kafka message.

reject

Reject the Kafka message.

Source code in faststream/kafka/message.py
def __init__(\n    self,\n    *args: Any,\n    consumer: aiokafka.AIOKafkaConsumer,\n    is_manual: bool = False,\n    **kwargs: Any,\n) -> None:\n    super().__init__(*args, **kwargs)\n\n    self.is_manual = is_manual\n    self.consumer = consumer\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.consumer","title":"consumer instance-attribute","text":"
consumer = consumer\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.is_manual","title":"is_manual instance-attribute","text":"
is_manual = is_manual\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.ack","title":"ack async","text":"
ack(**kwargs: Any) -> None\n

Acknowledge the Kafka message.

PARAMETER DESCRIPTION **kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

This method does not return a value.

TYPE: None

Source code in faststream/kafka/message.py
async def ack(self, **kwargs: Any) -> None:\n    \"\"\"\n    Acknowledge the Kafka message.\n\n    Args:\n        **kwargs (Any): Additional keyword arguments.\n\n    Returns:\n        None: This method does not return a value.\n    \"\"\"\n    if self.is_manual and not self.commited:\n        await self.consumer.commit()\n        await super().ack()\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.nack","title":"nack async","text":"
nack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def nack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/kafka/message/KafkaMessage/#faststream.kafka.message.KafkaMessage.reject","title":"reject async","text":"
reject(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def reject(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/","title":"AioKafkaParser","text":"","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/#faststream.kafka.parser.AioKafkaParser","title":"faststream.kafka.parser.AioKafkaParser","text":"","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/#faststream.kafka.parser.AioKafkaParser.decode_message","title":"decode_message async staticmethod","text":"
decode_message(\n    msg: StreamMessage[ConsumerRecord],\n) -> DecodedMessage\n

Decodes a message.

PARAMETER DESCRIPTION msg

The message to be decoded.

TYPE: StreamMessage[ConsumerRecord]

RETURNS DESCRIPTION DecodedMessage

The decoded message.

Source code in faststream/kafka/parser.py
@staticmethod\nasync def decode_message(msg: StreamMessage[ConsumerRecord]) -> DecodedMessage:\n    \"\"\"Decodes a message.\n\n    Args:\n        msg: The message to be decoded.\n\n    Returns:\n        The decoded message.\n\n    \"\"\"\n    return decode_message(msg)\n
","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/#faststream.kafka.parser.AioKafkaParser.decode_message_batch","title":"decode_message_batch async classmethod","text":"
decode_message_batch(\n    msg: StreamMessage[Tuple[ConsumerRecord, ...]]\n) -> List[DecodedMessage]\n

Decode a batch of messages.

PARAMETER DESCRIPTION msg

A stream message containing a tuple of consumer records.

TYPE: StreamMessage[Tuple[ConsumerRecord, ...]]

RETURNS DESCRIPTION List[DecodedMessage]

A list of decoded messages.

Source code in faststream/kafka/parser.py
@classmethod\nasync def decode_message_batch(\n    cls, msg: StreamMessage[Tuple[ConsumerRecord, ...]]\n) -> List[DecodedMessage]:\n    \"\"\"Decode a batch of messages.\n\n    Args:\n        msg: A stream message containing a tuple of consumer records.\n\n    Returns:\n        A list of decoded messages.\n\n    \"\"\"\n    return [decode_message(await cls.parse_message(m)) for m in msg.raw_message]\n
","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/#faststream.kafka.parser.AioKafkaParser.parse_message","title":"parse_message async staticmethod","text":"
parse_message(\n    message: ConsumerRecord,\n) -> StreamMessage[ConsumerRecord]\n

Parses a Kafka message.

PARAMETER DESCRIPTION message

The Kafka message to parse.

TYPE: ConsumerRecord

RETURNS DESCRIPTION StreamMessage[ConsumerRecord]

A StreamMessage object representing the parsed message.

Source code in faststream/kafka/parser.py
@staticmethod\nasync def parse_message(\n    message: ConsumerRecord,\n) -> StreamMessage[ConsumerRecord]:\n    \"\"\"Parses a Kafka message.\n\n    Args:\n        message: The Kafka message to parse.\n\n    Returns:\n        A StreamMessage object representing the parsed message.\n\n    \"\"\"\n    headers = {i: j.decode() for i, j in message.headers}\n    handler = context.get_local(\"handler_\")\n    return KafkaMessage(\n        body=message.value,\n        headers=headers,\n        reply_to=headers.get(\"reply_to\", \"\"),\n        content_type=headers.get(\"content-type\"),\n        message_id=f\"{message.offset}-{message.timestamp}\",\n        correlation_id=headers.get(\"correlation_id\", str(uuid4())),\n        raw_message=message,\n        consumer=handler.consumer,\n        is_manual=handler.is_manual,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/parser/AioKafkaParser/#faststream.kafka.parser.AioKafkaParser.parse_message_batch","title":"parse_message_batch async staticmethod","text":"
parse_message_batch(\n    message: Tuple[ConsumerRecord, ...]\n) -> KafkaMessage\n

Parses a batch of messages from a Kafka consumer.

PARAMETER DESCRIPTION message

A tuple of ConsumerRecord objects representing the messages to parse.

RETURNS DESCRIPTION KafkaMessage

A StreamMessage object containing the parsed messages.

RAISES DESCRIPTION NotImplementedError

If any of the messages are silent (i.e., have no sound).

Static Method

This method is a static method. It does not require an instance of the class to be called.

Source code in faststream/kafka/parser.py
@staticmethod\nasync def parse_message_batch(\n    message: Tuple[ConsumerRecord, ...],\n) -> KafkaMessage:\n    \"\"\"Parses a batch of messages from a Kafka consumer.\n\n    Args:\n        message : A tuple of ConsumerRecord objects representing the messages to parse.\n\n    Returns:\n        A StreamMessage object containing the parsed messages.\n\n    Raises:\n        NotImplementedError: If any of the messages are silent (i.e., have no sound).\n\n    Static Method:\n        This method is a static method. It does not require an instance of the class to be called.\n\n    \"\"\"\n    first = message[0]\n    last = message[-1]\n    headers = {i: j.decode() for i, j in first.headers}\n    handler = context.get_local(\"handler_\")\n    return KafkaMessage(\n        body=[m.value for m in message],\n        headers=headers,\n        reply_to=headers.get(\"reply_to\", \"\"),\n        content_type=headers.get(\"content-type\"),\n        message_id=f\"{first.offset}-{last.offset}-{first.timestamp}\",\n        correlation_id=headers.get(\"correlation_id\", str(uuid4())),\n        raw_message=message,\n        consumer=handler.consumer,\n        is_manual=handler.is_manual,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/producer/AioKafkaFastProducer/","title":"AioKafkaFastProducer","text":"","boost":0.5},{"location":"api/faststream/kafka/producer/AioKafkaFastProducer/#faststream.kafka.producer.AioKafkaFastProducer","title":"faststream.kafka.producer.AioKafkaFastProducer","text":"
AioKafkaFastProducer(producer: AIOKafkaProducer)\n

A class to represent a fast Kafka producer.

METHOD DESCRIPTION publish

Publishes a message to a Kafka topic.

stop

Stops the Kafka producer.

publish_batch

Publishes a batch of messages to a Kafka topic.

Initialize the class.

PARAMETER DESCRIPTION producer

An instance of AIOKafkaProducer.

TYPE: AIOKafkaProducer

Source code in faststream/kafka/producer.py
def __init__(\n    self,\n    producer: AIOKafkaProducer,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        producer: An instance of AIOKafkaProducer.\n\n    \"\"\"\n    self._producer = producer\n
","boost":0.5},{"location":"api/faststream/kafka/producer/AioKafkaFastProducer/#faststream.kafka.producer.AioKafkaFastProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\"\n) -> None\n

Publish a message to a topic.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

topic

The topic to publish the message to.

TYPE: str

key

The key associated with the message.

TYPE: Optional[bytes] DEFAULT: None

partition

The partition to which the message should be sent.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

The timestamp of the message in milliseconds.

TYPE: Optional[int] DEFAULT: None

headers

Additional headers to be included with the message.

TYPE: Optional[Dict[str, str]] DEFAULT: None

correlation_id

The correlation ID of the message.

TYPE: Optional[str] DEFAULT: None

reply_to

The topic to which the reply should be sent.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION AssertionError

If the broker is not connected.

Source code in faststream/kafka/producer.py
async def publish(\n    self,\n    message: SendableMessage,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\",\n) -> None:\n    \"\"\"Publish a message to a topic.\n\n    Args:\n        message: The message to be published.\n        topic: The topic to publish the message to.\n        key: The key associated with the message.\n        partition: The partition to which the message should be sent.\n        timestamp_ms: The timestamp of the message in milliseconds.\n        headers: Additional headers to be included with the message.\n        correlation_id: The correlation ID of the message.\n        reply_to: The topic to which the reply should be sent.\n\n    Returns:\n        None\n\n    Raises:\n        AssertionError: If the broker is not connected.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n\n    message, content_type = encode_message(message)\n\n    headers_to_send = {\n        \"content-type\": content_type or \"\",\n        \"correlation_id\": correlation_id or str(uuid4()),\n        **(headers or {}),\n    }\n\n    if reply_to:\n        headers_to_send.update({\"reply_to\": reply_to})\n\n    await self._producer.send(\n        topic=topic,\n        value=message,\n        key=key,\n        partition=partition,\n        timestamp_ms=timestamp_ms,\n        headers=[(i, (j or \"\").encode()) for i, j in headers_to_send.items()],\n    )\n\n    return None\n
","boost":0.5},{"location":"api/faststream/kafka/producer/AioKafkaFastProducer/#faststream.kafka.producer.AioKafkaFastProducer.publish_batch","title":"publish_batch async","text":"
publish_batch(\n    *msgs: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None\n) -> None\n

Publish a batch of messages to a topic.

PARAMETER DESCRIPTION *msgs

Variable length argument list of messages to be sent.

TYPE: SendableMessage DEFAULT: ()

topic

The topic to which the messages should be published.

TYPE: str

partition

The partition to which the messages should be sent. Defaults to None.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

The timestamp to be associated with the messages. Defaults to None.

TYPE: Optional[int] DEFAULT: None

headers

Additional headers to be included with the messages. Defaults to None.

TYPE: Optional[Dict[str, str]] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION AssertionError

If the broker is not connected.

Source code in faststream/kafka/producer.py
async def publish_batch(\n    self,\n    *msgs: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n) -> None:\n    \"\"\"Publish a batch of messages to a topic.\n\n    Args:\n        *msgs: Variable length argument list of messages to be sent.\n        topic: The topic to which the messages should be published.\n        partition: The partition to which the messages should be sent. Defaults to None.\n        timestamp_ms: The timestamp to be associated with the messages. Defaults to None.\n        headers: Additional headers to be included with the messages. Defaults to None.\n\n    Returns:\n        None\n\n    Raises:\n        AssertionError: If the broker is not connected.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n\n    batch = self._producer.create_batch()\n\n    for msg in msgs:\n        message, content_type = encode_message(msg)\n\n        headers_to_send = {\n            \"content-type\": content_type or \"\",\n            **(headers or {}),\n        }\n\n        batch.append(\n            key=None,\n            value=message,\n            timestamp=timestamp_ms,\n            headers=[(i, j.encode()) for i, j in headers_to_send.items()],\n        )\n\n    await self._producer.send_batch(batch, topic, partition=partition)\n
","boost":0.5},{"location":"api/faststream/kafka/producer/AioKafkaFastProducer/#faststream.kafka.producer.AioKafkaFastProducer.stop","title":"stop async","text":"
stop() -> None\n
Source code in faststream/kafka/producer.py
async def stop(self) -> None:\n    if self._producer is not None:  # pragma: no branch\n        await self._producer.stop()\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/","title":"LogicPublisher","text":"","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher","title":"faststream.kafka.publisher.LogicPublisher dataclass","text":"

Bases: ABCPublisher[ConsumerRecord]

A class to publish messages to a Kafka topic.

METHOD DESCRIPTION publish

Publishes messages to the Kafka topic

RAISES DESCRIPTION AssertionError

If _producer is not set up or if multiple messages are sent without the batch flag

","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = field(default=False)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.client_id","title":"client_id class-attribute instance-attribute","text":"
client_id: str = field(default='faststream-' + __version__)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.key","title":"key class-attribute instance-attribute","text":"
key: Optional[bytes] = None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.partition","title":"partition class-attribute instance-attribute","text":"
partition: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = ''\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.timestamp_ms","title":"timestamp_ms class-attribute instance-attribute","text":"
timestamp_ms: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.topic","title":"topic class-attribute instance-attribute","text":"
topic: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.publish","title":"publish async","text":"
publish(\n    *messages: SendableMessage,\n    message: SendableMessage = \"\",\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None\n) -> None\n

Publish messages to a topic.

PARAMETER DESCRIPTION *messages

Variable length argument list of SendableMessage objects.

TYPE: SendableMessage DEFAULT: ()

message

A SendableMessage object. Default is an empty string.

TYPE: SendableMessage DEFAULT: ''

key

Optional bytes object representing the message key.

TYPE: Optional[bytes] DEFAULT: None

partition

Optional integer representing the partition to publish the message to.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

Optional integer representing the timestamp of the message in milliseconds.

TYPE: Optional[int] DEFAULT: None

headers

Optional dictionary of header key-value pairs.

TYPE: Optional[Dict[str, str]] DEFAULT: None

correlation_id

Optional string representing the correlation ID of the message.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION AssertionError

If _producer is not set up.

AssertionError

If batch flag is not set and there are multiple messages.

ValueError

If message is not a sequence when messages is empty.

Source code in faststream/kafka/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *messages: SendableMessage,\n    message: SendableMessage = \"\",\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n) -> None:\n    \"\"\"Publish messages to a topic.\n\n    Args:\n        *messages: Variable length argument list of SendableMessage objects.\n        message: A SendableMessage object. Default is an empty string.\n        key: Optional bytes object representing the message key.\n        partition: Optional integer representing the partition to publish the message to.\n        timestamp_ms: Optional integer representing the timestamp of the message in milliseconds.\n        headers: Optional dictionary of header key-value pairs.\n        correlation_id: Optional string representing the correlation ID of the message.\n\n    Returns:\n        None\n\n    Raises:\n        AssertionError: If `_producer` is not set up.\n        AssertionError: If `batch` flag is not set and there are multiple messages.\n        ValueError: If `message` is not a sequence when `messages` is empty.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    assert (  # nosec B101\n        self.batch or len(messages) < 2\n    ), \"You can't send multiple messages without `batch` flag\"\n    assert self.topic, \"You have to specify outgoing topic\"  # nosec B101\n\n    if not self.batch:\n        return await self._producer.publish(\n            message=next(iter(messages), message),\n            topic=self.topic,\n            key=key or self.key,\n            partition=partition or self.partition,\n            timestamp_ms=timestamp_ms or self.timestamp_ms,\n            correlation_id=correlation_id,\n            headers=headers or self.headers,\n            reply_to=self.reply_to or \"\",\n        )\n    else:\n        to_send: Sequence[SendableMessage]\n        if not messages:\n            if not isinstance(message, Sequence):\n                raise ValueError(\n                    f\"Message: {message} should be Sequence type to send in batch\"\n                )\n            else:\n                to_send = message\n        else:\n            to_send = messages\n\n        await self._producer.publish_batch(\n            *to_send,\n            topic=self.topic,\n            partition=partition or self.partition,\n            timestamp_ms=timestamp_ms or self.timestamp_ms,\n            headers=headers or self.headers,\n        )\n        return None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/kafka/publisher/LogicPublisher/#faststream.kafka.publisher.LogicPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/","title":"KafkaRouter","text":"","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter","title":"faststream.kafka.router.KafkaRouter","text":"
KafkaRouter(\n    prefix: str = \"\",\n    handlers: Sequence[KafkaRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[aiokafka.ConsumerRecord, KafkaMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[KafkaMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: KafkaRouter

A class to represent a Kafka router.

METHOD DESCRIPTION _get_publisher_key

Get the key for a publisher

_update_publisher_prefix

Update the prefix of a publisher

publisher

Create a new publisher

Source code in faststream/kafka/router.py
        publisher: The publisher object.\n\n    Returns:\n        The publisher key.\n\n    \"\"\"\n    return publisher.topic\n\n@override\n@staticmethod\ndef _update_publisher_prefix(  # type: ignore[override]\n    prefix: str,\n    publisher: Publisher,\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.publisher","title":"publisher","text":"
publisher(\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n

Publishes a message to a topic.

PARAMETER DESCRIPTION topic

The topic to publish the message to.

TYPE: str

key

The key associated with the message.

TYPE: bytes DEFAULT: None

partition

The partition to publish the message to.

TYPE: int DEFAULT: None

timestamp_ms

The timestamp of the message in milliseconds.

TYPE: int DEFAULT: None

headers

Additional headers for the message.

TYPE: Dict[str, str] DEFAULT: None

reply_to

The topic to reply to.

TYPE: str DEFAULT: ''

batch

Whether to publish the message as part of a batch.

TYPE: bool DEFAULT: False

title

The title of the message.

TYPE: str DEFAULT: None

description

The description of the message.

TYPE: str DEFAULT: None

RETURNS DESCRIPTION Publisher

The publisher object used to publish the message.

TYPE: Publisher

Source code in faststream/kafka/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    batch: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"Publishes a message to a topic.\n\n    Args:\n        topic (str): The topic to publish the message to.\n        key (bytes, optional): The key associated with the message.\n        partition (int, optional): The partition to publish the message to.\n        timestamp_ms (int, optional): The timestamp of the message in milliseconds.\n        headers (Dict[str, str], optional): Additional headers for the message.\n        reply_to (str, optional): The topic to reply to.\n        batch (bool, optional): Whether to publish the message as part of a batch.\n        title (str, optional): The title of the message.\n        description (str, optional): The description of the message.\n\n    Returns:\n        Publisher: The publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            topic=topic,\n            key=key,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            batch=batch,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/router/KafkaRouter/#faststream.kafka.router.KafkaRouter.subscriber","title":"subscriber","text":"
subscriber(\n    *topics: str,\n    group_id: Optional[str] = None,\n    key_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    value_deserializer: Optional[\n        Callable[[bytes], Any]\n    ] = None,\n    fetch_max_wait_ms: int = 500,\n    fetch_max_bytes: int = 52428800,\n    fetch_min_bytes: int = 1,\n    max_partition_fetch_bytes: int = 1 * 1024 * 1024,\n    auto_offset_reset: Literal[\n        \"latest\", \"earliest\", \"none\"\n    ] = \"latest\",\n    auto_commit: bool = True,\n    auto_commit_interval_ms: int = 5000,\n    check_crcs: bool = True,\n    partition_assignment_strategy: Sequence[\n        AbstractPartitionAssignor\n    ] = (RoundRobinPartitionAssignor),\n    max_poll_interval_ms: int = 300000,\n    rebalance_timeout_ms: Optional[int] = None,\n    session_timeout_ms: int = 10000,\n    heartbeat_interval_ms: int = 3000,\n    consumer_timeout_ms: int = 200,\n    max_poll_records: Optional[int] = None,\n    exclude_internal_topics: bool = True,\n    isolation_level: Literal[\n        \"read_uncommitted\", \"read_committed\"\n    ] = \"read_uncommitted\",\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[aiokafka.ConsumerRecord, KafkaMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[KafkaMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aiokafka.ConsumerRecord], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Filter[KafkaMessage] = default_filter,\n    batch: bool = False,\n    max_records: Optional[int] = None,\n    batch_timeout_ms: int = 200,\n    retry: Union[bool, int] = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aiokafka.ConsumerRecord,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n
Source code in faststream/kafka/router.py
    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    \"\"\"Publishes a message to a topic.\n\n    Args:\n        topic (str): The topic to publish the message to.\n        key (bytes, optional): The key associated with the message.\n        partition (int, optional): The partition to publish the message to.\n        timestamp_ms (int, optional): The timestamp of the message in milliseconds.\n        headers (Dict[str, str], optional): Additional headers for the message.\n        reply_to (str, optional): The topic to reply to.\n        batch (bool, optional): Whether to publish the message as part of a batch.\n        title (str, optional): The title of the message.\n        description (str, optional): The description of the message.\n\n    Returns:\n        Publisher: The publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            topic=topic,\n            key=key,\n            partition=partition,\n            timestamp_ms=timestamp_ms,\n            headers=headers,\n            reply_to=reply_to,\n            title=title,\n            batch=batch,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/kafka/security/parse_security/","title":"parse_security","text":"","boost":0.5},{"location":"api/faststream/kafka/security/parse_security/#faststream.kafka.security.parse_security","title":"faststream.kafka.security.parse_security","text":"
parse_security(security: Optional[BaseSecurity]) -> AnyDict\n
Source code in faststream/kafka/security.py
def parse_security(security: Optional[BaseSecurity]) -> AnyDict:\n    if security is None:\n        return {}\n    elif type(security) == BaseSecurity:\n        return _parse_base_security(security)\n    elif type(security) == SASLPlaintext:\n        return _parse_sasl_plaintext(security)\n    elif type(security) == SASLScram256:\n        return _parse_sasl_scram256(security)\n    elif type(security) == SASLScram512:\n        return _parse_sasl_scram512(security)\n    else:\n        raise NotImplementedError(f\"KafkaBroker does not support {type(security)}\")\n
","boost":0.5},{"location":"api/faststream/kafka/shared/logging/KafkaLoggingMixin/","title":"KafkaLoggingMixin","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/logging/KafkaLoggingMixin/#faststream.kafka.shared.logging.KafkaLoggingMixin","title":"faststream.kafka.shared.logging.KafkaLoggingMixin","text":"
KafkaLoggingMixin(\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any\n)\n

Bases: LoggingMixin

A class that provides logging functionality for Kafka.

METHOD DESCRIPTION __init__

initializes the KafkaLoggingMixin object

_get_log_context

returns the log context for a given message and topics

fmt

returns the log format string

_setup_log_context

sets up the log context for a given list of topics

Initialize the class.

PARAMETER DESCRIPTION *args

Variable length argument list

TYPE: Any DEFAULT: ()

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: access_logger

log_level

Log level (default: logging.INFO)

TYPE: int DEFAULT: INFO

log_fmt

Optional log format string

TYPE: Optional[str] DEFAULT: None

**kwargs

Arbitrary keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None

Source code in faststream/kafka/shared/logging.py
def __init__(\n    self,\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        *args: Variable length argument list\n        logger: Optional logger object\n        log_level: Log level (default: logging.INFO)\n        log_fmt: Optional log format string\n        **kwargs: Arbitrary keyword arguments\n\n    Returns:\n        None\n\n    \"\"\"\n    super().__init__(\n        *args,\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n        **kwargs,\n    )\n    self._max_topic_len = 4\n    self._max_group_len = 0\n
","boost":0.5},{"location":"api/faststream/kafka/shared/logging/KafkaLoggingMixin/#faststream.kafka.shared.logging.KafkaLoggingMixin.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/logging/KafkaLoggingMixin/#faststream.kafka.shared.logging.KafkaLoggingMixin.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/kafka/shared/logging/KafkaLoggingMixin/#faststream.kafka.shared.logging.KafkaLoggingMixin.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/","title":"ABCPublisher","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher","title":"faststream.kafka.shared.publisher.ABCPublisher dataclass","text":"

Bases: ABC, BasePublisher[MsgType]

A class representing an ABCPublisher.

","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = None\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.key","title":"key class-attribute instance-attribute","text":"
key: Optional[bytes] = None\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.partition","title":"partition class-attribute instance-attribute","text":"
partition: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = ''\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.timestamp_ms","title":"timestamp_ms class-attribute instance-attribute","text":"
timestamp_ms: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.topic","title":"topic class-attribute instance-attribute","text":"
topic: str = ''\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.publish","title":"publish abstractmethod async","text":"
publish(\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

correlation_id

Optional correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/publisher.py
@abstractmethod\nasync def publish(\n    self,\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        correlation_id: Optional correlation ID for the message.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/kafka/shared/publisher/ABCPublisher/#faststream.kafka.shared.publisher.ABCPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/","title":"BrokerRouter","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter","title":"faststream.broker.router.BrokerRouter","text":"
BrokerRouter(\n    prefix: str = \"\",\n    handlers: Sequence[\n        BrokerRoute[MsgType, SendableMessage]\n    ] = (),\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    include_in_schema: Optional[bool] = None,\n)\n

Bases: Generic[PublisherKeyType, MsgType]

A generic class representing a broker router.

METHOD DESCRIPTION _get_publisher_key

abstract method to get the publisher key

_update_publisher_prefix

abstract method to update the publisher prefix

__init__

constructor method

subscriber

abstract method to define a subscriber

_wrap_subscriber

method to wrap a subscriber function

publisher

abstract method to define a publisher

include_router

method to include a router

include_routers

method to include multiple routers

Initialize a class object.

PARAMETER DESCRIPTION prefix

Prefix for the object.

TYPE: str DEFAULT: ''

handlers

Handlers for the object.

TYPE: Sequence[BrokerRoute[MsgType, SendableMessage]] DEFAULT: ()

dependencies

Dependencies for the object.

TYPE: Sequence[Depends] DEFAULT: ()

middlewares

Middlewares for the object.

TYPE: Optional[Sequence[Callable[[StreamMessage[MsgType]], AsyncContextManager[None]]]] DEFAULT: None

parser

Parser for the object.

TYPE: Optional[CustomParser[MsgType]] DEFAULT: None

decoder

Decoder for the object.

TYPE: Optional[CustomDecoder[StreamMessage[MsgType]]] DEFAULT: None

Source code in faststream/broker/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[BrokerRoute[MsgType, SendableMessage]] = (),\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    include_in_schema: Optional[bool] = None,\n) -> None:\n    \"\"\"Initialize a class object.\n\n    Args:\n        prefix (str): Prefix for the object.\n        handlers (Sequence[BrokerRoute[MsgType, SendableMessage]]): Handlers for the object.\n        dependencies (Sequence[Depends]): Dependencies for the object.\n        middlewares (Optional[Sequence[Callable[[StreamMessage[MsgType]], AsyncContextManager[None]]]]): Middlewares for the object.\n        parser (Optional[CustomParser[MsgType]]): Parser for the object.\n        decoder (Optional[CustomDecoder[StreamMessage[MsgType]]]): Decoder for the object.\n\n    \"\"\"\n    self.prefix = prefix\n    self.include_in_schema = include_in_schema\n    self._handlers = list(handlers)\n    self._publishers = {}\n    self._dependencies = dependencies\n    self._middlewares = middlewares\n    self._parser = parser\n    self._decoder = decoder\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/BrokerRouter/#faststream.broker.router.BrokerRouter.subscriber","title":"subscriber abstractmethod","text":"
subscriber(\n    subj: str,\n    *args: Any,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[MsgType, StreamMessage[MsgType]]\n    ] = None,\n    decoder: Optional[\n        CustomDecoder[StreamMessage[MsgType]]\n    ] = None,\n    include_in_schema: Optional[bool] = None,\n    **kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        MsgType, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function to subscribe to a subject.

PARAMETER DESCRIPTION subj

subject to subscribe to

*args

additional arguments

DEFAULT: ()

dependencies

sequence of dependencies

DEFAULT: ()

middlewares

optional sequence of middlewares

DEFAULT: None

parser

optional custom parser

DEFAULT: None

decoder

optional custom decoder

DEFAULT: None

**kwargs

additional keyword arguments

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]]

A callable handler function

RAISES DESCRIPTION NotImplementedError

If the function is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef subscriber(\n    self,\n    subj: str,\n    *args: Any,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [StreamMessage[MsgType]],\n                AsyncContextManager[None],\n            ]\n        ]\n    ] = None,\n    parser: Optional[CustomParser[MsgType, StreamMessage[MsgType]]] = None,\n    decoder: Optional[CustomDecoder[StreamMessage[MsgType]]] = None,\n    include_in_schema: Optional[bool] = None,\n    **kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function to subscribe to a subject.\n\n    Args:\n        subj : subject to subscribe to\n        *args : additional arguments\n        dependencies : sequence of dependencies\n        middlewares : optional sequence of middlewares\n        parser : optional custom parser\n        decoder : optional custom decoder\n        **kwargs : additional keyword arguments\n\n    Returns:\n        A callable handler function\n\n    Raises:\n        NotImplementedError: If the function is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRoute/","title":"KafkaRoute","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/","title":"KafkaRouter","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter","title":"faststream.kafka.shared.router.KafkaRouter","text":"
KafkaRouter(\n    prefix: str = \"\",\n    handlers: Sequence[\n        KafkaRoute[ConsumerRecord, SendableMessage]\n    ] = (),\n    **kwargs: Any\n)\n

Bases: BrokerRouter[str, ConsumerRecord]

A class to represent a Kafka router.

METHOD DESCRIPTION subscriber

decorator for subscribing to topics and handling messages

Initialize the class.

PARAMETER DESCRIPTION prefix

Prefix string.

TYPE: str DEFAULT: ''

handlers

Sequence of KafkaRoute objects.

TYPE: Sequence[BrokerRoute[ConsumerRecord, SendableMessage]] DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/kafka/shared/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[KafkaRoute[ConsumerRecord, SendableMessage]] = (),\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        prefix (str): Prefix string.\n        handlers (Sequence[KafkaRoute[ConsumerRecord, SendableMessage]]): Sequence of KafkaRoute objects.\n        **kwargs (Any): Additional keyword arguments.\n\n    \"\"\"\n    for h in handlers:\n        h.args = tuple(prefix + x for x in h.args)\n    super().__init__(prefix, handlers, **kwargs)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/kafka/shared/router/KafkaRouter/#faststream.kafka.shared.router.KafkaRouter.subscriber","title":"subscriber","text":"
subscriber(\n    *topics: str, **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        ConsumerRecord, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function to subscribe to topics.

PARAMETER DESCRIPTION *topics

variable number of topic names

DEFAULT: ()

**broker_kwargs

keyword arguments for the broker

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn]]

A callable function that wraps the handler function

Source code in faststream/kafka/shared/router.py
def subscriber(\n    self,\n    *topics: str,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[ConsumerRecord, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function to subscribe to topics.\n\n    Args:\n        *topics : variable number of topic names\n        **broker_kwargs : keyword arguments for the broker\n\n    Returns:\n        A callable function that wraps the handler function\n\n    \"\"\"\n    return self._wrap_subscriber(\n        *(self.prefix + x for x in topics),\n        **broker_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/","title":"ConsumerConnectionParams","text":"","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams","title":"faststream.kafka.shared.schemas.ConsumerConnectionParams","text":"

Bases: TypedDict

A class to represent the connection parameters for a consumer.

","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.api_version","title":"api_version instance-attribute","text":"
api_version: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.bootstrap_servers","title":"bootstrap_servers instance-attribute","text":"
bootstrap_servers: Required[Union[str, List[str]]]\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.client_id","title":"client_id instance-attribute","text":"
client_id: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.connections_max_idle_ms","title":"connections_max_idle_ms instance-attribute","text":"
connections_max_idle_ms: int\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.loop","title":"loop instance-attribute","text":"
loop: Optional[AbstractEventLoop]\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.metadata_max_age_ms","title":"metadata_max_age_ms instance-attribute","text":"
metadata_max_age_ms: int\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.request_timeout_ms","title":"request_timeout_ms instance-attribute","text":"
request_timeout_ms: int\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.retry_backoff_ms","title":"retry_backoff_ms instance-attribute","text":"
retry_backoff_ms: int\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_kerberos_domain_name","title":"sasl_kerberos_domain_name instance-attribute","text":"
sasl_kerberos_domain_name: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_kerberos_service_name","title":"sasl_kerberos_service_name instance-attribute","text":"
sasl_kerberos_service_name: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_mechanism","title":"sasl_mechanism instance-attribute","text":"
sasl_mechanism: Literal[\n    \"PLAIN\",\n    \"GSSAPI\",\n    \"SCRAM-SHA-256\",\n    \"SCRAM-SHA-512\",\n    \"OAUTHBEARER\",\n]\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_oauth_token_provider","title":"sasl_oauth_token_provider instance-attribute","text":"
sasl_oauth_token_provider: AbstractTokenProvider\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_plain_password","title":"sasl_plain_password instance-attribute","text":"
sasl_plain_password: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.sasl_plain_username","title":"sasl_plain_username instance-attribute","text":"
sasl_plain_username: str\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.security_protocol","title":"security_protocol instance-attribute","text":"
security_protocol: Literal['SSL', 'PLAINTEXT']\n
","boost":0.5},{"location":"api/faststream/kafka/shared/schemas/ConsumerConnectionParams/#faststream.kafka.shared.schemas.ConsumerConnectionParams.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context: ssl.SSLContext\n
","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/","title":"FakeProducer","text":"","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/#faststream.kafka.test.FakeProducer","title":"faststream.kafka.test.FakeProducer","text":"
FakeProducer(broker: KafkaBroker)\n

Bases: AioKafkaFastProducer

A fake Kafka producer for testing purposes.

This class extends AioKafkaFastProducer and is used to simulate Kafka message publishing during tests.

Initialize the FakeProducer.

PARAMETER DESCRIPTION broker

The KafkaBroker instance to associate with this FakeProducer.

TYPE: KafkaBroker

Source code in faststream/kafka/test.py
def __init__(self, broker: KafkaBroker) -> None:\n    \"\"\"\n    Initialize the FakeProducer.\n\n    Args:\n        broker (KafkaBroker): The KafkaBroker instance to associate with this FakeProducer.\n    \"\"\"\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/#faststream.kafka.test.FakeProducer.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/#faststream.kafka.test.FakeProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\",\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False\n) -> Optional[SendableMessage]\n

Publish a message to the Kafka broker.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

topic

The Kafka topic to publish the message to.

TYPE: str

key

The message key. Defaults to None.

TYPE: Optional[bytes] DEFAULT: None

partition

The Kafka partition to use. Defaults to None.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

The message timestamp in milliseconds. Defaults to None.

TYPE: Optional[int] DEFAULT: None

headers

Additional headers for the message. Defaults to None.

TYPE: Optional[Dict[str, str]] DEFAULT: None

correlation_id

The correlation ID for the message. Defaults to None.

TYPE: Optional[str] DEFAULT: None

reply_to

The topic to which responses should be sent. Defaults to \"\".

TYPE: str DEFAULT: ''

rpc

If True, treat the message as an RPC request. Defaults to False.

TYPE: bool DEFAULT: False

rpc_timeout

Timeout for RPC requests. Defaults to None.

TYPE: Optional[float] DEFAULT: None

raise_timeout

If True, raise an exception on timeout. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION Optional[SendableMessage]

Optional[SendableMessage]: The response message, if this was an RPC request, otherwise None.

Source code in faststream/kafka/test.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage,\n    topic: str,\n    key: Optional[bytes] = None,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\",\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False,\n) -> Optional[SendableMessage]:\n    \"\"\"\n    Publish a message to the Kafka broker.\n\n    Args:\n        message (SendableMessage): The message to be published.\n        topic (str): The Kafka topic to publish the message to.\n        key (Optional[bytes], optional): The message key. Defaults to None.\n        partition (Optional[int], optional): The Kafka partition to use. Defaults to None.\n        timestamp_ms (Optional[int], optional): The message timestamp in milliseconds. Defaults to None.\n        headers (Optional[Dict[str, str]], optional): Additional headers for the message. Defaults to None.\n        correlation_id (Optional[str], optional): The correlation ID for the message. Defaults to None.\n        reply_to (str, optional): The topic to which responses should be sent. Defaults to \"\".\n        rpc (bool, optional): If True, treat the message as an RPC request. Defaults to False.\n        rpc_timeout (Optional[float], optional): Timeout for RPC requests. Defaults to None.\n        raise_timeout (bool, optional): If True, raise an exception on timeout. Defaults to False.\n\n    Returns:\n        Optional[SendableMessage]: The response message, if this was an RPC request, otherwise None.\n    \"\"\"\n    incoming = build_message(\n        message=message,\n        topic=topic,\n        key=key,\n        partition=partition,\n        timestamp_ms=timestamp_ms,\n        headers=headers,\n        correlation_id=correlation_id,\n        reply_to=reply_to,\n    )\n\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        if topic in handler.topics:\n            return await call_handler(\n                handler=handler,\n                message=[incoming] if handler.batch else incoming,\n                rpc=rpc,\n                rpc_timeout=rpc_timeout,\n                raise_timeout=raise_timeout,\n            )\n\n    return None\n
","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/#faststream.kafka.test.FakeProducer.publish_batch","title":"publish_batch async","text":"
publish_batch(\n    *msgs: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None\n) -> None\n

Publish a batch of messages to the Kafka broker.

PARAMETER DESCRIPTION *msgs

Variable number of messages to be published.

TYPE: SendableMessage DEFAULT: ()

topic

The Kafka topic to publish the messages to.

TYPE: str

partition

The Kafka partition to use. Defaults to None.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

The message timestamp in milliseconds. Defaults to None.

TYPE: Optional[int] DEFAULT: None

headers

Additional headers for the messages. Defaults to None.

TYPE: Optional[Dict[str, str]] DEFAULT: None

RETURNS DESCRIPTION None

This method does not return a value.

TYPE: None

Source code in faststream/kafka/test.py
async def publish_batch(\n    self,\n    *msgs: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    headers: Optional[Dict[str, str]] = None,\n) -> None:\n    \"\"\"\n    Publish a batch of messages to the Kafka broker.\n\n    Args:\n        *msgs (SendableMessage): Variable number of messages to be published.\n        topic (str): The Kafka topic to publish the messages to.\n        partition (Optional[int], optional): The Kafka partition to use. Defaults to None.\n        timestamp_ms (Optional[int], optional): The message timestamp in milliseconds. Defaults to None.\n        headers (Optional[Dict[str, str]], optional): Additional headers for the messages. Defaults to None.\n\n    Returns:\n        None: This method does not return a value.\n    \"\"\"\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        if topic in handler.topics:\n            await call_handler(\n                handler=handler,\n                message=[\n                    build_message(\n                        message=message,\n                        topic=topic,\n                        partition=partition,\n                        timestamp_ms=timestamp_ms,\n                        headers=headers,\n                    )\n                    for message in msgs\n                ],\n            )\n\n    return None\n
","boost":0.5},{"location":"api/faststream/kafka/test/FakeProducer/#faststream.kafka.test.FakeProducer.stop","title":"stop async","text":"
stop() -> None\n
Source code in faststream/kafka/producer.py
async def stop(self) -> None:\n    if self._producer is not None:  # pragma: no branch\n        await self._producer.stop()\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/","title":"TestKafkaBroker","text":"","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker","title":"faststream.kafka.test.TestKafkaBroker","text":"
TestKafkaBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[KafkaBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/kafka/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: KafkaBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(  # type: ignore[call-overload,misc]\n        publisher.topic,\n        batch=publisher.batch,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f  # type: ignore[no-any-return]\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: KafkaBroker, publisher: Any\n) -> None\n
Source code in faststream/kafka/test.py
@staticmethod\ndef patch_publisher(broker: KafkaBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/kafka/test/TestKafkaBroker/#faststream.kafka.test.TestKafkaBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> None\n
Source code in faststream/kafka/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: KafkaBroker, publisher: Publisher\n) -> None:\n    broker.handlers.pop(publisher.topic, None)\n
","boost":0.5},{"location":"api/faststream/kafka/test/build_message/","title":"build_message","text":"","boost":0.5},{"location":"api/faststream/kafka/test/build_message/#faststream.kafka.test.build_message","title":"faststream.kafka.test.build_message","text":"
build_message(\n    message: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    key: Optional[bytes] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\"\n) -> ConsumerRecord\n

Build a Kafka ConsumerRecord for a sendable message.

PARAMETER DESCRIPTION message

The sendable message to be encoded.

TYPE: SendableMessage

topic

The Kafka topic for the message.

TYPE: str

partition

The Kafka partition for the message. Defaults to None.

TYPE: Optional[int] DEFAULT: None

timestamp_ms

The message timestamp in milliseconds. Defaults to None.

TYPE: Optional[int] DEFAULT: None

key

The message key. Defaults to None.

TYPE: Optional[bytes] DEFAULT: None

headers

Additional headers for the message. Defaults to None.

TYPE: Optional[Dict[str, str]] DEFAULT: None

correlation_id

The correlation ID for the message. Defaults to None.

TYPE: Optional[str] DEFAULT: None

reply_to

The topic to which responses should be sent. Defaults to \"\".

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION ConsumerRecord

A Kafka ConsumerRecord object.

TYPE: ConsumerRecord

Source code in faststream/kafka/test.py
def build_message(\n    message: SendableMessage,\n    topic: str,\n    partition: Optional[int] = None,\n    timestamp_ms: Optional[int] = None,\n    key: Optional[bytes] = None,\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    reply_to: str = \"\",\n) -> ConsumerRecord:\n    \"\"\"\n    Build a Kafka ConsumerRecord for a sendable message.\n\n    Args:\n        message (SendableMessage): The sendable message to be encoded.\n        topic (str): The Kafka topic for the message.\n        partition (Optional[int], optional): The Kafka partition for the message. Defaults to None.\n        timestamp_ms (Optional[int], optional): The message timestamp in milliseconds. Defaults to None.\n        key (Optional[bytes], optional): The message key. Defaults to None.\n        headers (Optional[Dict[str, str]], optional): Additional headers for the message. Defaults to None.\n        correlation_id (Optional[str], optional): The correlation ID for the message. Defaults to None.\n        reply_to (str, optional): The topic to which responses should be sent. Defaults to \"\".\n\n    Returns:\n        ConsumerRecord: A Kafka ConsumerRecord object.\n    \"\"\"\n    msg, content_type = encode_message(message)\n    k = key or b\"\"\n    headers = {\n        \"content-type\": content_type or \"\",\n        \"correlation_id\": correlation_id or str(uuid4()),\n        \"reply_to\": reply_to,\n        **(headers or {}),\n    }\n\n    return ConsumerRecord(\n        value=msg,\n        topic=topic,\n        partition=partition or 0,\n        timestamp=timestamp_ms or int(datetime.now().timestamp()),\n        timestamp_type=0,\n        key=k,\n        serialized_key_size=len(k),\n        serialized_value_size=len(msg),\n        checksum=sum(msg),\n        offset=0,\n        headers=[(i, j.encode()) for i, j in headers.items()],\n    )\n
","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/","title":"ColourizedFormatter","text":"","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/#faststream.log.formatter.ColourizedFormatter","title":"faststream.log.formatter.ColourizedFormatter","text":"
ColourizedFormatter(\n    fmt: Optional[str] = None,\n    datefmt: Optional[str] = None,\n    style: Literal[\"%\", \"{\", \"$\"] = \"%\",\n    use_colors: Optional[bool] = None,\n)\n

Bases: Formatter

A class to format log messages with colorized level names.

METHOD DESCRIPTION __init__

Initialize the formatter with specified format strings.

color_level_name

Colorize the level name based on the log level.

formatMessage

Format the log record message with colorized level name.

Initialize the formatter with specified format strings.

Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.

Use a style parameter of '%', '{' or '$' to specify that you want to use one of %-formatting, :meth:str.format ({}) formatting or :class:string.Template formatting in your format string.

Source code in faststream/log/formatter.py
def __init__(\n    self,\n    fmt: Optional[str] = None,\n    datefmt: Optional[str] = None,\n    style: Literal[\"%\", \"{\", \"$\"] = \"%\",\n    use_colors: Optional[bool] = None,\n) -> None:\n    \"\"\"\n    Initialize the formatter with specified format strings.\n\n    Initialize the formatter either with the specified format string, or a\n    default as described above. Allow for specialized date formatting with\n    the optional datefmt argument. If datefmt is omitted, you get an\n    ISO8601-like (or RFC 3339-like) format.\n\n    Use a style parameter of '%', '{' or '$' to specify that you want to\n    use one of %-formatting, :meth:`str.format` (``{}``) formatting or\n    :class:`string.Template` formatting in your format string.\n    \"\"\"\n    if use_colors in (True, False):\n        self.use_colors = use_colors\n    else:\n        self.use_colors = sys.stdout.isatty()\n    super().__init__(fmt=fmt, datefmt=datefmt, style=style)\n
","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/#faststream.log.formatter.ColourizedFormatter.level_name_colors","title":"level_name_colors class-attribute instance-attribute","text":"
level_name_colors: DefaultDict[\n    str, Callable[[str], str]\n] = defaultdict(\n    lambda: str,\n    **{\n        str(logging.DEBUG): lambda: click.style(\n            str(level_name), fg=\"cyan\"\n        ),\n        str(logging.INFO): lambda: click.style(\n            str(level_name), fg=\"green\"\n        ),\n        str(logging.WARNING): lambda: click.style(\n            str(level_name), fg=\"yellow\"\n        ),\n        str(logging.ERROR): lambda: click.style(\n            str(level_name), fg=\"red\"\n        ),\n        str(logging.CRITICAL): lambda: click.style(\n            str(level_name), fg=\"bright_red\"\n        ),\n    }\n)\n
","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/#faststream.log.formatter.ColourizedFormatter.use_colors","title":"use_colors instance-attribute","text":"
use_colors = use_colors\n
","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/#faststream.log.formatter.ColourizedFormatter.color_level_name","title":"color_level_name","text":"
color_level_name(level_name: str, level_no: int) -> str\n

Returns the colored level name.

PARAMETER DESCRIPTION level_name

The name of the level.

TYPE: str

level_no

The number of the level.

TYPE: int

RETURNS DESCRIPTION str

The colored level name.

RAISES DESCRIPTION KeyError

If the level number is not found in the level name colors dictionary.

Source code in faststream/log/formatter.py
def color_level_name(self, level_name: str, level_no: int) -> str:\n    \"\"\"Returns the colored level name.\n\n    Args:\n        level_name: The name of the level.\n        level_no: The number of the level.\n\n    Returns:\n        The colored level name.\n\n    Raises:\n        KeyError: If the level number is not found in the level name colors dictionary.\n\n    \"\"\"\n    return self.level_name_colors[str(level_no)](level_name)\n
","boost":0.5},{"location":"api/faststream/log/formatter/ColourizedFormatter/#faststream.log.formatter.ColourizedFormatter.formatMessage","title":"formatMessage","text":"
formatMessage(record: logging.LogRecord) -> str\n

Formats the log message.

PARAMETER DESCRIPTION record

The log record to format.

TYPE: LogRecord

RETURNS DESCRIPTION str

The formatted log message.

TYPE: str

Source code in faststream/log/formatter.py
def formatMessage(self, record: logging.LogRecord) -> str:\n    \"\"\"Formats the log message.\n\n    Args:\n        record (logging.LogRecord): The log record to format.\n\n    Returns:\n        str: The formatted log message.\n\n    \"\"\"\n    levelname = expand_log_field(record.levelname, 8)\n    if self.use_colors is True:  # pragma: no cover\n        levelname = self.color_level_name(levelname, record.levelno)\n    record.__dict__[\"levelname\"] = levelname\n    return super().formatMessage(record)\n
","boost":0.5},{"location":"api/faststream/log/formatter/expand_log_field/","title":"expand_log_field","text":"","boost":0.5},{"location":"api/faststream/log/formatter/expand_log_field/#faststream.log.formatter.expand_log_field","title":"faststream.log.formatter.expand_log_field","text":"
expand_log_field(field: str, symbols: int) -> str\n

Expands a log field by adding spaces.

PARAMETER DESCRIPTION field

The log field to expand.

TYPE: str

symbols

The desired length of the expanded field.

TYPE: int

RETURNS DESCRIPTION str

The expanded log field.

Source code in faststream/log/formatter.py
def expand_log_field(field: str, symbols: int) -> str:\n    \"\"\"Expands a log field by adding spaces.\n\n    Args:\n        field: The log field to expand.\n        symbols: The desired length of the expanded field.\n\n    Returns:\n        The expanded log field.\n\n    \"\"\"\n    return field + (\" \" * (symbols - len(field)))\n
","boost":0.5},{"location":"api/faststream/log/formatter/make_record_with_extra/","title":"make_record_with_extra","text":"","boost":0.5},{"location":"api/faststream/log/formatter/make_record_with_extra/#faststream.log.formatter.make_record_with_extra","title":"faststream.log.formatter.make_record_with_extra","text":"
make_record_with_extra(\n    self: logging.Logger,\n    name: str,\n    level: int,\n    fn: str,\n    lno: int,\n    msg: str,\n    args: Tuple[str],\n    exc_info: Optional[\n        Union[\n            Tuple[\n                Type[BaseException],\n                BaseException,\n                Optional[TracebackType],\n            ],\n            Tuple[None, None, None],\n        ]\n    ],\n    func: Optional[str] = None,\n    extra: Optional[Mapping[str, object]] = None,\n    sinfo: Optional[str] = None,\n) -> logging.LogRecord\n

Creates a log record with additional information.

PARAMETER DESCRIPTION self

The logger object.

TYPE: Logger

name

The name of the logger.

TYPE: str

level

The logging level.

TYPE: int

fn

The filename where the log message originated.

TYPE: str

lno

The line number where the log message originated.

TYPE: int

msg

The log message.

TYPE: str

args

The arguments for the log message.

TYPE: Tuple[str]

exc_info

Information about an exception.

TYPE: Optional[Union[Tuple[Type[BaseException], BaseException, Optional[TracebackType]], Tuple[None, None, None]]]

func

The name of the function where the log message originated.

TYPE: Optional[str] DEFAULT: None

extra

Additional information to include in the log record.

TYPE: Optional[Mapping[str, object]] DEFAULT: None

sinfo

Stack information.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION LogRecord

The log record.

Note

If extra is None, it will be set to the value of context.get_local(\"log_context\").

Source code in faststream/log/formatter.py
def make_record_with_extra(\n    self: logging.Logger,\n    name: str,\n    level: int,\n    fn: str,\n    lno: int,\n    msg: str,\n    args: Tuple[str],\n    exc_info: Optional[\n        Union[\n            Tuple[Type[BaseException], BaseException, Optional[TracebackType]],\n            Tuple[None, None, None],\n        ]\n    ],\n    func: Optional[str] = None,\n    extra: Optional[Mapping[str, object]] = None,\n    sinfo: Optional[str] = None,\n) -> logging.LogRecord:\n    \"\"\"Creates a log record with additional information.\n\n    Args:\n        self: The logger object.\n        name: The name of the logger.\n        level: The logging level.\n        fn: The filename where the log message originated.\n        lno: The line number where the log message originated.\n        msg: The log message.\n        args: The arguments for the log message.\n        exc_info: Information about an exception.\n        func: The name of the function where the log message originated.\n        extra: Additional information to include in the log record.\n        sinfo: Stack information.\n\n    Returns:\n        The log record.\n\n    Note:\n        If `extra` is `None`, it will be set to the value of `context.get_local(\"log_context\")`.\n\n    \"\"\"\n    if extra is None:\n        extra = context.get_local(\n            \"log_context\", default=context.get(\"default_log_context\")\n        )\n\n    record = original_makeRecord(\n        self,\n        name,\n        level,\n        fn,\n        lno,\n        msg,\n        args,\n        exc_info,\n        func,\n        extra,\n        sinfo,\n    )\n\n    return record\n
","boost":0.5},{"location":"api/faststream/log/logging/configure_formatter/","title":"configure_formatter","text":"","boost":0.5},{"location":"api/faststream/log/logging/configure_formatter/#faststream.log.logging.configure_formatter","title":"faststream.log.logging.configure_formatter","text":"
configure_formatter(\n    formatter: Type[logging.Formatter],\n    *args: Any,\n    **kwargs: Any\n) -> logging.Formatter\n

Configures a logging formatter.

PARAMETER DESCRIPTION formatter

The type of logging formatter to configure.

TYPE: Type[Formatter]

*args

Additional positional arguments to pass to the formatter constructor.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments to pass to the formatter constructor.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Formatter

An instance of the configured logging formatter.

Source code in faststream/log/logging.py
def configure_formatter(\n    formatter: Type[logging.Formatter], *args: Any, **kwargs: Any\n) -> logging.Formatter:\n    \"\"\"Configures a logging formatter.\n\n    Args:\n        formatter: The type of logging formatter to configure.\n        *args: Additional positional arguments to pass to the formatter constructor.\n        **kwargs: Additional keyword arguments to pass to the formatter constructor.\n\n    Returns:\n        An instance of the configured logging formatter.\n\n    \"\"\"\n    return formatter(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/nats/AckPolicy/","title":"AckPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/AckPolicy/#nats.js.api.AckPolicy","title":"nats.js.api.AckPolicy","text":"

Bases: str, Enum

Policies defining how messages should be acknowledged.

If an ack is required but is not received within the AckWait window, the message will be redelivered.

References ","boost":0.5},{"location":"api/faststream/nats/AckPolicy/#nats.js.api.AckPolicy.ALL","title":"ALL class-attribute instance-attribute","text":"
ALL = 'all'\n
","boost":0.5},{"location":"api/faststream/nats/AckPolicy/#nats.js.api.AckPolicy.EXPLICIT","title":"EXPLICIT class-attribute instance-attribute","text":"
EXPLICIT = 'explicit'\n
","boost":0.5},{"location":"api/faststream/nats/AckPolicy/#nats.js.api.AckPolicy.NONE","title":"NONE class-attribute instance-attribute","text":"
NONE = 'none'\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/","title":"ConsumerConfig","text":"","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig","title":"nats.js.api.ConsumerConfig dataclass","text":"

Bases: Base

Consumer configuration.

References ","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.ack_policy","title":"ack_policy class-attribute instance-attribute","text":"
ack_policy: Optional[AckPolicy] = AckPolicy.EXPLICIT\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.ack_wait","title":"ack_wait class-attribute instance-attribute","text":"
ack_wait: Optional[float] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.deliver_group","title":"deliver_group class-attribute instance-attribute","text":"
deliver_group: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.deliver_policy","title":"deliver_policy class-attribute instance-attribute","text":"
deliver_policy: Optional[DeliverPolicy] = DeliverPolicy.ALL\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.deliver_subject","title":"deliver_subject class-attribute instance-attribute","text":"
deliver_subject: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.durable_name","title":"durable_name class-attribute instance-attribute","text":"
durable_name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.filter_subject","title":"filter_subject class-attribute instance-attribute","text":"
filter_subject: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.flow_control","title":"flow_control class-attribute instance-attribute","text":"
flow_control: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.headers_only","title":"headers_only class-attribute instance-attribute","text":"
headers_only: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.idle_heartbeat","title":"idle_heartbeat class-attribute instance-attribute","text":"
idle_heartbeat: Optional[float] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.inactive_threshold","title":"inactive_threshold class-attribute instance-attribute","text":"
inactive_threshold: Optional[float] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.max_ack_pending","title":"max_ack_pending class-attribute instance-attribute","text":"
max_ack_pending: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.max_deliver","title":"max_deliver class-attribute instance-attribute","text":"
max_deliver: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.max_waiting","title":"max_waiting class-attribute instance-attribute","text":"
max_waiting: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.mem_storage","title":"mem_storage class-attribute instance-attribute","text":"
mem_storage: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.num_replicas","title":"num_replicas class-attribute instance-attribute","text":"
num_replicas: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.opt_start_seq","title":"opt_start_seq class-attribute instance-attribute","text":"
opt_start_seq: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.opt_start_time","title":"opt_start_time class-attribute instance-attribute","text":"
opt_start_time: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.rate_limit_bps","title":"rate_limit_bps class-attribute instance-attribute","text":"
rate_limit_bps: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.replay_policy","title":"replay_policy class-attribute instance-attribute","text":"
replay_policy: Optional[ReplayPolicy] = ReplayPolicy.INSTANT\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.sample_freq","title":"sample_freq class-attribute instance-attribute","text":"
sample_freq: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n
Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    result = super().as_dict()\n    result['ack_wait'] = self._to_nanoseconds(self.ack_wait)\n    result['idle_heartbeat'] = self._to_nanoseconds(self.idle_heartbeat)\n    result['inactive_threshold'] = self._to_nanoseconds(\n        self.inactive_threshold\n    )\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/ConsumerConfig/#nats.js.api.ConsumerConfig.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any])\n
Source code in nats/js/api.py
@classmethod\ndef from_response(cls, resp: Dict[str, Any]):\n    cls._convert_nanoseconds(resp, 'ack_wait')\n    cls._convert_nanoseconds(resp, 'idle_heartbeat')\n    cls._convert_nanoseconds(resp, 'inactive_threshold')\n    return super().from_response(resp)\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/","title":"DeliverPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy","title":"nats.js.api.DeliverPolicy","text":"

Bases: str, Enum

When a consumer is first created, it can specify where in the stream it wants to start receiving messages.

This is the DeliverPolicy, and this enumeration defines allowed values.

References ","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.ALL","title":"ALL class-attribute instance-attribute","text":"
ALL = 'all'\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.BY_START_SEQUENCE","title":"BY_START_SEQUENCE class-attribute instance-attribute","text":"
BY_START_SEQUENCE = 'by_start_sequence'\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.BY_START_TIME","title":"BY_START_TIME class-attribute instance-attribute","text":"
BY_START_TIME = 'by_start_time'\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.LAST","title":"LAST class-attribute instance-attribute","text":"
LAST = 'last'\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.LAST_PER_SUBJECT","title":"LAST_PER_SUBJECT class-attribute instance-attribute","text":"
LAST_PER_SUBJECT = 'last_per_subject'\n
","boost":0.5},{"location":"api/faststream/nats/DeliverPolicy/#nats.js.api.DeliverPolicy.NEW","title":"NEW class-attribute instance-attribute","text":"
NEW = 'new'\n
","boost":0.5},{"location":"api/faststream/nats/DiscardPolicy/","title":"DiscardPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/DiscardPolicy/#nats.js.api.DiscardPolicy","title":"nats.js.api.DiscardPolicy","text":"

Bases: str, Enum

Discard policy when a stream reaches its limits

","boost":0.5},{"location":"api/faststream/nats/DiscardPolicy/#nats.js.api.DiscardPolicy.NEW","title":"NEW class-attribute instance-attribute","text":"
NEW = 'new'\n
","boost":0.5},{"location":"api/faststream/nats/DiscardPolicy/#nats.js.api.DiscardPolicy.OLD","title":"OLD class-attribute instance-attribute","text":"
OLD = 'old'\n
","boost":0.5},{"location":"api/faststream/nats/ExternalStream/","title":"ExternalStream","text":"","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream","title":"nats.js.api.ExternalStream dataclass","text":"

Bases: Base

","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream.api","title":"api instance-attribute","text":"
api: str\n
","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream.deliver","title":"deliver class-attribute instance-attribute","text":"
deliver: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/ExternalStream/#nats.js.api.ExternalStream.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/JStream/","title":"JStream","text":"","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream","title":"faststream.nats.JStream","text":"
JStream(\n    name: str,\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any\n)\n

Bases: NameRequired

Source code in faststream/nats/js_stream.py
def __init__(\n    self,\n    name: str,\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any,\n) -> None:\n    super().__init__(\n        name=name,\n        declare=declare,\n        subjects=[],\n        config=StreamConfig(\n            *args,\n            name=name,\n            **kwargs,  # type: ignore[misc]\n        ),\n    )\n
","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream.config","title":"config instance-attribute","text":"
config: StreamConfig\n
","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream.declare","title":"declare class-attribute instance-attribute","text":"
declare: bool = Field(default=True)\n
","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream.subjects","title":"subjects class-attribute instance-attribute","text":"
subjects: List[str] = Field(default_factory=list)\n
","boost":0.5},{"location":"api/faststream/nats/JStream/#faststream.nats.JStream.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/","title":"NatsBroker","text":"","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker","title":"faststream.nats.NatsBroker","text":"
NatsBroker(\n    servers: Union[str, Sequence[str]] = (\n        \"nats://localhost:4222\"\n    ),\n    *,\n    security: Optional[BaseSecurity] = None,\n    protocol: str = \"nats\",\n    protocol_version: Optional[str] = \"custom\",\n    **kwargs: Any\n)\n

Bases: NatsLoggingMixin, BrokerAsyncUsecase[Msg, Client]

Source code in faststream/nats/broker.py
def __init__(\n    self,\n    servers: Union[str, Sequence[str]] = (\"nats://localhost:4222\",),  # noqa: B006\n    *,\n    security: Optional[BaseSecurity] = None,\n    protocol: str = \"nats\",\n    protocol_version: Optional[str] = \"custom\",\n    **kwargs: Any,\n) -> None:\n    kwargs.update(parse_security(security))\n\n    if kwargs.get(\"tls\"):  # pragma: no cover\n        warnings.warn(\n            (\n                \"\\nNATS `tls` option was deprecated and will be removed in 0.4.0\"\n                \"\\nPlease, use `security` with `BaseSecurity` or `SASLPlaintext` instead\"\n            ),\n            DeprecationWarning,\n            stacklevel=2,\n        )\n\n    super().__init__(\n        url=([servers] if isinstance(servers, str) else list(servers)),\n        protocol=protocol,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n    )\n\n    self.__is_connected = False\n    self._producer = None\n\n    # JS options\n    self.stream = None\n    self._js_producer = None\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[Subject, Handler]\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.stream","title":"stream instance-attribute","text":"
stream: Optional[JetStreamContext] = None\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.url","title":"url instance-attribute","text":"
url: List[str]\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.connect","title":"connect async","text":"
connect(*args: Any, **kwargs: Any) -> Client\n
Source code in faststream/nats/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Client:\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        self.__set_publisher_producer(p)\n    return connection\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, stream: Optional[str] = None, **kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    stream: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[DecodedMessage]:\n    if stream is None:\n        assert self._producer, NOT_CONNECTED_YET  # nosec B101\n        return await self._producer.publish(*args, **kwargs)\n    else:\n        assert self._js_producer, NOT_CONNECTED_YET  # nosec B101\n        return await self._js_producer.publish(\n            *args,\n            stream=stream,\n            **kwargs,  # type: ignore[misc]\n        )\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.publisher","title":"publisher","text":"
publisher(\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    stream: Union[str, JStream, None] = None,\n    timeout: Optional[float] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/nats/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    # Core\n    reply_to: str = \"\",\n    # JS\n    stream: Union[str, JStream, None] = None,\n    timeout: Optional[float] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    if (stream := stream_builder.stream(stream)) is not None:\n        stream.subjects.append(subject)\n\n    publisher = self._publishers.get(\n        subject,\n        Publisher(\n            subject=subject,\n            headers=headers,\n            # Core\n            reply_to=reply_to,\n            # JS\n            timeout=timeout,\n            stream=stream,\n            # AsyncAPI\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(subject, publisher)\n    self.__set_publisher_producer(publisher)\n    return publisher\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.start","title":"start async","text":"
start() -> None\n
Source code in faststream/nats/broker.py
async def start(self) -> None:\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n    assert (\n        self._connection and self.stream\n    ), \"Broker should be started already\"  # nosec B101\n\n    for handler in self.handlers.values():\n        stream = handler.stream\n\n        if (is_js := stream is not None) and stream.declare:\n            try:  # pragma: no branch\n                await self.stream.add_stream(\n                    config=stream.config,\n                    subjects=stream.subjects,\n                )\n\n            except nats.js.errors.BadRequestError as e:\n                old_config = (await self.stream.stream_info(stream.name)).config\n\n                c = self._get_log_context(None, \"\")\n                if (\n                    e.description\n                    == \"stream name already in use with a different configuration\"\n                ):\n                    self._log(str(e), logging.WARNING, c)\n                    await self.stream.update_stream(\n                        config=stream.config,\n                        subjects=tuple(\n                            set(old_config.subjects or ()).union(stream.subjects)\n                        ),\n                    )\n\n                else:  # pragma: no cover\n                    self._log(str(e), logging.ERROR, c, exc_info=e)\n\n            finally:\n                # prevent from double declaration\n                stream.declare = False\n\n        c = self._get_log_context(\n            None,\n            subject=handler.subject,\n            queue=handler.queue,\n            stream=stream.name if stream else \"\",\n        )\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self.stream if is_js else self._connection)\n
","boost":0.5},{"location":"api/faststream/nats/NatsBroker/#faststream.nats.NatsBroker.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/nats/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    # Core arguments\n    max_msgs: int = 0,\n    # JS arguments\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    # pull arguments\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    # custom\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[Sequence[Callable[[Msg], BaseMiddleware]]] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],\n]:\n    stream = stream_builder.stream(stream)\n\n    if pull_sub is not None and stream is None:\n        raise ValueError(\"Pull subscriber can be used only with a stream\")\n\n    self._setup_log_context(\n        queue=queue,\n        subject=subject,\n        stream=stream.name if stream else None,\n    )\n    super().subscriber()\n\n    extra_options: AnyDict = {\n        \"pending_msgs_limit\": pending_msgs_limit\n        or (\n            DEFAULT_JS_SUB_PENDING_MSGS_LIMIT\n            if stream\n            else DEFAULT_SUB_PENDING_MSGS_LIMIT\n        ),\n        \"pending_bytes_limit\": pending_bytes_limit\n        or (\n            DEFAULT_JS_SUB_PENDING_BYTES_LIMIT\n            if stream\n            else DEFAULT_SUB_PENDING_BYTES_LIMIT\n        ),\n    }\n\n    if stream:\n        extra_options.update(\n            {\n                \"durable\": durable,\n                \"stream\": stream.name,\n                \"config\": config,\n            }\n        )\n\n        if pull_sub is not None:\n            extra_options.update({\"inbox_prefix\": inbox_prefix})\n\n        else:\n            extra_options.update(\n                {\n                    \"ordered_consumer\": ordered_consumer,\n                    \"idle_heartbeat\": idle_heartbeat,\n                    \"flow_control\": flow_control,\n                    \"deliver_policy\": deliver_policy,\n                    \"headers_only\": headers_only,\n                    \"manual_ack\": not ack_first,\n                }\n            )\n\n    else:\n        extra_options.update(\n            {\n                \"max_msgs\": max_msgs,\n            }\n        )\n\n    key = Handler.get_routing_hash(subject)\n    handler = self.handlers[key] = self.handlers.get(\n        key,\n        Handler(\n            subject=subject,\n            queue=queue,\n            stream=stream,\n            pull_sub=pull_sub,\n            extra_options=extra_options,\n            title=title,\n            description=description,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n            log_context_builder=partial(\n                self._get_log_context,\n                stream=stream.name if stream else \"\",\n                subject=subject,\n                queue=queue,\n            ),\n        ),\n    )\n\n    if stream:\n        stream.subjects.append(handler.subject)\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn,]:\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/nats/NatsRoute/","title":"NatsRoute","text":"","boost":0.5},{"location":"api/faststream/nats/NatsRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/nats/NatsRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/nats/NatsRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/nats/NatsRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/","title":"NatsRouter","text":"","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter","title":"faststream.nats.NatsRouter","text":"
NatsRouter(\n    prefix: str = \"\",\n    handlers: Sequence[NatsRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: NatsRouter

Source code in faststream/nats/router.py
    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.publisher","title":"publisher","text":"
publisher(\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/nats/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            subject=subject,\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/nats/NatsRouter/#faststream.nats.NatsRouter.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    retry: bool = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
","boost":0.5},{"location":"api/faststream/nats/Placement/","title":"Placement","text":"","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement","title":"nats.js.api.Placement dataclass","text":"

Bases: Base

Placement directives to consider when placing replicas of this stream

","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement.cluster","title":"cluster class-attribute instance-attribute","text":"
cluster: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/Placement/#nats.js.api.Placement.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/PullSub/","title":"PullSub","text":"","boost":0.5},{"location":"api/faststream/nats/PullSub/#faststream.nats.PullSub","title":"faststream.nats.PullSub","text":"
PullSub(\n    batch_size: int = 1,\n    timeout: Optional[float] = 5.0,\n    batch: bool = False,\n)\n

Bases: BaseModel

Source code in faststream/nats/pull_sub.py
def __init__(\n    self,\n    batch_size: int = 1,\n    timeout: Optional[float] = 5.0,\n    batch: bool = False,\n) -> None:\n    super().__init__(\n        batch_size=batch_size,\n        timeout=timeout,\n        batch=batch,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/PullSub/#faststream.nats.PullSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = Field(default=False)\n
","boost":0.5},{"location":"api/faststream/nats/PullSub/#faststream.nats.PullSub.batch_size","title":"batch_size class-attribute instance-attribute","text":"
batch_size: int = Field(default=1)\n
","boost":0.5},{"location":"api/faststream/nats/PullSub/#faststream.nats.PullSub.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: Optional[float] = Field(default=5.0)\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/","title":"RePublish","text":"","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish","title":"nats.js.api.RePublish dataclass","text":"

Bases: Base

RePublish is for republishing messages once committed to a stream. The original subject cis remapped from the subject pattern to the destination pattern.

","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.dest","title":"dest class-attribute instance-attribute","text":"
dest: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.headers_only","title":"headers_only class-attribute instance-attribute","text":"
headers_only: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.src","title":"src class-attribute instance-attribute","text":"
src: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/RePublish/#nats.js.api.RePublish.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/ReplayPolicy/","title":"ReplayPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/ReplayPolicy/#nats.js.api.ReplayPolicy","title":"nats.js.api.ReplayPolicy","text":"

Bases: str, Enum

The replay policy applies when the DeliverPolicy is one of

since those deliver policies begin reading the stream at a position other than the end.

References ","boost":0.5},{"location":"api/faststream/nats/ReplayPolicy/#nats.js.api.ReplayPolicy.INSTANT","title":"INSTANT class-attribute instance-attribute","text":"
INSTANT = 'instant'\n
","boost":0.5},{"location":"api/faststream/nats/ReplayPolicy/#nats.js.api.ReplayPolicy.ORIGINAL","title":"ORIGINAL class-attribute instance-attribute","text":"
ORIGINAL = 'original'\n
","boost":0.5},{"location":"api/faststream/nats/RetentionPolicy/","title":"RetentionPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/RetentionPolicy/#nats.js.api.RetentionPolicy","title":"nats.js.api.RetentionPolicy","text":"

Bases: str, Enum

How message retention is considered

","boost":0.5},{"location":"api/faststream/nats/RetentionPolicy/#nats.js.api.RetentionPolicy.INTEREST","title":"INTEREST class-attribute instance-attribute","text":"
INTEREST = 'interest'\n
","boost":0.5},{"location":"api/faststream/nats/RetentionPolicy/#nats.js.api.RetentionPolicy.LIMITS","title":"LIMITS class-attribute instance-attribute","text":"
LIMITS = 'limits'\n
","boost":0.5},{"location":"api/faststream/nats/RetentionPolicy/#nats.js.api.RetentionPolicy.WORK_QUEUE","title":"WORK_QUEUE class-attribute instance-attribute","text":"
WORK_QUEUE = 'workqueue'\n
","boost":0.5},{"location":"api/faststream/nats/StorageType/","title":"StorageType","text":"","boost":0.5},{"location":"api/faststream/nats/StorageType/#nats.js.api.StorageType","title":"nats.js.api.StorageType","text":"

Bases: str, Enum

The type of storage backend

","boost":0.5},{"location":"api/faststream/nats/StorageType/#nats.js.api.StorageType.FILE","title":"FILE class-attribute instance-attribute","text":"
FILE = 'file'\n
","boost":0.5},{"location":"api/faststream/nats/StorageType/#nats.js.api.StorageType.MEMORY","title":"MEMORY class-attribute instance-attribute","text":"
MEMORY = 'memory'\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/","title":"StreamConfig","text":"","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig","title":"nats.js.api.StreamConfig dataclass","text":"

Bases: Base

StreamConfig represents the configuration of a stream.

","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.allow_direct","title":"allow_direct class-attribute instance-attribute","text":"
allow_direct: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.allow_rollup_hdrs","title":"allow_rollup_hdrs class-attribute instance-attribute","text":"
allow_rollup_hdrs: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.deny_delete","title":"deny_delete class-attribute instance-attribute","text":"
deny_delete: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.deny_purge","title":"deny_purge class-attribute instance-attribute","text":"
deny_purge: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.description","title":"description class-attribute instance-attribute","text":"
description: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.discard","title":"discard class-attribute instance-attribute","text":"
discard: Optional[DiscardPolicy] = DiscardPolicy.OLD\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.duplicate_window","title":"duplicate_window class-attribute instance-attribute","text":"
duplicate_window: float = 0\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_age","title":"max_age class-attribute instance-attribute","text":"
max_age: Optional[float] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_bytes","title":"max_bytes class-attribute instance-attribute","text":"
max_bytes: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_consumers","title":"max_consumers class-attribute instance-attribute","text":"
max_consumers: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_msg_size","title":"max_msg_size class-attribute instance-attribute","text":"
max_msg_size: Optional[int] = -1\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_msgs","title":"max_msgs class-attribute instance-attribute","text":"
max_msgs: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.max_msgs_per_subject","title":"max_msgs_per_subject class-attribute instance-attribute","text":"
max_msgs_per_subject: int = -1\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.mirror","title":"mirror class-attribute instance-attribute","text":"
mirror: Optional[StreamSource] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.mirror_direct","title":"mirror_direct class-attribute instance-attribute","text":"
mirror_direct: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.name","title":"name class-attribute instance-attribute","text":"
name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.no_ack","title":"no_ack class-attribute instance-attribute","text":"
no_ack: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.num_replicas","title":"num_replicas class-attribute instance-attribute","text":"
num_replicas: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.placement","title":"placement class-attribute instance-attribute","text":"
placement: Optional[Placement] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.republish","title":"republish class-attribute instance-attribute","text":"
republish: Optional[RePublish] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.retention","title":"retention class-attribute instance-attribute","text":"
retention: Optional[RetentionPolicy] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.sealed","title":"sealed class-attribute instance-attribute","text":"
sealed: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.sources","title":"sources class-attribute instance-attribute","text":"
sources: Optional[List[StreamSource]] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.storage","title":"storage class-attribute instance-attribute","text":"
storage: Optional[StorageType] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.subjects","title":"subjects class-attribute instance-attribute","text":"
subjects: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.template_owner","title":"template_owner class-attribute instance-attribute","text":"
template_owner: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n
Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    result = super().as_dict()\n    result['duplicate_window'] = self._to_nanoseconds(\n        self.duplicate_window\n    )\n    result['max_age'] = self._to_nanoseconds(self.max_age)\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/StreamConfig/#nats.js.api.StreamConfig.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any])\n
Source code in nats/js/api.py
@classmethod\ndef from_response(cls, resp: Dict[str, Any]):\n    cls._convert_nanoseconds(resp, 'max_age')\n    cls._convert_nanoseconds(resp, 'duplicate_window')\n    cls._convert(resp, 'placement', Placement)\n    cls._convert(resp, 'mirror', StreamSource)\n    cls._convert(resp, 'sources', StreamSource)\n    cls._convert(resp, 'republish', RePublish)\n    return super().from_response(resp)\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/","title":"StreamSource","text":"","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource","title":"nats.js.api.StreamSource dataclass","text":"

Bases: Base

","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.external","title":"external class-attribute instance-attribute","text":"
external: Optional[ExternalStream] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.filter_subject","title":"filter_subject class-attribute instance-attribute","text":"
filter_subject: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.opt_start_seq","title":"opt_start_seq class-attribute instance-attribute","text":"
opt_start_seq: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/StreamSource/#nats.js.api.StreamSource.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any])\n
Source code in nats/js/api.py
@classmethod\ndef from_response(cls, resp: Dict[str, Any]):\n    cls._convert(resp, 'external', ExternalStream)\n    return super().from_response(resp)\n
","boost":0.5},{"location":"api/faststream/nats/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/nats/TestApp/#faststream.broker.test.TestApp","title":"faststream.broker.test.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/nats/TestApp/#faststream.broker.test.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/","title":"TestNatsBroker","text":"","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker","title":"faststream.nats.TestNatsBroker","text":"
TestNatsBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[NatsBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/nats/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: NatsBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(publisher.subject, _raw=True)\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(broker: NatsBroker, publisher: Any) -> None\n
Source code in faststream/nats/test.py
@staticmethod\ndef patch_publisher(broker: NatsBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/nats/TestNatsBroker/#faststream.nats.TestNatsBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> None\n
Source code in faststream/nats/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> None:\n    broker.handlers.pop(Handler.get_routing_hash(publisher.subject), None)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/","title":"Handler","text":"","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler","title":"faststream.nats.asyncapi.Handler","text":"
Handler(\n    subject: str,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    queue: str = \"\",\n    stream: Optional[JStream] = None,\n    pull_sub: Optional[PullSub] = None,\n    extra_options: Optional[AnyDict] = None,\n    graceful_timeout: Optional[float] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n)\n

Bases: LogicNatsHandler

Source code in faststream/nats/handler.py
def __init__(\n    self,\n    subject: str,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    queue: str = \"\",\n    stream: Optional[JStream] = None,\n    pull_sub: Optional[PullSub] = None,\n    extra_options: Optional[AnyDict] = None,\n    graceful_timeout: Optional[float] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    reg, path = compile_path(subject, replace_symbol=\"*\")\n    self.subject = path\n    self.path_regex = reg\n\n    self.queue = queue\n\n    self.stream = stream\n    self.pull_sub = pull_sub\n    self.extra_options = extra_options or {}\n\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        include_in_schema=include_in_schema,\n        title=title,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.task = None\n    self.subscription = None\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.extra_options","title":"extra_options instance-attribute","text":"
extra_options = extra_options or {}\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.path_regex","title":"path_regex instance-attribute","text":"
path_regex = reg\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.pull_sub","title":"pull_sub instance-attribute","text":"
pull_sub = pull_sub\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.queue","title":"queue instance-attribute","text":"
queue = queue\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.stream","title":"stream instance-attribute","text":"
stream = stream\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.subject","title":"subject instance-attribute","text":"
subject = path\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.subscription","title":"subscription instance-attribute","text":"
subscription: Union[\n    None,\n    Subscription,\n    JetStreamContext.PushSubscription,\n    JetStreamContext.PullSubscription,\n] = None\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.task","title":"task class-attribute instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[Msg, NatsMessage]],\n    decoder: Optional[CustomDecoder[NatsMessage]],\n    filter: Filter[NatsMessage],\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ]\n) -> None\n
Source code in faststream/nats/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[Msg, NatsMessage]],\n    decoder: Optional[CustomDecoder[NatsMessage]],\n    filter: Filter[NatsMessage],\n    middlewares: Optional[Sequence[Callable[[Msg], BaseMiddleware]]],\n) -> None:\n    parser_ = Parser if self.stream is None else JsParser\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, parser_.parse_message),\n        decoder=resolve_custom_func(decoder, parser_.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/nats/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.subscription is not None:\n        await self.subscription.unsubscribe()\n        self.subscription = None\n\n    if self.task is not None:\n        self.task.cancel()\n        self.task = None\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(subject: str) -> str\n
Source code in faststream/nats/handler.py
@staticmethod\ndef get_routing_hash(subject: str) -> str:\n    return subject\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/nats/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n    handler_name = self._title or f\"{self.subject}:{self.call_name}\"\n    return {\n        handler_name: Channel(\n            description=self.description,\n            subscribe=Operation(\n                message=Message(\n                    title=f\"{handler_name}:Message\",\n                    payload=resolve_payloads(payloads),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                nats=nats.ChannelBinding(\n                    subject=self.subject,\n                    queue=self.queue or None,\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Handler/#faststream.nats.asyncapi.Handler.start","title":"start async","text":"
start(connection: Union[Client, JetStreamContext]) -> None\n
Source code in faststream/nats/handler.py
@override\nasync def start(self, connection: Union[Client, JetStreamContext]) -> None:  # type: ignore[override]\n    if self.pull_sub is not None:\n        connection = cast(JetStreamContext, connection)\n\n        if self.stream is None:\n            raise ValueError(\"Pull subscriber can be used only with a stream\")\n\n        self.subscription = await connection.pull_subscribe(\n            subject=self.subject,\n            **self.extra_options,\n        )\n        self.task = asyncio.create_task(self._consume())\n\n    else:\n        self.subscription = await connection.subscribe(\n            subject=self.subject,\n            queue=self.queue,\n            cb=self.consume,  # type: ignore[arg-type]\n            **self.extra_options,\n        )\n\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/","title":"Publisher","text":"","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher","title":"faststream.nats.asyncapi.Publisher","text":"

Bases: LogicPublisher

","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.name","title":"name property","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.stream","title":"stream class-attribute instance-attribute","text":"
stream: Optional[JStream] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.subject","title":"subject class-attribute instance-attribute","text":"
subject: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: Optional[float] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.publish","title":"publish async","text":"
publish(\n    message: SendableMessage = \"\",\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[Dict[str, str]] = None,\n    **producer_kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage = \"\",\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[Dict[str, str]] = None,\n    **producer_kwargs: Any,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    assert self.subject, \"You have to specify outgoing subject\"  # nosec B101\n\n    extra: AnyDict = {\n        \"reply_to\": reply_to or self.reply_to,\n    }\n    if self.stream is not None:\n        extra.update(\n            {\n                \"stream\": self.stream.name,\n                \"timeout\": self.timeout,\n            }\n        )\n\n    return await self._producer.publish(\n        message=message,\n        subject=self.subject,\n        headers=headers or self.headers,\n        correlation_id=correlation_id,\n        **extra,\n        **producer_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/nats/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    return {\n        self.name: Channel(\n            description=self.description,\n            publish=Operation(\n                message=Message(\n                    title=f\"{self.name}:Message\",\n                    payload=resolve_payloads(payloads, \"Publisher\"),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                nats=nats.ChannelBinding(\n                    subject=self.subject,\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/nats/asyncapi/Publisher/#faststream.nats.asyncapi.Publisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/","title":"NatsBroker","text":"","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker","title":"faststream.nats.broker.NatsBroker","text":"
NatsBroker(\n    servers: Union[str, Sequence[str]] = (\n        \"nats://localhost:4222\"\n    ),\n    *,\n    security: Optional[BaseSecurity] = None,\n    protocol: str = \"nats\",\n    protocol_version: Optional[str] = \"custom\",\n    **kwargs: Any\n)\n

Bases: NatsLoggingMixin, BrokerAsyncUsecase[Msg, Client]

Source code in faststream/nats/broker.py
def __init__(\n    self,\n    servers: Union[str, Sequence[str]] = (\"nats://localhost:4222\",),  # noqa: B006\n    *,\n    security: Optional[BaseSecurity] = None,\n    protocol: str = \"nats\",\n    protocol_version: Optional[str] = \"custom\",\n    **kwargs: Any,\n) -> None:\n    kwargs.update(parse_security(security))\n\n    if kwargs.get(\"tls\"):  # pragma: no cover\n        warnings.warn(\n            (\n                \"\\nNATS `tls` option was deprecated and will be removed in 0.4.0\"\n                \"\\nPlease, use `security` with `BaseSecurity` or `SASLPlaintext` instead\"\n            ),\n            DeprecationWarning,\n            stacklevel=2,\n        )\n\n    super().__init__(\n        url=([servers] if isinstance(servers, str) else list(servers)),\n        protocol=protocol,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n    )\n\n    self.__is_connected = False\n    self._producer = None\n\n    # JS options\n    self.stream = None\n    self._js_producer = None\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[Subject, Handler]\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.stream","title":"stream instance-attribute","text":"
stream: Optional[JetStreamContext] = None\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.url","title":"url instance-attribute","text":"
url: List[str]\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.connect","title":"connect async","text":"
connect(*args: Any, **kwargs: Any) -> Client\n
Source code in faststream/nats/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Client:\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        self.__set_publisher_producer(p)\n    return connection\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, stream: Optional[str] = None, **kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    stream: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[DecodedMessage]:\n    if stream is None:\n        assert self._producer, NOT_CONNECTED_YET  # nosec B101\n        return await self._producer.publish(*args, **kwargs)\n    else:\n        assert self._js_producer, NOT_CONNECTED_YET  # nosec B101\n        return await self._js_producer.publish(\n            *args,\n            stream=stream,\n            **kwargs,  # type: ignore[misc]\n        )\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.publisher","title":"publisher","text":"
publisher(\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    stream: Union[str, JStream, None] = None,\n    timeout: Optional[float] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/nats/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    # Core\n    reply_to: str = \"\",\n    # JS\n    stream: Union[str, JStream, None] = None,\n    timeout: Optional[float] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    if (stream := stream_builder.stream(stream)) is not None:\n        stream.subjects.append(subject)\n\n    publisher = self._publishers.get(\n        subject,\n        Publisher(\n            subject=subject,\n            headers=headers,\n            # Core\n            reply_to=reply_to,\n            # JS\n            timeout=timeout,\n            stream=stream,\n            # AsyncAPI\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(subject, publisher)\n    self.__set_publisher_producer(publisher)\n    return publisher\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.start","title":"start async","text":"
start() -> None\n
Source code in faststream/nats/broker.py
async def start(self) -> None:\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n    assert (\n        self._connection and self.stream\n    ), \"Broker should be started already\"  # nosec B101\n\n    for handler in self.handlers.values():\n        stream = handler.stream\n\n        if (is_js := stream is not None) and stream.declare:\n            try:  # pragma: no branch\n                await self.stream.add_stream(\n                    config=stream.config,\n                    subjects=stream.subjects,\n                )\n\n            except nats.js.errors.BadRequestError as e:\n                old_config = (await self.stream.stream_info(stream.name)).config\n\n                c = self._get_log_context(None, \"\")\n                if (\n                    e.description\n                    == \"stream name already in use with a different configuration\"\n                ):\n                    self._log(str(e), logging.WARNING, c)\n                    await self.stream.update_stream(\n                        config=stream.config,\n                        subjects=tuple(\n                            set(old_config.subjects or ()).union(stream.subjects)\n                        ),\n                    )\n\n                else:  # pragma: no cover\n                    self._log(str(e), logging.ERROR, c, exc_info=e)\n\n            finally:\n                # prevent from double declaration\n                stream.declare = False\n\n        c = self._get_log_context(\n            None,\n            subject=handler.subject,\n            queue=handler.queue,\n            stream=stream.name if stream else \"\",\n        )\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self.stream if is_js else self._connection)\n
","boost":0.5},{"location":"api/faststream/nats/broker/NatsBroker/#faststream.nats.broker.NatsBroker.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/nats/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    # Core arguments\n    max_msgs: int = 0,\n    # JS arguments\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    # pull arguments\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    # custom\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[Sequence[Callable[[Msg], BaseMiddleware]]] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],\n]:\n    stream = stream_builder.stream(stream)\n\n    if pull_sub is not None and stream is None:\n        raise ValueError(\"Pull subscriber can be used only with a stream\")\n\n    self._setup_log_context(\n        queue=queue,\n        subject=subject,\n        stream=stream.name if stream else None,\n    )\n    super().subscriber()\n\n    extra_options: AnyDict = {\n        \"pending_msgs_limit\": pending_msgs_limit\n        or (\n            DEFAULT_JS_SUB_PENDING_MSGS_LIMIT\n            if stream\n            else DEFAULT_SUB_PENDING_MSGS_LIMIT\n        ),\n        \"pending_bytes_limit\": pending_bytes_limit\n        or (\n            DEFAULT_JS_SUB_PENDING_BYTES_LIMIT\n            if stream\n            else DEFAULT_SUB_PENDING_BYTES_LIMIT\n        ),\n    }\n\n    if stream:\n        extra_options.update(\n            {\n                \"durable\": durable,\n                \"stream\": stream.name,\n                \"config\": config,\n            }\n        )\n\n        if pull_sub is not None:\n            extra_options.update({\"inbox_prefix\": inbox_prefix})\n\n        else:\n            extra_options.update(\n                {\n                    \"ordered_consumer\": ordered_consumer,\n                    \"idle_heartbeat\": idle_heartbeat,\n                    \"flow_control\": flow_control,\n                    \"deliver_policy\": deliver_policy,\n                    \"headers_only\": headers_only,\n                    \"manual_ack\": not ack_first,\n                }\n            )\n\n    else:\n        extra_options.update(\n            {\n                \"max_msgs\": max_msgs,\n            }\n        )\n\n    key = Handler.get_routing_hash(subject)\n    handler = self.handlers[key] = self.handlers.get(\n        key,\n        Handler(\n            subject=subject,\n            queue=queue,\n            stream=stream,\n            pull_sub=pull_sub,\n            extra_options=extra_options,\n            title=title,\n            description=description,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n            log_context_builder=partial(\n                self._get_log_context,\n                stream=stream.name if stream else \"\",\n                subject=subject,\n                queue=queue,\n            ),\n        ),\n    )\n\n    if stream:\n        stream.subjects.append(handler.subject)\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn,]:\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/nats/fastapi/Context/#faststream.broker.fastapi.context.Context","title":"faststream.broker.fastapi.context.Context","text":"
Context(name: str) -> Any\n
Source code in faststream/broker/fastapi/context.py
def Context(name: str) -> Any:\n    return params.Depends(\n        lambda: context.resolve(name),\n        use_cache=True,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/","title":"NatsRouter","text":"","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter","title":"faststream.nats.fastapi.NatsRouter","text":"
NatsRouter(\n    servers: Union[str, Sequence[str]] = (\n        \"nats://localhost:4222\"\n    ),\n    *,\n    error_cb: Optional[ErrorCallback] = None,\n    disconnected_cb: Optional[Callback] = None,\n    closed_cb: Optional[Callback] = None,\n    discovered_server_cb: Optional[Callback] = None,\n    reconnected_cb: Optional[Callback] = None,\n    name: Optional[str] = None,\n    pedantic: bool = False,\n    verbose: bool = False,\n    allow_reconnect: bool = True,\n    connect_timeout: int = DEFAULT_CONNECT_TIMEOUT,\n    reconnect_time_wait: int = DEFAULT_RECONNECT_TIME_WAIT,\n    max_reconnect_attempts: int = DEFAULT_MAX_RECONNECT_ATTEMPTS,\n    ping_interval: int = DEFAULT_PING_INTERVAL,\n    max_outstanding_pings: int = DEFAULT_MAX_OUTSTANDING_PINGS,\n    dont_randomize: bool = False,\n    flusher_queue_size: int = DEFAULT_MAX_FLUSHER_QUEUE_SIZE,\n    no_echo: bool = False,\n    tls: Optional[ssl.SSLContext] = None,\n    tls_hostname: Optional[str] = None,\n    user: Optional[str] = None,\n    password: Optional[str] = None,\n    token: Optional[str] = None,\n    drain_timeout: int = DEFAULT_DRAIN_TIMEOUT,\n    signature_cb: Optional[SignatureCallback] = None,\n    user_jwt_cb: Optional[JWTCallback] = None,\n    user_credentials: Optional[Credentials] = None,\n    nkeys_seed: Optional[str] = None,\n    inbox_prefix: Union[str, bytes] = DEFAULT_INBOX_PREFIX,\n    pending_size: int = DEFAULT_PENDING_SIZE,\n    flush_timeout: Optional[float] = None,\n    graceful_timeout: Optional[float] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    asyncapi_url: Union[str, List[str], None] = None,\n    protocol: str = \"nats\",\n    protocol_version: Optional[str] = \"0.9.1\",\n    description: Optional[str] = None,\n    asyncapi_tags: Optional[Sequence[asyncapi.Tag]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    setup_state: bool = True,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n)\n

Bases: StreamRouter[Msg]

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.broker","title":"broker instance-attribute","text":"
broker: NatsBroker\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.broker_class","title":"broker_class class-attribute instance-attribute","text":"
broker_class = NB\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    subject: str,\n    *,\n    endpoint: Callable[..., T_HandlerReturn],\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    retry: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    **__service_kwargs: Any\n) -> Callable[[Msg, bool], Awaitable[T_HandlerReturn]]\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.publisher","title":"publisher","text":"
publisher(\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    stream: Union[str, JStream, None] = None,\n    timeout: Optional[float] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    retry: bool = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/nats/fastapi/NatsRouter/#faststream.nats.fastapi.NatsRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/","title":"LogicNatsHandler","text":"","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler","title":"faststream.nats.handler.LogicNatsHandler","text":"
LogicNatsHandler(\n    subject: str,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    queue: str = \"\",\n    stream: Optional[JStream] = None,\n    pull_sub: Optional[PullSub] = None,\n    extra_options: Optional[AnyDict] = None,\n    graceful_timeout: Optional[float] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n)\n

Bases: AsyncHandler[Msg]

Source code in faststream/nats/handler.py
def __init__(\n    self,\n    subject: str,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    queue: str = \"\",\n    stream: Optional[JStream] = None,\n    pull_sub: Optional[PullSub] = None,\n    extra_options: Optional[AnyDict] = None,\n    graceful_timeout: Optional[float] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    reg, path = compile_path(subject, replace_symbol=\"*\")\n    self.subject = path\n    self.path_regex = reg\n\n    self.queue = queue\n\n    self.stream = stream\n    self.pull_sub = pull_sub\n    self.extra_options = extra_options or {}\n\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        include_in_schema=include_in_schema,\n        title=title,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.task = None\n    self.subscription = None\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.extra_options","title":"extra_options instance-attribute","text":"
extra_options = extra_options or {}\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.path_regex","title":"path_regex instance-attribute","text":"
path_regex = reg\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.pull_sub","title":"pull_sub instance-attribute","text":"
pull_sub = pull_sub\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.queue","title":"queue instance-attribute","text":"
queue = queue\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.stream","title":"stream instance-attribute","text":"
stream = stream\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.subject","title":"subject instance-attribute","text":"
subject = path\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.subscription","title":"subscription instance-attribute","text":"
subscription: Union[\n    None,\n    Subscription,\n    JetStreamContext.PushSubscription,\n    JetStreamContext.PullSubscription,\n] = None\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.task","title":"task class-attribute instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[Msg, NatsMessage]],\n    decoder: Optional[CustomDecoder[NatsMessage]],\n    filter: Filter[NatsMessage],\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ]\n) -> None\n
Source code in faststream/nats/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[Msg, NatsMessage]],\n    decoder: Optional[CustomDecoder[NatsMessage]],\n    filter: Filter[NatsMessage],\n    middlewares: Optional[Sequence[Callable[[Msg], BaseMiddleware]]],\n) -> None:\n    parser_ = Parser if self.stream is None else JsParser\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, parser_.parse_message),\n        decoder=resolve_custom_func(decoder, parser_.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/nats/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.subscription is not None:\n        await self.subscription.unsubscribe()\n        self.subscription = None\n\n    if self.task is not None:\n        self.task.cancel()\n        self.task = None\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(subject: str) -> str\n
Source code in faststream/nats/handler.py
@staticmethod\ndef get_routing_hash(subject: str) -> str:\n    return subject\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/nats/handler/LogicNatsHandler/#faststream.nats.handler.LogicNatsHandler.start","title":"start async","text":"
start(connection: Union[Client, JetStreamContext]) -> None\n
Source code in faststream/nats/handler.py
@override\nasync def start(self, connection: Union[Client, JetStreamContext]) -> None:  # type: ignore[override]\n    if self.pull_sub is not None:\n        connection = cast(JetStreamContext, connection)\n\n        if self.stream is None:\n            raise ValueError(\"Pull subscriber can be used only with a stream\")\n\n        self.subscription = await connection.pull_subscribe(\n            subject=self.subject,\n            **self.extra_options,\n        )\n        self.task = asyncio.create_task(self._consume())\n\n    else:\n        self.subscription = await connection.subscribe(\n            subject=self.subject,\n            queue=self.queue,\n            cb=self.consume,  # type: ignore[arg-type]\n            **self.extra_options,\n        )\n\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/nats/helpers/StreamBuilder/","title":"StreamBuilder","text":"","boost":0.5},{"location":"api/faststream/nats/helpers/StreamBuilder/#faststream.nats.helpers.StreamBuilder","title":"faststream.nats.helpers.StreamBuilder","text":"
StreamBuilder()\n
Source code in faststream/nats/helpers.py
def __init__(self) -> None:\n    self.streams = {}\n
","boost":0.5},{"location":"api/faststream/nats/helpers/StreamBuilder/#faststream.nats.helpers.StreamBuilder.streams","title":"streams instance-attribute","text":"
streams: Dict[str, JStream] = {}\n
","boost":0.5},{"location":"api/faststream/nats/helpers/StreamBuilder/#faststream.nats.helpers.StreamBuilder.stream","title":"stream","text":"
stream(\n    name: Union[str, JStream, None],\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any\n) -> Optional[JStream]\n
Source code in faststream/nats/helpers.py
def stream(\n    self,\n    name: Union[str, JStream, None],\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any,\n) -> Optional[JStream]:\n    stream = JStream.validate(name)\n\n    if stream is not None:\n        stream = self.streams[stream.name] = self.streams.get(stream.name, stream)\n\n    return stream\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/DiscardPolicy/","title":"DiscardPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/DiscardPolicy/#nats.js.api.DiscardPolicy","title":"nats.js.api.DiscardPolicy","text":"

Bases: str, Enum

Discard policy when a stream reaches its limits

","boost":0.5},{"location":"api/faststream/nats/js_stream/DiscardPolicy/#nats.js.api.DiscardPolicy.NEW","title":"NEW class-attribute instance-attribute","text":"
NEW = 'new'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/DiscardPolicy/#nats.js.api.DiscardPolicy.OLD","title":"OLD class-attribute instance-attribute","text":"
OLD = 'old'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/","title":"ExternalStream","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream","title":"nats.js.api.ExternalStream dataclass","text":"

Bases: Base

","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream.api","title":"api instance-attribute","text":"
api: str\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream.deliver","title":"deliver class-attribute instance-attribute","text":"
deliver: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/ExternalStream/#nats.js.api.ExternalStream.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/","title":"JStream","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream","title":"faststream.nats.js_stream.JStream","text":"
JStream(\n    name: str,\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any\n)\n

Bases: NameRequired

Source code in faststream/nats/js_stream.py
def __init__(\n    self,\n    name: str,\n    *args: Any,\n    declare: bool = True,\n    **kwargs: Any,\n) -> None:\n    super().__init__(\n        name=name,\n        declare=declare,\n        subjects=[],\n        config=StreamConfig(\n            *args,\n            name=name,\n            **kwargs,  # type: ignore[misc]\n        ),\n    )\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream.config","title":"config instance-attribute","text":"
config: StreamConfig\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream.declare","title":"declare class-attribute instance-attribute","text":"
declare: bool = Field(default=True)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream.subjects","title":"subjects class-attribute instance-attribute","text":"
subjects: List[str] = Field(default_factory=list)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/JStream/#faststream.nats.js_stream.JStream.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/","title":"Placement","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement","title":"nats.js.api.Placement dataclass","text":"

Bases: Base

Placement directives to consider when placing replicas of this stream

","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement.cluster","title":"cluster class-attribute instance-attribute","text":"
cluster: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement.tags","title":"tags class-attribute instance-attribute","text":"
tags: Optional[List[str]] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/Placement/#nats.js.api.Placement.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/","title":"RePublish","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish","title":"nats.js.api.RePublish dataclass","text":"

Bases: Base

RePublish is for republishing messages once committed to a stream. The original subject cis remapped from the subject pattern to the destination pattern.

","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.dest","title":"dest class-attribute instance-attribute","text":"
dest: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.headers_only","title":"headers_only class-attribute instance-attribute","text":"
headers_only: Optional[bool] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.src","title":"src class-attribute instance-attribute","text":"
src: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RePublish/#nats.js.api.RePublish.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any]) -> _B\n

Read the class instance from a server response.

Unknown fields are ignored (\"open-world assumption\").

Source code in nats/js/api.py
@classmethod\ndef from_response(cls: type[_B], resp: Dict[str, Any]) -> _B:\n    \"\"\"Read the class instance from a server response.\n\n    Unknown fields are ignored (\"open-world assumption\").\n    \"\"\"\n    params = {}\n    for field in fields(cls):\n        if field.name in resp:\n            params[field.name] = resp[field.name]\n    return cls(**params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RetentionPolicy/","title":"RetentionPolicy","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/RetentionPolicy/#nats.js.api.RetentionPolicy","title":"nats.js.api.RetentionPolicy","text":"

Bases: str, Enum

How message retention is considered

","boost":0.5},{"location":"api/faststream/nats/js_stream/RetentionPolicy/#nats.js.api.RetentionPolicy.INTEREST","title":"INTEREST class-attribute instance-attribute","text":"
INTEREST = 'interest'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RetentionPolicy/#nats.js.api.RetentionPolicy.LIMITS","title":"LIMITS class-attribute instance-attribute","text":"
LIMITS = 'limits'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/RetentionPolicy/#nats.js.api.RetentionPolicy.WORK_QUEUE","title":"WORK_QUEUE class-attribute instance-attribute","text":"
WORK_QUEUE = 'workqueue'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StorageType/","title":"StorageType","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/StorageType/#nats.js.api.StorageType","title":"nats.js.api.StorageType","text":"

Bases: str, Enum

The type of storage backend

","boost":0.5},{"location":"api/faststream/nats/js_stream/StorageType/#nats.js.api.StorageType.FILE","title":"FILE class-attribute instance-attribute","text":"
FILE = 'file'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StorageType/#nats.js.api.StorageType.MEMORY","title":"MEMORY class-attribute instance-attribute","text":"
MEMORY = 'memory'\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/","title":"StreamSource","text":"","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource","title":"nats.js.api.StreamSource dataclass","text":"

Bases: Base

","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.external","title":"external class-attribute instance-attribute","text":"
external: Optional[ExternalStream] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.filter_subject","title":"filter_subject class-attribute instance-attribute","text":"
filter_subject: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.name","title":"name instance-attribute","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.opt_start_seq","title":"opt_start_seq class-attribute instance-attribute","text":"
opt_start_seq: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.as_dict","title":"as_dict","text":"
as_dict() -> Dict[str, object]\n

Return the object converted into an API-friendly dict.

Source code in nats/js/api.py
def as_dict(self) -> Dict[str, object]:\n    \"\"\"Return the object converted into an API-friendly dict.\n    \"\"\"\n    result = {}\n    for field in fields(self):\n        val = getattr(self, field.name)\n        if val is None:\n            continue\n        if isinstance(val, Base):\n            val = val.as_dict()\n        result[field.name] = val\n    return result\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.evolve","title":"evolve","text":"
evolve(**params) -> _B\n

Return a copy of the instance with the passed values replaced.

Source code in nats/js/api.py
def evolve(self: _B, **params) -> _B:\n    \"\"\"Return a copy of the instance with the passed values replaced.\n    \"\"\"\n    return replace(self, **params)\n
","boost":0.5},{"location":"api/faststream/nats/js_stream/StreamSource/#nats.js.api.StreamSource.from_response","title":"from_response classmethod","text":"
from_response(resp: Dict[str, Any])\n
Source code in nats/js/api.py
@classmethod\ndef from_response(cls, resp: Dict[str, Any]):\n    cls._convert(resp, 'external', ExternalStream)\n    return super().from_response(resp)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/","title":"NatsMessage","text":"","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage","title":"faststream.nats.message.NatsMessage dataclass","text":"

Bases: StreamMessage[Msg]

","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.is_js","title":"is_js class-attribute instance-attribute","text":"
is_js: bool = True\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.ack","title":"ack async","text":"
ack(**kwargs: Any) -> None\n
Source code in faststream/nats/message.py
async def ack(self, **kwargs: Any) -> None:\n    await super().ack()\n    if self.is_js:\n        if not isinstance(self.raw_message, list):\n            if not self.raw_message._ackd:\n                await self.raw_message.ack()\n\n        else:\n            for m in filter(\n                lambda m: not m._ackd,\n                self.raw_message,\n            ):\n                await m.ack()\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.in_progress","title":"in_progress async","text":"
in_progress(**kwargs: Any) -> None\n
Source code in faststream/nats/message.py
async def in_progress(self, **kwargs: Any) -> None:\n    if self.is_js:\n        if not isinstance(self.raw_message, list):\n            if not self.raw_message._ackd:\n                await self.raw_message.in_progress()\n\n        else:\n            for m in filter(\n                lambda m: not m._ackd,\n                self.raw_message,\n            ):\n                await m.in_progress()\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.nack","title":"nack async","text":"
nack(**kwargs: Any) -> None\n
Source code in faststream/nats/message.py
async def nack(self, **kwargs: Any) -> None:\n    await super().nack()\n    if self.is_js:\n        if not isinstance(self.raw_message, list):\n            if not self.raw_message._ackd:\n                await self.raw_message.nak(**kwargs)\n\n        else:\n            for m in filter(\n                lambda m: not m._ackd,\n                self.raw_message,\n            ):\n                await m.nak(**kwargs)\n
","boost":0.5},{"location":"api/faststream/nats/message/NatsMessage/#faststream.nats.message.NatsMessage.reject","title":"reject async","text":"
reject(**kwargs: Any) -> None\n
Source code in faststream/nats/message.py
async def reject(self, **kwargs: Any) -> None:\n    await super().reject()\n    if self.is_js:\n        if not isinstance(self.raw_message, list):\n            if not self.raw_message._ackd:\n                await self.raw_message.term()\n\n        else:\n            for m in filter(\n                lambda m: not m._ackd,\n                self.raw_message,\n            ):\n                await m.term()\n
","boost":0.5},{"location":"api/faststream/nats/parser/NatsParser/","title":"NatsParser","text":"","boost":0.5},{"location":"api/faststream/nats/parser/NatsParser/#faststream.nats.parser.NatsParser","title":"faststream.nats.parser.NatsParser","text":"
NatsParser(is_js: bool)\n
Source code in faststream/nats/parser.py
def __init__(self, is_js: bool) -> None:\n    self.is_js = is_js\n
","boost":0.5},{"location":"api/faststream/nats/parser/NatsParser/#faststream.nats.parser.NatsParser.is_js","title":"is_js instance-attribute","text":"
is_js = is_js\n
","boost":0.5},{"location":"api/faststream/nats/parser/NatsParser/#faststream.nats.parser.NatsParser.decode_message","title":"decode_message async","text":"
decode_message(\n    msg: Union[StreamMessage[Msg], StreamMessage[List[Msg]]]\n) -> DecodedMessage\n
Source code in faststream/nats/parser.py
async def decode_message(\n    self,\n    msg: Union[\n        StreamMessage[Msg],\n        StreamMessage[List[Msg]],\n    ],\n) -> DecodedMessage:\n    if isinstance(msg.raw_message, list):\n        data = []\n\n        path: Optional[AnyDict] = None\n        for m in msg.raw_message:\n            msg = await self.parse_message(m, path=path)\n            path = msg.path\n\n            data.append(decode_message(msg))\n\n        return data\n\n    else:\n        return decode_message(msg)\n
","boost":0.5},{"location":"api/faststream/nats/parser/NatsParser/#faststream.nats.parser.NatsParser.parse_message","title":"parse_message async","text":"
parse_message(\n    message: Union[Msg, List[Msg]],\n    *,\n    path: Optional[AnyDict] = None\n) -> Union[StreamMessage[Msg], StreamMessage[List[Msg]]]\n
Source code in faststream/nats/parser.py
async def parse_message(\n    self, message: Union[Msg, List[Msg]], *, path: Optional[AnyDict] = None\n) -> Union[StreamMessage[Msg], StreamMessage[List[Msg]],]:\n    if isinstance(message, list):\n        return NatsMessage(\n            is_js=self.is_js,\n            raw_message=message,  # type: ignore[arg-type]\n            body=[m.data for m in message],\n        )\n\n    else:\n        path_re: Optional[Pattern[str]]\n        if (\n            path is None\n            and (handler := context.get_local(\"handler_\"))\n            and (path_re := handler.path_regex) is not None\n            and (match := path_re.match(message.subject)) is not None\n        ):\n            path = match.groupdict()\n\n        headers = message.header or {}\n\n        return NatsMessage(\n            is_js=self.is_js,\n            raw_message=message,\n            body=message.data,\n            path=path or {},\n            reply_to=headers.get(\"reply_to\", \"\") if self.is_js else message.reply,\n            headers=headers,\n            content_type=headers.get(\"content-type\", \"\"),\n            message_id=headers.get(\"message_id\", str(uuid4())),\n            correlation_id=headers.get(\"correlation_id\", str(uuid4())),\n        )\n
","boost":0.5},{"location":"api/faststream/nats/producer/NatsFastProducer/","title":"NatsFastProducer","text":"","boost":0.5},{"location":"api/faststream/nats/producer/NatsFastProducer/#faststream.nats.producer.NatsFastProducer","title":"faststream.nats.producer.NatsFastProducer","text":"
NatsFastProducer(\n    connection: Client,\n    parser: Optional[AsyncCustomParser[Msg, NatsMessage]],\n    decoder: Optional[AsyncCustomDecoder[NatsMessage]],\n)\n
Source code in faststream/nats/producer.py
def __init__(\n    self,\n    connection: Client,\n    parser: Optional[AsyncCustomParser[Msg, NatsMessage]],\n    decoder: Optional[AsyncCustomDecoder[NatsMessage]],\n) -> None:\n    self._connection = connection\n    self._parser = resolve_custom_func(parser, Parser.parse_message)\n    self._decoder = resolve_custom_func(decoder, Parser.decode_message)\n
","boost":0.5},{"location":"api/faststream/nats/producer/NatsFastProducer/#faststream.nats.producer.NatsFastProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    subject: str,\n    reply_to: str = \"\",\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/producer.py
async def publish(\n    self,\n    message: SendableMessage,\n    subject: str,\n    reply_to: str = \"\",\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    payload, content_type = encode_message(message)\n\n    headers_to_send = {\n        \"content-type\": content_type or \"\",\n        \"correlation_id\": correlation_id or str(uuid4()),\n        **(headers or {}),\n    }\n\n    client = self._connection\n\n    if rpc:\n        if reply_to:\n            raise WRONG_PUBLISH_ARGS\n\n        token = client._nuid.next()\n        token.extend(token_hex(2).encode())\n        reply_to = token.decode()\n\n        future: asyncio.Future[Msg] = asyncio.Future()\n        sub = await client.subscribe(reply_to, future=future, max_msgs=1)\n        await sub.unsubscribe(limit=1)\n\n    await client.publish(\n        subject=subject,\n        payload=payload,\n        reply=reply_to,\n        headers=headers_to_send,\n    )\n\n    if rpc:\n        msg: Any = None\n        with timeout_scope(rpc_timeout, raise_timeout):\n            msg = await future\n\n        if msg:  # pragma: no branch\n            if msg.headers:  # pragma: no cover\n                if (\n                    msg.headers.get(nats.js.api.Header.STATUS)\n                    == nats.aio.client.NO_RESPONDERS_STATUS\n                ):\n                    raise nats.errors.NoRespondersError\n            return await self._decoder(await self._parser(msg))\n\n    return None\n
","boost":0.5},{"location":"api/faststream/nats/producer/NatsJSFastProducer/","title":"NatsJSFastProducer","text":"","boost":0.5},{"location":"api/faststream/nats/producer/NatsJSFastProducer/#faststream.nats.producer.NatsJSFastProducer","title":"faststream.nats.producer.NatsJSFastProducer","text":"
NatsJSFastProducer(\n    connection: JetStreamContext,\n    parser: Optional[AsyncCustomParser[Msg, NatsMessage]],\n    decoder: Optional[AsyncCustomDecoder[NatsMessage]],\n)\n
Source code in faststream/nats/producer.py
def __init__(\n    self,\n    connection: JetStreamContext,\n    parser: Optional[AsyncCustomParser[Msg, NatsMessage]],\n    decoder: Optional[AsyncCustomDecoder[NatsMessage]],\n) -> None:\n    self._connection = connection\n    self._parser = resolve_custom_func(parser, Parser.parse_message)\n    self._decoder = resolve_custom_func(decoder, Parser.decode_message)\n
","boost":0.5},{"location":"api/faststream/nats/producer/NatsJSFastProducer/#faststream.nats.producer.NatsJSFastProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    stream: Optional[str] = None,\n    timeout: Optional[float] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/producer.py
async def publish(\n    self,\n    message: SendableMessage,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    stream: Optional[str] = None,\n    timeout: Optional[float] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    payload, content_type = encode_message(message)\n\n    headers_to_send = {\n        \"content-type\": content_type or \"\",\n        \"correlation_id\": correlation_id or str(uuid4()),\n        **(headers or {}),\n    }\n\n    if rpc:\n        if reply_to:\n            raise WRONG_PUBLISH_ARGS\n\n        reply_to = str(uuid4())\n        future: asyncio.Future[Msg] = asyncio.Future()\n        sub = await self._connection._nc.subscribe(\n            reply_to, future=future, max_msgs=1\n        )\n        await sub.unsubscribe(limit=1)\n\n    if reply_to:\n        headers_to_send.update({\"reply_to\": reply_to})\n\n    await self._connection.publish(\n        subject=subject,\n        payload=payload,\n        headers=headers_to_send,\n        stream=stream,\n        timeout=timeout,\n    )\n\n    if rpc:\n        msg: Any = None\n        with timeout_scope(rpc_timeout, raise_timeout):\n            msg = await future\n\n        if msg:  # pragma: no branch\n            if msg.headers:  # pragma: no cover\n                if (\n                    msg.headers.get(nats.js.api.Header.STATUS)\n                    == nats.aio.client.NO_RESPONDERS_STATUS\n                ):\n                    raise nats.errors.NoRespondersError\n            return await self._decoder(await self._parser(msg))\n\n    return None\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/","title":"LogicPublisher","text":"","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher","title":"faststream.nats.publisher.LogicPublisher dataclass","text":"

Bases: BasePublisher[Msg]

","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.stream","title":"stream class-attribute instance-attribute","text":"
stream: Optional[JStream] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.subject","title":"subject class-attribute instance-attribute","text":"
subject: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: Optional[float] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.publish","title":"publish async","text":"
publish(\n    message: SendableMessage = \"\",\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[Dict[str, str]] = None,\n    **producer_kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/nats/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage = \"\",\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[Dict[str, str]] = None,\n    **producer_kwargs: Any,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    assert self.subject, \"You have to specify outgoing subject\"  # nosec B101\n\n    extra: AnyDict = {\n        \"reply_to\": reply_to or self.reply_to,\n    }\n    if self.stream is not None:\n        extra.update(\n            {\n                \"stream\": self.stream.name,\n                \"timeout\": self.timeout,\n            }\n        )\n\n    return await self._producer.publish(\n        message=message,\n        subject=self.subject,\n        headers=headers or self.headers,\n        correlation_id=correlation_id,\n        **extra,\n        **producer_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/nats/publisher/LogicPublisher/#faststream.nats.publisher.LogicPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/nats/pull_sub/PullSub/","title":"PullSub","text":"","boost":0.5},{"location":"api/faststream/nats/pull_sub/PullSub/#faststream.nats.pull_sub.PullSub","title":"faststream.nats.pull_sub.PullSub","text":"
PullSub(\n    batch_size: int = 1,\n    timeout: Optional[float] = 5.0,\n    batch: bool = False,\n)\n

Bases: BaseModel

Source code in faststream/nats/pull_sub.py
def __init__(\n    self,\n    batch_size: int = 1,\n    timeout: Optional[float] = 5.0,\n    batch: bool = False,\n) -> None:\n    super().__init__(\n        batch_size=batch_size,\n        timeout=timeout,\n        batch=batch,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/pull_sub/PullSub/#faststream.nats.pull_sub.PullSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = Field(default=False)\n
","boost":0.5},{"location":"api/faststream/nats/pull_sub/PullSub/#faststream.nats.pull_sub.PullSub.batch_size","title":"batch_size class-attribute instance-attribute","text":"
batch_size: int = Field(default=1)\n
","boost":0.5},{"location":"api/faststream/nats/pull_sub/PullSub/#faststream.nats.pull_sub.PullSub.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: Optional[float] = Field(default=5.0)\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/","title":"NatsRouter","text":"","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter","title":"faststream.nats.router.NatsRouter","text":"
NatsRouter(\n    prefix: str = \"\",\n    handlers: Sequence[NatsRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: NatsRouter

Source code in faststream/nats/router.py
    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.publisher","title":"publisher","text":"
publisher(\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/nats/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    subject: str,\n    headers: Optional[Dict[str, str]] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            subject=subject,\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/nats/router/NatsRouter/#faststream.nats.router.NatsRouter.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str,\n    queue: str = \"\",\n    pending_msgs_limit: Optional[int] = None,\n    pending_bytes_limit: Optional[int] = None,\n    max_msgs: int = 0,\n    ack_first: bool = False,\n    stream: Union[str, JStream, None] = None,\n    durable: Optional[str] = None,\n    config: Optional[api.ConsumerConfig] = None,\n    ordered_consumer: bool = False,\n    idle_heartbeat: Optional[float] = None,\n    flow_control: bool = False,\n    deliver_policy: Optional[api.DeliverPolicy] = None,\n    headers_only: Optional[bool] = None,\n    pull_sub: Optional[PullSub] = None,\n    inbox_prefix: bytes = api.INBOX_PREFIX,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[Msg, NatsMessage]] = None,\n    decoder: Optional[CustomDecoder[NatsMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[Msg], BaseMiddleware]]\n    ] = None,\n    filter: Filter[NatsMessage] = default_filter,\n    retry: bool = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
","boost":0.5},{"location":"api/faststream/nats/security/parse_security/","title":"parse_security","text":"","boost":0.5},{"location":"api/faststream/nats/security/parse_security/#faststream.nats.security.parse_security","title":"faststream.nats.security.parse_security","text":"
parse_security(security: Optional[BaseSecurity]) -> AnyDict\n
Source code in faststream/nats/security.py
def parse_security(security: Optional[BaseSecurity]) -> AnyDict:\n    if security is None:\n        return {}\n    elif isinstance(security, SASLPlaintext):\n        return _parse_sasl_plaintext(security)\n    elif isinstance(security, BaseSecurity):\n        return _parse_base_security(security)\n    else:\n        raise NotImplementedError(f\"NatsBroker does not support {type(security)}\")\n
","boost":0.5},{"location":"api/faststream/nats/shared/logging/NatsLoggingMixin/","title":"NatsLoggingMixin","text":"","boost":0.5},{"location":"api/faststream/nats/shared/logging/NatsLoggingMixin/#faststream.nats.shared.logging.NatsLoggingMixin","title":"faststream.nats.shared.logging.NatsLoggingMixin","text":"
NatsLoggingMixin(\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any\n)\n

Bases: LoggingMixin

Source code in faststream/nats/shared/logging.py
def __init__(\n    self,\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any,\n) -> None:\n    super().__init__(\n        *args,\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n        **kwargs,\n    )\n    self._max_queue_len = 0\n    self._max_stream_len = 0\n    self._max_subject_len = 4\n
","boost":0.5},{"location":"api/faststream/nats/shared/logging/NatsLoggingMixin/#faststream.nats.shared.logging.NatsLoggingMixin.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/nats/shared/logging/NatsLoggingMixin/#faststream.nats.shared.logging.NatsLoggingMixin.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/nats/shared/logging/NatsLoggingMixin/#faststream.nats.shared.logging.NatsLoggingMixin.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRoute/","title":"NatsRoute","text":"","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/","title":"NatsRouter","text":"","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter","title":"faststream.nats.shared.router.NatsRouter","text":"
NatsRouter(\n    prefix: str = \"\",\n    handlers: Sequence[NatsRoute] = (),\n    **kwargs: Any\n)\n

Bases: BrokerRouter[str, Msg]

Source code in faststream/nats/shared/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[NatsRoute[Msg, SendableMessage]] = (),\n    **kwargs: Any,\n) -> None:\n    for h in handlers:\n        if not (subj := h.kwargs.pop(\"subject\", None)):\n            subj, h.args = h.args[0], h.args[1:]\n        h.args = (prefix + subj, *h.args)\n    super().__init__(prefix, handlers, **kwargs)\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/nats/shared/router/NatsRouter/#faststream.nats.shared.router.NatsRouter.subscriber","title":"subscriber","text":"
subscriber(\n    subject: str, **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Msg, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/nats/shared/router.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    subject: str,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[Msg, P_HandlerParams, T_HandlerReturn],\n]:\n    return self._wrap_subscriber(\n        self.prefix + subject,\n        **broker_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/nats/test/FakeProducer/","title":"FakeProducer","text":"","boost":0.5},{"location":"api/faststream/nats/test/FakeProducer/#faststream.nats.test.FakeProducer","title":"faststream.nats.test.FakeProducer","text":"
FakeProducer(broker: NatsBroker)\n

Bases: NatsFastProducer

Source code in faststream/nats/test.py
def __init__(self, broker: NatsBroker) -> None:\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/nats/test/FakeProducer/#faststream.nats.test.FakeProducer.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/nats/test/FakeProducer/#faststream.nats.test.FakeProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    subject: str,\n    reply_to: str = \"\",\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    timeout: Optional[float] = None,\n    stream: Optional[str] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False\n) -> Optional[SendableMessage]\n
Source code in faststream/nats/test.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage,\n    subject: str,\n    reply_to: str = \"\",\n    headers: Optional[Dict[str, str]] = None,\n    correlation_id: Optional[str] = None,\n    # NatsJSFastProducer compatibility\n    timeout: Optional[float] = None,\n    stream: Optional[str] = None,\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = None,\n    raise_timeout: bool = False,\n) -> Optional[SendableMessage]:\n    incoming = build_message(\n        message=message,\n        subject=subject,\n        headers=headers,\n        correlation_id=correlation_id,\n        reply_to=reply_to,\n    )\n\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        call = False\n\n        if stream and getattr(handler.stream, \"name\", None) != stream:\n            continue\n\n        if subject == handler.subject:\n            call = True\n\n        else:\n            call = True\n\n            for current, base in zip_longest(\n                subject.split(\".\"),\n                handler.subject.split(\".\"),\n                fillvalue=None,\n            ):\n                if base == \">\":\n                    break\n\n                if base != \"*\" and current != base:\n                    call = False\n                    break\n\n        if call:\n            r = await call_handler(\n                handler=handler,\n                message=[incoming]\n                if getattr(handler.pull_sub, \"batch\", False)\n                else incoming,\n                rpc=rpc,\n                rpc_timeout=rpc_timeout,\n                raise_timeout=raise_timeout,\n            )\n\n            if rpc:\n                return r\n\n    return None\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/","title":"PatchedMessage","text":"","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage","title":"faststream.nats.test.PatchedMessage","text":"

Bases: Msg

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.data","title":"data class-attribute instance-attribute","text":"
data: bytes = b''\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.header","title":"header property","text":"
header: Optional[Dict[str, str]]\n

header returns the headers from a message.

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[Dict[str, str]] = None\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.metadata","title":"metadata property","text":"
metadata: Metadata\n

metadata returns the Metadata of a JetStream message.

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.reply","title":"reply class-attribute instance-attribute","text":"
reply: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.sid","title":"sid property","text":"
sid: int\n

sid returns the subscription ID from a message.

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.subject","title":"subject class-attribute instance-attribute","text":"
subject: str = ''\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack","title":"Ack","text":"","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.AccHash","title":"AccHash class-attribute instance-attribute","text":"
AccHash = 3\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Ack","title":"Ack class-attribute instance-attribute","text":"
Ack = b'+ACK'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Consumer","title":"Consumer class-attribute instance-attribute","text":"
Consumer = 5\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.ConsumerSeq","title":"ConsumerSeq class-attribute instance-attribute","text":"
ConsumerSeq = 8\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Domain","title":"Domain class-attribute instance-attribute","text":"
Domain = 2\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Nak","title":"Nak class-attribute instance-attribute","text":"
Nak = b'-NAK'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.NumDelivered","title":"NumDelivered class-attribute instance-attribute","text":"
NumDelivered = 6\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.NumPending","title":"NumPending class-attribute instance-attribute","text":"
NumPending = 10\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Prefix0","title":"Prefix0 class-attribute instance-attribute","text":"
Prefix0 = '$JS'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Prefix1","title":"Prefix1 class-attribute instance-attribute","text":"
Prefix1 = 'ACK'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Progress","title":"Progress class-attribute instance-attribute","text":"
Progress = b'+WPI'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Stream","title":"Stream class-attribute instance-attribute","text":"
Stream = 4\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.StreamSeq","title":"StreamSeq class-attribute instance-attribute","text":"
StreamSeq = 7\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Term","title":"Term class-attribute instance-attribute","text":"
Term = b'+TERM'\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Ack.Timestamp","title":"Timestamp class-attribute instance-attribute","text":"
Timestamp = 9\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata","title":"Metadata dataclass","text":"

Metadata is the metadata from a JetStream message.

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.consumer","title":"consumer instance-attribute","text":"
consumer: str\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.domain","title":"domain class-attribute instance-attribute","text":"
domain: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.num_delivered","title":"num_delivered instance-attribute","text":"
num_delivered: int\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.num_pending","title":"num_pending instance-attribute","text":"
num_pending: int\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.sequence","title":"sequence instance-attribute","text":"
sequence: SequencePair\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.stream","title":"stream instance-attribute","text":"
stream: str\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.timestamp","title":"timestamp instance-attribute","text":"
timestamp: datetime.datetime\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.SequencePair","title":"SequencePair dataclass","text":"

SequencePair represents a pair of consumer and stream sequence.

","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.SequencePair.consumer","title":"consumer instance-attribute","text":"
consumer: int\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.Metadata.SequencePair.stream","title":"stream instance-attribute","text":"
stream: int\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.ack","title":"ack async","text":"
ack() -> None\n
Source code in faststream/nats/test.py
async def ack(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.ack_sync","title":"ack_sync async","text":"
ack_sync(timeout: float = 1) -> PatchedMessage\n
Source code in faststream/nats/test.py
async def ack_sync(\n    self, timeout: float = 1\n) -> \"PatchedMessage\":  # pragma: no cover\n    return self\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.in_progress","title":"in_progress async","text":"
in_progress() -> None\n
Source code in faststream/nats/test.py
async def in_progress(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.nak","title":"nak async","text":"
nak(delay: Union[int, float, None] = None) -> None\n
Source code in faststream/nats/test.py
async def nak(self, delay: Union[int, float, None] = None) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.respond","title":"respond async","text":"
respond(data: bytes) -> None\n

respond replies to the inbox of the message if there is one.

Source code in nats/aio/msg.py
async def respond(self, data: bytes) -> None:\n    \"\"\"\n    respond replies to the inbox of the message if there is one.\n    \"\"\"\n    if not self.reply:\n        raise Error('no reply subject available')\n    if not self._client:\n        raise Error('client not set')\n\n    await self._client.publish(self.reply, data, headers=self.headers)\n
","boost":0.5},{"location":"api/faststream/nats/test/PatchedMessage/#faststream.nats.test.PatchedMessage.term","title":"term async","text":"
term() -> None\n
Source code in faststream/nats/test.py
async def term(self) -> None:\n    pass\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/","title":"TestNatsBroker","text":"","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker","title":"faststream.nats.test.TestNatsBroker","text":"
TestNatsBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[NatsBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/nats/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: NatsBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(publisher.subject, _raw=True)\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(broker: NatsBroker, publisher: Any) -> None\n
Source code in faststream/nats/test.py
@staticmethod\ndef patch_publisher(broker: NatsBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/nats/test/TestNatsBroker/#faststream.nats.test.TestNatsBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> None\n
Source code in faststream/nats/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: NatsBroker, publisher: Publisher\n) -> None:\n    broker.handlers.pop(Handler.get_routing_hash(publisher.subject), None)\n
","boost":0.5},{"location":"api/faststream/nats/test/build_message/","title":"build_message","text":"","boost":0.5},{"location":"api/faststream/nats/test/build_message/#faststream.nats.test.build_message","title":"faststream.nats.test.build_message","text":"
build_message(\n    message: SendableMessage,\n    subject: str,\n    *,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[AnyDict] = None\n) -> PatchedMessage\n
Source code in faststream/nats/test.py
def build_message(\n    message: SendableMessage,\n    subject: str,\n    *,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[AnyDict] = None,\n) -> \"PatchedMessage\":\n    msg, content_type = encode_message(message)\n    return PatchedMessage(\n        _client=None,  # type: ignore\n        subject=subject,\n        reply=reply_to,\n        data=msg,\n        headers={\n            \"content-type\": content_type or \"\",\n            \"correlation_id\": correlation_id or str(uuid4()),\n            **(headers or {}),\n        },\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/","title":"ExchangeType","text":"","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType","title":"faststream.rabbit.ExchangeType","text":"

Bases: str, Enum

A class to represent the exchange type.

","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.DIRECT","title":"DIRECT class-attribute instance-attribute","text":"
DIRECT = 'direct'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.FANOUT","title":"FANOUT class-attribute instance-attribute","text":"
FANOUT = 'fanout'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.HEADERS","title":"HEADERS class-attribute instance-attribute","text":"
HEADERS = 'headers'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.TOPIC","title":"TOPIC class-attribute instance-attribute","text":"
TOPIC = 'topic'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.X_CONSISTENT_HASH","title":"X_CONSISTENT_HASH class-attribute instance-attribute","text":"
X_CONSISTENT_HASH = 'x-consistent-hash'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.X_DELAYED_MESSAGE","title":"X_DELAYED_MESSAGE class-attribute instance-attribute","text":"
X_DELAYED_MESSAGE = 'x-delayed-message'\n
","boost":0.5},{"location":"api/faststream/rabbit/ExchangeType/#faststream.rabbit.ExchangeType.X_MODULUS_HASH","title":"X_MODULUS_HASH class-attribute instance-attribute","text":"
X_MODULUS_HASH = 'x-modulus-hash'\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/","title":"RabbitBroker","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker","title":"faststream.rabbit.RabbitBroker","text":"
RabbitBroker(\n    url: Union[\n        str, URL, None\n    ] = \"amqp://guest:guest@localhost:5672/\",\n    *,\n    host: str = None,\n    port: int = None,\n    login: str = None,\n    password: str = None,\n    virtualhost: str = None,\n    ssl_options: Optional[aio_pika.abc.SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    max_consumers: Optional[int] = None,\n    protocol: str = None,\n    protocol_version: Optional[str] = \"0.9.1\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: RabbitLoggingMixin, BrokerAsyncUsecase[IncomingMessage, RobustConnection]

A RabbitMQ broker for FastAPI applications.

This class extends the base BrokerAsyncUsecase and provides asynchronous support for RabbitMQ as a message broker.

PARAMETER DESCRIPTION url

The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".

TYPE: Union[str, URL, None] DEFAULT: 'amqp://guest:guest@localhost:5672/'

max_consumers

Maximum number of consumers to limit message consumption. Defaults to None.

TYPE: Optional[int] DEFAULT: None

protocol

The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".

TYPE: str DEFAULT: None

protocol_version

The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".

TYPE: Optional[str] DEFAULT: '0.9.1'

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Initialize the RabbitBroker.

PARAMETER DESCRIPTION url

The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".

TYPE: Union[str, URL, None] DEFAULT: 'amqp://guest:guest@localhost:5672/'

max_consumers

Maximum number of consumers to limit message consumption. Defaults to None.

TYPE: Optional[int] DEFAULT: None

protocol

The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".

TYPE: str DEFAULT: None

protocol_version

The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".

TYPE: Optional[str] DEFAULT: '0.9.1'

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/rabbit/broker.py
def __init__(\n    self,\n    url: Union[str, URL, None] = \"amqp://guest:guest@localhost:5672/\",\n    *,\n    # connection args\n    host: Optional[str] = None,\n    port: Optional[int] = None,\n    login: Optional[str] = None,\n    password: Optional[str] = None,\n    virtualhost: Optional[str] = None,\n    ssl_options: Optional[SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    # broker args\n    max_consumers: Optional[int] = None,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"0.9.1\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Initialize the RabbitBroker.\n\n    Args:\n        url (Union[str, URL, None], optional): The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".\n        max_consumers (Optional[int], optional): Maximum number of consumers to limit message consumption. Defaults to None.\n        protocol (str, optional): The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".\n        protocol_version (Optional[str], optional): The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".\n        **kwargs: Additional keyword arguments.\n    \"\"\"\n    security_args = parse_security(security)\n\n    if (ssl := kwargs.get(\"ssl\")) or kwargs.get(\"ssl_context\"):  # pragma: no cover\n        warnings.warn(\n            (\n                f\"\\nRabbitMQ {'`ssl`' if ssl else '`ssl_context`'} option was deprecated and will be removed in 0.4.0\"\n                \"\\nPlease, use `security` with `BaseSecurity` or `SASLPlaintext` instead\"\n            ),\n            DeprecationWarning,\n            stacklevel=2,\n        )\n\n    amqp_url = build_url(\n        url,\n        host=host,\n        port=port,\n        login=security_args.get(\"login\", login),\n        password=security_args.get(\"password\", password),\n        virtualhost=virtualhost,\n        ssl=security_args.get(\"ssl\", kwargs.pop(\"ssl\", False)),\n        ssl_options=ssl_options,\n        client_properties=client_properties,\n    )\n\n    super().__init__(\n        url=str(amqp_url),\n        protocol_version=protocol_version,\n        security=security,\n        ssl_context=security_args.get(\n            \"ssl_context\",\n            kwargs.pop(\"ssl_context\", None),\n        ),\n        **kwargs,\n    )\n\n    # respect ascynapi_url argument scheme\n    asyncapi_url = build_url(self.url)\n    self.protocol = protocol or asyncapi_url.scheme\n    self.virtual_host = asyncapi_url.path\n\n    self._max_consumers = max_consumers\n\n    self._channel = None\n    self.declarer = None\n    self._producer = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.declarer","title":"declarer instance-attribute","text":"
declarer: Optional[RabbitDeclarer] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[int, Handler]\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol or asyncapi_url.scheme\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.virtual_host","title":"virtual_host instance-attribute","text":"
virtual_host = asyncapi_url.path\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.connect","title":"connect async","text":"
connect(\n    *args: Any, **kwargs: Any\n) -> aio_pika.RobustConnection\n

Connect to the RabbitMQ server.

PARAMETER DESCRIPTION *args

Additional positional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION RobustConnection

aio_pika.RobustConnection: The RabbitMQ connection instance.

Source code in faststream/rabbit/broker.py
async def connect(self, *args: Any, **kwargs: Any) -> aio_pika.RobustConnection:\n    \"\"\"\n    Connect to the RabbitMQ server.\n\n    Args:\n        *args: Additional positional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        aio_pika.RobustConnection: The RabbitMQ connection instance.\n    \"\"\"\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.declare_exchange","title":"declare_exchange async","text":"
declare_exchange(\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange\n

Declare a RabbitMQ exchange.

PARAMETER DESCRIPTION exchange

The RabbitMQ exchange to declare.

TYPE: RabbitExchange

RETURNS DESCRIPTION RobustExchange

aio_pika.RobustExchange: The declared RabbitMQ exchange.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def declare_exchange(\n    self,\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange:\n    \"\"\"\n    Declare a RabbitMQ exchange.\n\n    Args:\n        exchange (RabbitExchange): The RabbitMQ exchange to declare.\n\n    Returns:\n        aio_pika.RobustExchange: The declared RabbitMQ exchange.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n    return await self.declarer.declare_exchange(exchange)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.declare_queue","title":"declare_queue async","text":"
declare_queue(queue: RabbitQueue) -> aio_pika.RobustQueue\n

Declare a RabbitMQ queue.

PARAMETER DESCRIPTION queue

The RabbitMQ queue to declare.

TYPE: RabbitQueue

RETURNS DESCRIPTION RobustQueue

aio_pika.RobustQueue: The declared RabbitMQ queue.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def declare_queue(\n    self,\n    queue: RabbitQueue,\n) -> aio_pika.RobustQueue:\n    \"\"\"\n    Declare a RabbitMQ queue.\n\n    Args:\n        queue (RabbitQueue): The RabbitMQ queue to declare.\n\n    Returns:\n        aio_pika.RobustQueue: The declared RabbitMQ queue.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n    return await self.declarer.declare_queue(queue)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, **kwargs: Any\n) -> Union[\n    aiormq.abc.ConfirmationFrameType, SendableMessage\n]\n

Publish a message to the RabbitMQ broker.

PARAMETER DESCRIPTION *args

Additional positional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Union[ConfirmationFrameType, SendableMessage]

Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The confirmation frame or the response message.

Source code in faststream/rabbit/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Union[aiormq.abc.ConfirmationFrameType, SendableMessage]:\n    \"\"\"\n    Publish a message to the RabbitMQ broker.\n\n    Args:\n        *args: Additional positional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The confirmation frame or the response message.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.publisher","title":"publisher","text":"
publisher(\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Publisher\n

Define a message publisher.

PARAMETER DESCRIPTION queue

The name of the RabbitMQ queue. Defaults to \"\".

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The name of the RabbitMQ exchange. Defaults to None.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key for messages. Defaults to \"\".

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory. Defaults to True.

TYPE: bool DEFAULT: True

immediate

Whether the message should be sent immediately. Defaults to False.

TYPE: bool DEFAULT: False

timeout

Timeout for message publishing. Defaults to None.

TYPE: TimeoutType DEFAULT: None

persist

Whether to persist messages. Defaults to False.

TYPE: bool DEFAULT: False

reply_to

The reply-to queue name. Defaults to None.

TYPE: Optional[str] DEFAULT: None

title

Title for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

description

Description for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional message properties and content.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Publisher

A message publisher instance.

TYPE: Publisher

Source code in faststream/rabbit/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Publisher:\n    \"\"\"\n    Define a message publisher.\n\n    Args:\n        queue (Union[RabbitQueue, str], optional): The name of the RabbitMQ queue. Defaults to \"\".\n        exchange (Union[RabbitExchange, str, None], optional): The name of the RabbitMQ exchange. Defaults to None.\n        routing_key (str, optional): The routing key for messages. Defaults to \"\".\n        mandatory (bool, optional): Whether the message is mandatory. Defaults to True.\n        immediate (bool, optional): Whether the message should be sent immediately. Defaults to False.\n        timeout (TimeoutType, optional): Timeout for message publishing. Defaults to None.\n        persist (bool, optional): Whether to persist messages. Defaults to False.\n        reply_to (Optional[str], optional): The reply-to queue name. Defaults to None.\n        title (Optional[str]): Title for AsyncAPI docs.\n        description (Optional[str]): Description for AsyncAPI docs.\n        **message_kwargs (Any): Additional message properties and content.\n\n    Returns:\n        Publisher: A message publisher instance.\n    \"\"\"\n    q, ex = RabbitQueue.validate(queue), RabbitExchange.validate(exchange)\n\n    publisher = Publisher(\n        title=title,\n        queue=q,\n        exchange=ex,\n        routing_key=routing_key,\n        mandatory=mandatory,\n        immediate=immediate,\n        timeout=timeout,\n        persist=persist,\n        reply_to=reply_to,\n        priority=priority,\n        message_kwargs=message_kwargs,\n        _description=description,\n        _schema=schema,\n        virtual_host=self.virtual_host,\n        include_in_schema=include_in_schema,\n    )\n\n    key = publisher._get_routing_hash()\n    publisher = self._publishers.get(key, publisher)\n    super().publisher(key, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.start","title":"start async","text":"
start() -> None\n

Start the RabbitMQ broker.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def start(self) -> None:\n    \"\"\"\n    Start the RabbitMQ broker.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, RabbitQueue(\"\"), RabbitExchange(\"\")),\n    )\n\n    await super().start()\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n\n    for publisher in self._publishers.values():\n        if publisher.exchange is not None:\n            await self.declare_exchange(publisher.exchange)\n\n    for handler in self.handlers.values():\n        c = self._get_log_context(None, handler.queue, handler.exchange)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self.declarer)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitBroker/#faststream.rabbit.RabbitBroker.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Filter[RabbitMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n

Decorator to define a message subscriber.

PARAMETER DESCRIPTION queue

The name of the RabbitMQ queue.

TYPE: Union[str, RabbitQueue]

exchange

The name of the RabbitMQ exchange. Defaults to None.

TYPE: Union[str, RabbitExchange, None] DEFAULT: None

consume_args

Additional arguments for message consumption.

TYPE: Optional[AnyDict] DEFAULT: None

no_ack

Whether not to ack/nack/reject messages.

TYPE: bool DEFAULT: False

title

Title for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

description

Description for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION Callable

A decorator function for defining message subscribers.

TYPE: Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn]]

Source code in faststream/rabbit/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[aio_pika.IncomingMessage, RabbitMessage]] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[aio_pika.IncomingMessage], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RabbitMessage] = default_filter,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"\n    Decorator to define a message subscriber.\n\n    Args:\n        queue (Union[str, RabbitQueue]): The name of the RabbitMQ queue.\n        exchange (Union[str, RabbitExchange, None], optional): The name of the RabbitMQ exchange. Defaults to None.\n        consume_args (Optional[AnyDict], optional): Additional arguments for message consumption.\n        no_ack (bool): Whether not to ack/nack/reject messages.\n        title (Optional[str]): Title for AsyncAPI docs.\n        description (Optional[str]): Description for AsyncAPI docs.\n\n    Returns:\n        Callable: A decorator function for defining message subscribers.\n    \"\"\"\n    super().subscriber()\n\n    r_queue = RabbitQueue.validate(queue)\n    r_exchange = RabbitExchange.validate(exchange)\n\n    self._setup_log_context(r_queue, r_exchange)\n\n    key = get_routing_hash(r_queue, r_exchange)\n    handler = self.handlers.get(\n        key,\n        Handler(\n            log_context_builder=partial(\n                self._get_log_context, queue=r_queue, exchange=r_exchange\n            ),\n            queue=r_queue,\n            exchange=r_exchange,\n            consume_args=consume_args,\n            description=description,\n            title=title,\n            virtual_host=self.virtual_host,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n        ),\n    )\n\n    self.handlers[key] = handler\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[\n        aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn\n    ]:\n        \"\"\"Wraps a consumer function with additional functionality.\n\n        Args:\n            func: The consumer function to be wrapped.\n\n        Returns:\n            The wrapped consumer function.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            _process_kwargs={\n                \"reply_config\": reply_config,\n            },\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/","title":"RabbitExchange","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange","title":"faststream.rabbit.RabbitExchange","text":"
RabbitExchange(\n    name: str,\n    type: ExchangeType = ExchangeType.DIRECT,\n    durable: bool = False,\n    auto_delete: bool = False,\n    internal: bool = False,\n    passive: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_to: Optional[RabbitExchange] = None,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n)\n

Bases: NameRequired

A class to represent a RabbitMQ exchange.

METHOD DESCRIPTION __hash__

returns the hash value of the exchange

__init__

initializes the RabbitExchange object

Initialize a RabbitExchange object.

PARAMETER DESCRIPTION name

Name of the exchange.

TYPE: str

type

Type of the exchange. Defaults to ExchangeType.DIRECT.

TYPE: ExchangeType DEFAULT: DIRECT

durable

Whether the exchange should survive broker restarts. Defaults to False.

TYPE: bool DEFAULT: False

auto_delete

Whether the exchange should be deleted when no longer in use. Defaults to False.

TYPE: bool DEFAULT: False

internal

Whether the exchange is used for internal purposes and should not be published to directly. Defaults to False.

TYPE: bool DEFAULT: False

passive

Whether to check if the exchange exists before creating it. Defaults to False.

TYPE: bool DEFAULT: False

arguments

Additional arguments for the exchange. Defaults to None.

TYPE: Optional[AnyDict] DEFAULT: None

timeout

Timeout for the operation. Defaults to None.

TYPE: TimeoutType DEFAULT: None

robust

Whether to use robust mode for the exchange. Defaults to True.

TYPE: bool DEFAULT: True

bind_to

Exchange to bind to. Defaults to None.

TYPE: Optional[RabbitExchange] DEFAULT: None

bind_arguments

Arguments for the binding. Defaults to None.

TYPE: Optional[AnyDict] DEFAULT: None

routing_key

Routing key for the exchange. Defaults to \"\".

TYPE: str DEFAULT: ''

RAISES DESCRIPTION NotImplementedError Source code in faststream/rabbit/shared/schemas.py
def __init__(\n    self,\n    name: str,\n    type: ExchangeType = ExchangeType.DIRECT,\n    durable: bool = False,\n    auto_delete: bool = False,\n    internal: bool = False,\n    passive: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_to: Optional[\"RabbitExchange\"] = None,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n) -> None:\n    \"\"\"Initialize a RabbitExchange object.\n\n    Args:\n        name (str): Name of the exchange.\n        type (ExchangeType, optional): Type of the exchange. Defaults to ExchangeType.DIRECT.\n        durable (bool, optional): Whether the exchange should survive broker restarts. Defaults to False.\n        auto_delete (bool, optional): Whether the exchange should be deleted when no longer in use. Defaults to False.\n        internal (bool, optional): Whether the exchange is used for internal purposes and should not be published to directly. Defaults to False.\n        passive (bool, optional): Whether to check if the exchange exists before creating it. Defaults to False.\n        arguments (Optional[AnyDict], optional): Additional arguments for the exchange. Defaults to None.\n        timeout (TimeoutType, optional): Timeout for the operation. Defaults to None.\n        robust (bool, optional): Whether to use robust mode for the exchange. Defaults to True.\n        bind_to (Optional[\"RabbitExchange\"], optional): Exchange to bind to. Defaults to None.\n        bind_arguments (Optional[AnyDict], optional): Arguments for the binding. Defaults to None.\n        routing_key (str, optional): Routing key for the exchange. Defaults to \"\".\n\n    Raises:\n        NotImplementedError:\n\n    \"\"\"\n    if routing_key and bind_to is None:  # pragma: no cover\n        warnings.warn(\n            (\n                \"\\nRabbitExchange `routing_key` is using to bind exchange to another one\"\n                \"\\nIt can be used only with the `bind_to` argument, please setup it too\"\n            ),\n            category=RuntimeWarning,\n            stacklevel=1,\n        )\n\n    super().__init__(\n        name=name,\n        type=type.value,\n        durable=durable,\n        auto_delete=auto_delete,\n        routing_key=routing_key,\n        bind_to=bind_to,\n        bind_arguments=bind_arguments,\n        robust=robust,\n        internal=internal,\n        passive=passive,\n        timeout=timeout,\n        arguments=arguments,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.arguments","title":"arguments class-attribute instance-attribute","text":"
arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.auto_delete","title":"auto_delete class-attribute instance-attribute","text":"
auto_delete: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.bind_arguments","title":"bind_arguments class-attribute instance-attribute","text":"
bind_arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.bind_to","title":"bind_to class-attribute instance-attribute","text":"
bind_to: Optional[RabbitExchange] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.durable","title":"durable class-attribute instance-attribute","text":"
durable: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.internal","title":"internal class-attribute instance-attribute","text":"
internal: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.passive","title":"passive class-attribute instance-attribute","text":"
passive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.robust","title":"robust class-attribute instance-attribute","text":"
robust: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.type","title":"type class-attribute instance-attribute","text":"
type: str = ExchangeType.DIRECT.value\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitExchange/#faststream.rabbit.RabbitExchange.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/","title":"RabbitQueue","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue","title":"faststream.rabbit.RabbitQueue","text":"
RabbitQueue(\n    name: str,\n    durable: bool = False,\n    exclusive: bool = False,\n    passive: bool = False,\n    auto_delete: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n)\n

Bases: NameRequired

A class to represent a RabbitMQ queue.

METHOD DESCRIPTION __hash__

returns the hash value of the queue

routing

returns the routing key of the queue

__init__

initializes the RabbitQueue object with the given parameters

Initialize a class object.

PARAMETER DESCRIPTION name

The name of the object.

TYPE: str

durable

Whether the object is durable. Defaults to False.

TYPE: bool DEFAULT: False

exclusive

Whether the object is exclusive. Defaults to False.

TYPE: bool DEFAULT: False

passive

Whether the object is passive. Defaults to False.

TYPE: bool DEFAULT: False

auto_delete

Whether the object is auto delete. Defaults to False.

TYPE: bool DEFAULT: False

arguments

Additional arguments for the object. Defaults to None.

TYPE: dict DEFAULT: None

timeout

Timeout for the object. Defaults to None.

TYPE: TimeoutType DEFAULT: None

robust

Whether the object is robust. Defaults to True.

TYPE: bool DEFAULT: True

bind_arguments

Bind arguments for the object. Defaults to None.

TYPE: dict DEFAULT: None

routing_key

Routing key for the object. Defaults to \"\".

TYPE: str DEFAULT: ''

Source code in faststream/rabbit/shared/schemas.py
def __init__(\n    self,\n    name: str,\n    durable: bool = False,\n    exclusive: bool = False,\n    passive: bool = False,\n    auto_delete: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n) -> None:\n    \"\"\"Initialize a class object.\n\n    Args:\n        name (str): The name of the object.\n        durable (bool, optional): Whether the object is durable. Defaults to False.\n        exclusive (bool, optional): Whether the object is exclusive. Defaults to False.\n        passive (bool, optional): Whether the object is passive. Defaults to False.\n        auto_delete (bool, optional): Whether the object is auto delete. Defaults to False.\n        arguments (dict, optional): Additional arguments for the object. Defaults to None.\n        timeout (TimeoutType, optional): Timeout for the object. Defaults to None.\n        robust (bool, optional): Whether the object is robust. Defaults to True.\n        bind_arguments (dict, optional): Bind arguments for the object. Defaults to None.\n        routing_key (str, optional): Routing key for the object. Defaults to \"\".\n\n    \"\"\"\n    re, routing_key = compile_path(routing_key, replace_symbol=\"*\")\n    super().__init__(\n        name=name,\n        path_regex=re,\n        durable=durable,\n        exclusive=exclusive,\n        bind_arguments=bind_arguments,\n        routing_key=routing_key,\n        robust=robust,\n        passive=passive,\n        auto_delete=auto_delete,\n        arguments=arguments,\n        timeout=timeout,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.arguments","title":"arguments class-attribute instance-attribute","text":"
arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.auto_delete","title":"auto_delete class-attribute instance-attribute","text":"
auto_delete: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.bind_arguments","title":"bind_arguments class-attribute instance-attribute","text":"
bind_arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.durable","title":"durable class-attribute instance-attribute","text":"
durable: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.exclusive","title":"exclusive class-attribute instance-attribute","text":"
exclusive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'arbitrary_types_allowed': True}\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.name","title":"name class-attribute instance-attribute","text":"
name: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.passive","title":"passive class-attribute instance-attribute","text":"
passive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.path_regex","title":"path_regex class-attribute instance-attribute","text":"
path_regex: Optional[Pattern[str]] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.robust","title":"robust class-attribute instance-attribute","text":"
robust: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.routing","title":"routing property","text":"
routing: str\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.Config.arbitrary_types_allowed","title":"arbitrary_types_allowed class-attribute instance-attribute","text":"
arbitrary_types_allowed = True\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitQueue/#faststream.rabbit.RabbitQueue.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRoute/","title":"RabbitRoute","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/","title":"RabbitRouter","text":"","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter","title":"faststream.rabbit.RabbitRouter","text":"
RabbitRouter(\n    prefix: str = \"\",\n    handlers: Sequence[RabbitRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: RabbitRouter

A class representing a RabbitMQ router for publishing messages.

METHOD DESCRIPTION _get_publisher_key

Returns the key for a given Publisher object

_update_publisher_prefix

Updates the prefix of a given Publisher object

publisher

Publishes a message to RabbitMQ

Source code in faststream/rabbit/router.py
_publishers: Dict[int, Publisher]\n\n@staticmethod\ndef _get_publisher_key(publisher: Publisher) -> int:\n    \"\"\"Get the publisher key.\n\n    Args:\n        publisher: The publisher object.\n\n    Returns:\n        The publisher key as an integer.\n\n    \"\"\"\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.publisher","title":"publisher","text":"
publisher(\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Publisher\n

Publishes a message to a RabbitMQ queue or exchange.

PARAMETER DESCRIPTION queue

The RabbitMQ queue to publish the message to. Can be either a RabbitQueue object or a string representing the queue name.

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The RabbitMQ exchange to publish the message to. Can be either a RabbitExchange object, a string representing the exchange name, or None.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key to use when publishing the message.

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory or not.

TYPE: bool DEFAULT: True

immediate

Whether the message should be delivered immediately or not.

TYPE: bool DEFAULT: False

timeout

The timeout for the publish operation.

TYPE: TimeoutType DEFAULT: None

persist

Whether the message should be persisted or not.

TYPE: bool DEFAULT: False

reply_to

The reply-to address for the message.

TYPE: Optional[str] DEFAULT: None

title

The title of the message (AsyncAPI information).

TYPE: Optional[str] DEFAULT: None

description

The description of the message (AsyncAPI information).

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional keyword arguments to include in the message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Publisher

The Publisher object used to publish the message.

Source code in faststream/rabbit/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Publisher:\n    \"\"\"Publishes a message to a RabbitMQ queue or exchange.\n\n    Args:\n        queue: The RabbitMQ queue to publish the message to. Can be either a RabbitQueue object or a string representing the queue name.\n        exchange: The RabbitMQ exchange to publish the message to. Can be either a RabbitExchange object, a string representing the exchange name, or None.\n        routing_key: The routing key to use when publishing the message.\n        mandatory: Whether the message is mandatory or not.\n        immediate: Whether the message should be delivered immediately or not.\n        timeout: The timeout for the publish operation.\n        persist: Whether the message should be persisted or not.\n        reply_to: The reply-to address for the message.\n        title: The title of the message (AsyncAPI information).\n        description: The description of the message (AsyncAPI information).\n        **message_kwargs: Additional keyword arguments to include in the message.\n\n    Returns:\n        The Publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            queue=RabbitQueue.validate(queue),\n            exchange=RabbitExchange.validate(exchange),\n            routing_key=routing_key,\n            mandatory=mandatory,\n            immediate=immediate,\n            timeout=timeout,\n            persist=persist,\n            reply_to=reply_to,\n            priority=priority,\n            message_kwargs=message_kwargs,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[key] = self._publishers.get(key, new_publisher)\n    return publisher\n
","boost":0.5},{"location":"api/faststream/rabbit/RabbitRouter/#faststream.rabbit.RabbitRouter.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    dependencies: Sequence[Depends] = (),\n    filter: Filter[RabbitMessage] = default_filter,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    retry: Union[bool, int] = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n
Source code in faststream/rabbit/router.py
    Returns:\n        Publisher: The updated publisher object.\n\n    Note:\n        This function is intended to be used as a decorator.\n\n    \"\"\"\n    publisher.queue = model_copy(\n        publisher.queue, update={\"name\": prefix + publisher.queue.name}\n    )\n    return publisher\n\n@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n
","boost":0.5},{"location":"api/faststream/rabbit/ReplyConfig/","title":"ReplyConfig","text":"","boost":0.5},{"location":"api/faststream/rabbit/ReplyConfig/#faststream.rabbit.ReplyConfig","title":"faststream.rabbit.ReplyConfig","text":"

Bases: BaseModel

","boost":0.5},{"location":"api/faststream/rabbit/ReplyConfig/#faststream.rabbit.ReplyConfig.immediate","title":"immediate class-attribute instance-attribute","text":"
immediate: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/ReplyConfig/#faststream.rabbit.ReplyConfig.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/ReplyConfig/#faststream.rabbit.ReplyConfig.persist","title":"persist class-attribute instance-attribute","text":"
persist: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/rabbit/TestApp/#faststream.broker.test.TestApp","title":"faststream.broker.test.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/rabbit/TestApp/#faststream.broker.test.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/","title":"TestRabbitBroker","text":"","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker","title":"faststream.rabbit.TestRabbitBroker","text":"
TestRabbitBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[RabbitBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: RabbitBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: RabbitBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(\n        queue=publisher.queue,\n        exchange=publisher.exchange,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: RabbitBroker, publisher: Any\n) -> None\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef patch_publisher(broker: RabbitBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/rabbit/TestRabbitBroker/#faststream.rabbit.TestRabbitBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: RabbitBroker, publisher: Publisher\n) -> None\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: RabbitBroker,\n    publisher: Publisher,\n) -> None:\n    broker.handlers.pop(\n        publisher._get_routing_hash(),\n        None,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/","title":"Handler","text":"","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler","title":"faststream.rabbit.asyncapi.Handler","text":"
Handler(\n    queue: RabbitQueue,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    exchange: Optional[RabbitExchange] = None,\n    consume_args: Optional[AnyDict] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    virtual_host: str = \"/\",\n)\n

Bases: LogicHandler

A class that serves as a handler for RMQAsyncAPIChannel and LogicHandler.

METHOD DESCRIPTION - name

Returns the name of the handler.

- get_payloads

Returns a list of payloads.

Initialize a RabbitMQ consumer.

PARAMETER DESCRIPTION queue

RabbitQueue object representing the queue to consume from

TYPE: RabbitQueue

exchange

RabbitExchange object representing the exchange to bind the queue to (optional)

TYPE: Optional[RabbitExchange] DEFAULT: None

consume_args

Additional arguments for consuming from the queue (optional)

TYPE: Optional[AnyDict] DEFAULT: None

description

Description of the consumer (optional)

TYPE: Optional[str] DEFAULT: None

title

Title of the consumer (optional)

TYPE: Optional[str] DEFAULT: None

Source code in faststream/rabbit/handler.py
def __init__(\n    self,\n    queue: RabbitQueue,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # RMQ information\n    exchange: Optional[RabbitExchange] = None,\n    consume_args: Optional[AnyDict] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    virtual_host: str = \"/\",\n) -> None:\n    \"\"\"Initialize a RabbitMQ consumer.\n\n    Args:\n        queue: RabbitQueue object representing the queue to consume from\n        exchange: RabbitExchange object representing the exchange to bind the queue to (optional)\n        consume_args: Additional arguments for consuming from the queue (optional)\n        description: Description of the consumer (optional)\n        title: Title of the consumer (optional)\n\n    \"\"\"\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.queue = queue\n    self.exchange = exchange\n    self.virtual_host = virtual_host\n    self.consume_args = consume_args or {}\n\n    self._consumer_tag = None\n    self._queue_obj = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.consume_args","title":"consume_args instance-attribute","text":"
consume_args: AnyDict = consume_args or {}\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.exchange","title":"exchange instance-attribute","text":"
exchange: Optional[RabbitExchange] = exchange\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.queue","title":"queue instance-attribute","text":"
queue: RabbitQueue = queue\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.virtual_host","title":"virtual_host instance-attribute","text":"
virtual_host = virtual_host\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ],\n    decoder: Optional[CustomDecoder[RabbitMessage]],\n    filter: Filter[RabbitMessage],\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ]\n) -> None\n

Add a call to the handler.

PARAMETER DESCRIPTION handler

The handler for the call.

TYPE: HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn]

dependant

The dependant for the call.

TYPE: CallModel[P_HandlerParams, T_HandlerReturn]

parser

Optional custom parser for the call.

TYPE: Optional[CustomParser[IncomingMessage, RabbitMessage]]

decoder

Optional custom decoder for the call.

TYPE: Optional[CustomDecoder[RabbitMessage]]

filter

The filter for the call.

TYPE: Filter[RabbitMessage]

middlewares

Optional sequence of middlewares for the call.

TYPE: Optional[Sequence[Callable[[IncomingMessage], BaseMiddleware]]]

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[\n        aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[aio_pika.IncomingMessage, RabbitMessage]],\n    decoder: Optional[CustomDecoder[RabbitMessage]],\n    filter: Filter[RabbitMessage],\n    middlewares: Optional[\n        Sequence[Callable[[aio_pika.IncomingMessage], BaseMiddleware]]\n    ],\n) -> None:\n    \"\"\"Add a call to the handler.\n\n    Args:\n        handler: The handler for the call.\n        dependant: The dependant for the call.\n        parser: Optional custom parser for the call.\n        decoder: Optional custom decoder for the call.\n        filter: The filter for the call.\n        middlewares: Optional sequence of middlewares for the call.\n\n    Returns:\n        None\n\n    \"\"\"\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, AioPikaParser.parse_message),\n        decoder=resolve_custom_func(decoder, AioPikaParser.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/rabbit/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self._queue_obj is not None:\n        if self._consumer_tag is not None:  # pragma: no branch\n            await self._queue_obj.cancel(self._consumer_tag)\n            self._consumer_tag = None\n        self._queue_obj = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/rabbit/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    handler_name = (\n        self._title\n        or f\"{self.queue.name}:{getattr(self.exchange, 'name', '_')}:{self.call_name}\"\n    )\n\n    return {\n        handler_name: Channel(\n            description=self.description,  # type: ignore[attr-defined]\n            subscribe=Operation(\n                bindings=OperationBinding(\n                    amqp=amqp.OperationBinding(\n                        cc=self.queue.routing,\n                    ),\n                )\n                if _is_exchange(self.exchange)\n                else None,\n                message=Message(\n                    title=f\"{handler_name}:Message\",\n                    payload=resolve_payloads(payloads),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                amqp=amqp.ChannelBinding(\n                    **{\n                        \"is\": \"routingKey\",  # type: ignore\n                        \"queue\": amqp.Queue(\n                            name=self.queue.name,\n                            durable=self.queue.durable,\n                            exclusive=self.queue.exclusive,\n                            autoDelete=self.queue.auto_delete,\n                            vhost=self.virtual_host,\n                        )\n                        if _is_exchange(self.exchange)\n                        else None,\n                        \"exchange\": (\n                            amqp.Exchange(type=\"default\", vhost=self.virtual_host)\n                            if self.exchange is None\n                            else amqp.Exchange(\n                                type=self.exchange.type,  # type: ignore\n                                name=self.exchange.name,\n                                durable=self.exchange.durable,\n                                autoDelete=self.exchange.auto_delete,\n                                vhost=self.virtual_host,\n                            )\n                        ),\n                    }\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Handler/#faststream.rabbit.asyncapi.Handler.start","title":"start async","text":"
start(declarer: RabbitDeclarer) -> None\n

Starts the consumer for the RabbitMQ queue.

PARAMETER DESCRIPTION declarer

RabbitDeclarer object used to declare the queue and exchange

TYPE: RabbitDeclarer

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/handler.py
@override\nasync def start(self, declarer: RabbitDeclarer) -> None:  # type: ignore[override]\n    \"\"\"Starts the consumer for the RabbitMQ queue.\n\n    Args:\n        declarer: RabbitDeclarer object used to declare the queue and exchange\n\n    Returns:\n        None\n\n    \"\"\"\n    self._queue_obj = queue = await declarer.declare_queue(self.queue)\n\n    if self.exchange is not None:\n        exchange = await declarer.declare_exchange(self.exchange)\n        await queue.bind(\n            exchange,\n            routing_key=self.queue.routing,\n            arguments=self.queue.bind_arguments,\n        )\n\n    self._consumer_tag = await queue.consume(\n        # NOTE: aio-pika expects AbstractIncomingMessage, not IncomingMessage\n        self.consume,  # type: ignore[arg-type]\n        arguments=self.consume_args,\n    )\n\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/","title":"Publisher","text":"","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher","title":"faststream.rabbit.asyncapi.Publisher","text":"

Bases: LogicPublisher

A class representing a publisher.

METHOD DESCRIPTION get_payloads

Get the payloads for the publisher

","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.exchange","title":"exchange class-attribute instance-attribute","text":"
exchange: Optional[RabbitExchange] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.immediate","title":"immediate class-attribute instance-attribute","text":"
immediate: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.message_kwargs","title":"message_kwargs class-attribute instance-attribute","text":"
message_kwargs: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.name","title":"name property","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.persist","title":"persist class-attribute instance-attribute","text":"
persist: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.priority","title":"priority class-attribute instance-attribute","text":"
priority: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.queue","title":"queue class-attribute instance-attribute","text":"
queue: RabbitQueue = field(default=RabbitQueue(''))\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.routing","title":"routing property","text":"
routing: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.virtual_host","title":"virtual_host class-attribute instance-attribute","text":"
virtual_host: str = '/'\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.publish","title":"publish async","text":"
publish(\n    message: AioPikaSendableMessage = \"\",\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    correlation_id: Optional[str] = None,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Union[\n    aiormq.abc.ConfirmationFrameType, SendableMessage\n]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: AioPikaSendableMessage DEFAULT: ''

rpc

Whether the message is for RPC (Remote Procedure Call).

TYPE: bool DEFAULT: False

rpc_timeout

Timeout for RPC.

TYPE: Optional[float] DEFAULT: 30.0

raise_timeout

Whether to raise an exception if timeout occurs.

TYPE: bool DEFAULT: False

correlation_id

Correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional keyword arguments for the message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Union[ConfirmationFrameType, SendableMessage]

ConfirmationFrameType or SendableMessage: The result of the publish operation.

RAISES DESCRIPTION AssertionError

If _producer is not set up.

Source code in faststream/rabbit/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: AioPikaSendableMessage = \"\",\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    correlation_id: Optional[str] = None,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Union[aiormq.abc.ConfirmationFrameType, SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        rpc: Whether the message is for RPC (Remote Procedure Call).\n        rpc_timeout: Timeout for RPC.\n        raise_timeout: Whether to raise an exception if timeout occurs.\n        correlation_id: Correlation ID for the message.\n        **message_kwargs: Additional keyword arguments for the message.\n\n    Returns:\n        ConfirmationFrameType or SendableMessage: The result of the publish operation.\n\n    Raises:\n        AssertionError: If `_producer` is not set up.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(\n        message=message,\n        exchange=self.exchange,\n        routing_key=self.routing,\n        mandatory=self.mandatory,\n        immediate=self.immediate,\n        timeout=self.timeout,\n        rpc=rpc,\n        rpc_timeout=rpc_timeout,\n        raise_timeout=raise_timeout,\n        persist=self.persist,\n        reply_to=self.reply_to,\n        correlation_id=correlation_id,\n        priority=priority or self.priority,\n        **self.message_kwargs,\n        **message_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/rabbit/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    return {\n        self.name: Channel(\n            description=self.description,  # type: ignore[attr-defined]\n            publish=Operation(\n                bindings=OperationBinding(\n                    amqp=amqp.OperationBinding(\n                        cc=self.routing or None,\n                        deliveryMode=2 if self.persist else 1,\n                        mandatory=self.mandatory,\n                        replyTo=self.reply_to,\n                        priority=self.priority,\n                    ),\n                )\n                if _is_exchange(self.exchange)\n                else None,\n                message=Message(\n                    title=f\"{self.name}:Message\",\n                    payload=resolve_payloads(\n                        payloads,\n                        \"Publisher\",\n                        served_words=2 if self.title is None else 1,\n                    ),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                amqp=amqp.ChannelBinding(\n                    **{\n                        \"is\": \"routingKey\",  # type: ignore\n                        \"queue\": amqp.Queue(\n                            name=self.queue.name,\n                            durable=self.queue.durable,\n                            exclusive=self.queue.exclusive,\n                            autoDelete=self.queue.auto_delete,\n                            vhost=self.virtual_host,\n                        )\n                        if _is_exchange(self.exchange) and self.queue.name\n                        else None,\n                        \"exchange\": (\n                            amqp.Exchange(type=\"default\", vhost=self.virtual_host)\n                            if self.exchange is None\n                            else amqp.Exchange(\n                                type=self.exchange.type,  # type: ignore\n                                name=self.exchange.name,\n                                durable=self.exchange.durable,\n                                autoDelete=self.exchange.auto_delete,\n                                vhost=self.virtual_host,\n                            )\n                        ),\n                    }\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/rabbit/asyncapi/Publisher/#faststream.rabbit.asyncapi.Publisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/","title":"RabbitBroker","text":"","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker","title":"faststream.rabbit.broker.RabbitBroker","text":"
RabbitBroker(\n    url: Union[\n        str, URL, None\n    ] = \"amqp://guest:guest@localhost:5672/\",\n    *,\n    host: str = None,\n    port: int = None,\n    login: str = None,\n    password: str = None,\n    virtualhost: str = None,\n    ssl_options: Optional[aio_pika.abc.SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    max_consumers: Optional[int] = None,\n    protocol: str = None,\n    protocol_version: Optional[str] = \"0.9.1\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: RabbitLoggingMixin, BrokerAsyncUsecase[IncomingMessage, RobustConnection]

A RabbitMQ broker for FastAPI applications.

This class extends the base BrokerAsyncUsecase and provides asynchronous support for RabbitMQ as a message broker.

PARAMETER DESCRIPTION url

The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".

TYPE: Union[str, URL, None] DEFAULT: 'amqp://guest:guest@localhost:5672/'

max_consumers

Maximum number of consumers to limit message consumption. Defaults to None.

TYPE: Optional[int] DEFAULT: None

protocol

The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".

TYPE: str DEFAULT: None

protocol_version

The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".

TYPE: Optional[str] DEFAULT: '0.9.1'

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Initialize the RabbitBroker.

PARAMETER DESCRIPTION url

The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".

TYPE: Union[str, URL, None] DEFAULT: 'amqp://guest:guest@localhost:5672/'

max_consumers

Maximum number of consumers to limit message consumption. Defaults to None.

TYPE: Optional[int] DEFAULT: None

protocol

The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".

TYPE: str DEFAULT: None

protocol_version

The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".

TYPE: Optional[str] DEFAULT: '0.9.1'

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in faststream/rabbit/broker.py
def __init__(\n    self,\n    url: Union[str, URL, None] = \"amqp://guest:guest@localhost:5672/\",\n    *,\n    # connection args\n    host: Optional[str] = None,\n    port: Optional[int] = None,\n    login: Optional[str] = None,\n    password: Optional[str] = None,\n    virtualhost: Optional[str] = None,\n    ssl_options: Optional[SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    # broker args\n    max_consumers: Optional[int] = None,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"0.9.1\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"\n    Initialize the RabbitBroker.\n\n    Args:\n        url (Union[str, URL, None], optional): The RabbitMQ connection URL. Defaults to \"amqp://guest:guest@localhost:5672/\".\n        max_consumers (Optional[int], optional): Maximum number of consumers to limit message consumption. Defaults to None.\n        protocol (str, optional): The protocol to use (e.g., \"amqp\"). Defaults to \"amqp\".\n        protocol_version (Optional[str], optional): The protocol version to use (e.g., \"0.9.1\"). Defaults to \"0.9.1\".\n        **kwargs: Additional keyword arguments.\n    \"\"\"\n    security_args = parse_security(security)\n\n    if (ssl := kwargs.get(\"ssl\")) or kwargs.get(\"ssl_context\"):  # pragma: no cover\n        warnings.warn(\n            (\n                f\"\\nRabbitMQ {'`ssl`' if ssl else '`ssl_context`'} option was deprecated and will be removed in 0.4.0\"\n                \"\\nPlease, use `security` with `BaseSecurity` or `SASLPlaintext` instead\"\n            ),\n            DeprecationWarning,\n            stacklevel=2,\n        )\n\n    amqp_url = build_url(\n        url,\n        host=host,\n        port=port,\n        login=security_args.get(\"login\", login),\n        password=security_args.get(\"password\", password),\n        virtualhost=virtualhost,\n        ssl=security_args.get(\"ssl\", kwargs.pop(\"ssl\", False)),\n        ssl_options=ssl_options,\n        client_properties=client_properties,\n    )\n\n    super().__init__(\n        url=str(amqp_url),\n        protocol_version=protocol_version,\n        security=security,\n        ssl_context=security_args.get(\n            \"ssl_context\",\n            kwargs.pop(\"ssl_context\", None),\n        ),\n        **kwargs,\n    )\n\n    # respect ascynapi_url argument scheme\n    asyncapi_url = build_url(self.url)\n    self.protocol = protocol or asyncapi_url.scheme\n    self.virtual_host = asyncapi_url.path\n\n    self._max_consumers = max_consumers\n\n    self._channel = None\n    self.declarer = None\n    self._producer = None\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.declarer","title":"declarer instance-attribute","text":"
declarer: Optional[RabbitDeclarer] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[int, Handler]\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol or asyncapi_url.scheme\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.virtual_host","title":"virtual_host instance-attribute","text":"
virtual_host = asyncapi_url.path\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.connect","title":"connect async","text":"
connect(\n    *args: Any, **kwargs: Any\n) -> aio_pika.RobustConnection\n

Connect to the RabbitMQ server.

PARAMETER DESCRIPTION *args

Additional positional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION RobustConnection

aio_pika.RobustConnection: The RabbitMQ connection instance.

Source code in faststream/rabbit/broker.py
async def connect(self, *args: Any, **kwargs: Any) -> aio_pika.RobustConnection:\n    \"\"\"\n    Connect to the RabbitMQ server.\n\n    Args:\n        *args: Additional positional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        aio_pika.RobustConnection: The RabbitMQ connection instance.\n    \"\"\"\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.declare_exchange","title":"declare_exchange async","text":"
declare_exchange(\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange\n

Declare a RabbitMQ exchange.

PARAMETER DESCRIPTION exchange

The RabbitMQ exchange to declare.

TYPE: RabbitExchange

RETURNS DESCRIPTION RobustExchange

aio_pika.RobustExchange: The declared RabbitMQ exchange.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def declare_exchange(\n    self,\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange:\n    \"\"\"\n    Declare a RabbitMQ exchange.\n\n    Args:\n        exchange (RabbitExchange): The RabbitMQ exchange to declare.\n\n    Returns:\n        aio_pika.RobustExchange: The declared RabbitMQ exchange.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n    return await self.declarer.declare_exchange(exchange)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.declare_queue","title":"declare_queue async","text":"
declare_queue(queue: RabbitQueue) -> aio_pika.RobustQueue\n

Declare a RabbitMQ queue.

PARAMETER DESCRIPTION queue

The RabbitMQ queue to declare.

TYPE: RabbitQueue

RETURNS DESCRIPTION RobustQueue

aio_pika.RobustQueue: The declared RabbitMQ queue.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def declare_queue(\n    self,\n    queue: RabbitQueue,\n) -> aio_pika.RobustQueue:\n    \"\"\"\n    Declare a RabbitMQ queue.\n\n    Args:\n        queue (RabbitQueue): The RabbitMQ queue to declare.\n\n    Returns:\n        aio_pika.RobustQueue: The declared RabbitMQ queue.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n    return await self.declarer.declare_queue(queue)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, **kwargs: Any\n) -> Union[\n    aiormq.abc.ConfirmationFrameType, SendableMessage\n]\n

Publish a message to the RabbitMQ broker.

PARAMETER DESCRIPTION *args

Additional positional arguments.

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Union[ConfirmationFrameType, SendableMessage]

Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The confirmation frame or the response message.

Source code in faststream/rabbit/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Union[aiormq.abc.ConfirmationFrameType, SendableMessage]:\n    \"\"\"\n    Publish a message to the RabbitMQ broker.\n\n    Args:\n        *args: Additional positional arguments.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The confirmation frame or the response message.\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.publisher","title":"publisher","text":"
publisher(\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Publisher\n

Define a message publisher.

PARAMETER DESCRIPTION queue

The name of the RabbitMQ queue. Defaults to \"\".

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The name of the RabbitMQ exchange. Defaults to None.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key for messages. Defaults to \"\".

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory. Defaults to True.

TYPE: bool DEFAULT: True

immediate

Whether the message should be sent immediately. Defaults to False.

TYPE: bool DEFAULT: False

timeout

Timeout for message publishing. Defaults to None.

TYPE: TimeoutType DEFAULT: None

persist

Whether to persist messages. Defaults to False.

TYPE: bool DEFAULT: False

reply_to

The reply-to queue name. Defaults to None.

TYPE: Optional[str] DEFAULT: None

title

Title for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

description

Description for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional message properties and content.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Publisher

A message publisher instance.

TYPE: Publisher

Source code in faststream/rabbit/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Publisher:\n    \"\"\"\n    Define a message publisher.\n\n    Args:\n        queue (Union[RabbitQueue, str], optional): The name of the RabbitMQ queue. Defaults to \"\".\n        exchange (Union[RabbitExchange, str, None], optional): The name of the RabbitMQ exchange. Defaults to None.\n        routing_key (str, optional): The routing key for messages. Defaults to \"\".\n        mandatory (bool, optional): Whether the message is mandatory. Defaults to True.\n        immediate (bool, optional): Whether the message should be sent immediately. Defaults to False.\n        timeout (TimeoutType, optional): Timeout for message publishing. Defaults to None.\n        persist (bool, optional): Whether to persist messages. Defaults to False.\n        reply_to (Optional[str], optional): The reply-to queue name. Defaults to None.\n        title (Optional[str]): Title for AsyncAPI docs.\n        description (Optional[str]): Description for AsyncAPI docs.\n        **message_kwargs (Any): Additional message properties and content.\n\n    Returns:\n        Publisher: A message publisher instance.\n    \"\"\"\n    q, ex = RabbitQueue.validate(queue), RabbitExchange.validate(exchange)\n\n    publisher = Publisher(\n        title=title,\n        queue=q,\n        exchange=ex,\n        routing_key=routing_key,\n        mandatory=mandatory,\n        immediate=immediate,\n        timeout=timeout,\n        persist=persist,\n        reply_to=reply_to,\n        priority=priority,\n        message_kwargs=message_kwargs,\n        _description=description,\n        _schema=schema,\n        virtual_host=self.virtual_host,\n        include_in_schema=include_in_schema,\n    )\n\n    key = publisher._get_routing_hash()\n    publisher = self._publishers.get(key, publisher)\n    super().publisher(key, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.start","title":"start async","text":"
start() -> None\n

Start the RabbitMQ broker.

RAISES DESCRIPTION RuntimeError

If the declarer is not initialized in the connect method.

Source code in faststream/rabbit/broker.py
async def start(self) -> None:\n    \"\"\"\n    Start the RabbitMQ broker.\n\n    Raises:\n        RuntimeError: If the declarer is not initialized in the `connect` method.\n    \"\"\"\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, RabbitQueue(\"\"), RabbitExchange(\"\")),\n    )\n\n    await super().start()\n    assert self.declarer, NOT_CONNECTED_YET  # nosec B101\n\n    for publisher in self._publishers.values():\n        if publisher.exchange is not None:\n            await self.declare_exchange(publisher.exchange)\n\n    for handler in self.handlers.values():\n        c = self._get_log_context(None, handler.queue, handler.exchange)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self.declarer)\n
","boost":0.5},{"location":"api/faststream/rabbit/broker/RabbitBroker/#faststream.rabbit.broker.RabbitBroker.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    filter: Filter[RabbitMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n

Decorator to define a message subscriber.

PARAMETER DESCRIPTION queue

The name of the RabbitMQ queue.

TYPE: Union[str, RabbitQueue]

exchange

The name of the RabbitMQ exchange. Defaults to None.

TYPE: Union[str, RabbitExchange, None] DEFAULT: None

consume_args

Additional arguments for message consumption.

TYPE: Optional[AnyDict] DEFAULT: None

no_ack

Whether not to ack/nack/reject messages.

TYPE: bool DEFAULT: False

title

Title for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

description

Description for AsyncAPI docs.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION Callable

A decorator function for defining message subscribers.

TYPE: Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn]]

Source code in faststream/rabbit/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[aio_pika.IncomingMessage, RabbitMessage]] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[aio_pika.IncomingMessage], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RabbitMessage] = default_filter,\n    no_ack: bool = False,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"\n    Decorator to define a message subscriber.\n\n    Args:\n        queue (Union[str, RabbitQueue]): The name of the RabbitMQ queue.\n        exchange (Union[str, RabbitExchange, None], optional): The name of the RabbitMQ exchange. Defaults to None.\n        consume_args (Optional[AnyDict], optional): Additional arguments for message consumption.\n        no_ack (bool): Whether not to ack/nack/reject messages.\n        title (Optional[str]): Title for AsyncAPI docs.\n        description (Optional[str]): Description for AsyncAPI docs.\n\n    Returns:\n        Callable: A decorator function for defining message subscribers.\n    \"\"\"\n    super().subscriber()\n\n    r_queue = RabbitQueue.validate(queue)\n    r_exchange = RabbitExchange.validate(exchange)\n\n    self._setup_log_context(r_queue, r_exchange)\n\n    key = get_routing_hash(r_queue, r_exchange)\n    handler = self.handlers.get(\n        key,\n        Handler(\n            log_context_builder=partial(\n                self._get_log_context, queue=r_queue, exchange=r_exchange\n            ),\n            queue=r_queue,\n            exchange=r_exchange,\n            consume_args=consume_args,\n            description=description,\n            title=title,\n            virtual_host=self.virtual_host,\n            include_in_schema=include_in_schema,\n            graceful_timeout=self.graceful_timeout,\n        ),\n    )\n\n    self.handlers[key] = handler\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[\n        aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn\n    ]:\n        \"\"\"Wraps a consumer function with additional functionality.\n\n        Args:\n            func: The consumer function to be wrapped.\n\n        Returns:\n            The wrapped consumer function.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            no_ack=no_ack,\n            _process_kwargs={\n                \"reply_config\": reply_config,\n            },\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,\n            decoder=decoder or self._global_decoder,\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/rabbit/fastapi/Context/#faststream.broker.fastapi.context.Context","title":"faststream.broker.fastapi.context.Context","text":"
Context(name: str) -> Any\n
Source code in faststream/broker/fastapi/context.py
def Context(name: str) -> Any:\n    return params.Depends(\n        lambda: context.resolve(name),\n        use_cache=True,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/","title":"RabbitRouter","text":"","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter","title":"faststream.rabbit.fastapi.RabbitRouter","text":"
RabbitRouter(\n    url: Union[\n        str, URL, None\n    ] = \"amqp://guest:guest@localhost:5672/\",\n    *,\n    host: str = \"localhost\",\n    port: int = 5672,\n    login: str = \"guest\",\n    password: str = \"guest\",\n    virtualhost: str = \"/\",\n    ssl_options: Optional[aio_pika.abc.SSLOptions] = None,\n    timeout: aio_pika.abc.TimeoutType = None,\n    client_properties: Optional[FieldTable] = None,\n    security: Optional[BaseSecurity] = None,\n    max_consumers: Optional[int] = None,\n    graceful_timeout: Optional[float] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    asyncapi_url: Optional[str] = None,\n    protocol: str = \"amqp\",\n    protocol_version: Optional[str] = \"0.9.1\",\n    description: Optional[str] = None,\n    asyncapi_tags: Optional[Sequence[asyncapi.Tag]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    setup_state: bool = True,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n)\n

Bases: StreamRouter[IncomingMessage]

A class to represent a RabbitMQ router for incoming messages.

METHOD DESCRIPTION _setup_log_context

sets up the log context for the main broker and the including broker

Source code in faststream/rabbit/fastapi.py
main_broker._setup_log_context(h.queue, h.exchange)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.broker","title":"broker instance-attribute","text":"
broker: RabbitBroker\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.broker_class","title":"broker_class class-attribute instance-attribute","text":"
broker_class: Type[RabbitBroker] = RB\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    queue: Union[str, RabbitQueue],\n    *,\n    endpoint: Callable[..., T_HandlerReturn],\n    exchange: Union[str, RabbitExchange, None] = None,\n    consume_args: Optional[AnyDict] = None,\n    dependencies: Sequence[params.Depends] = (),\n    filter: Filter[RabbitMessage] = default_filter,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    retry: Union[bool, int] = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    **__service_kwargs: Any\n) -> Callable[\n    [IncomingMessage, bool], Awaitable[T_HandlerReturn]\n]\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.publisher","title":"publisher","text":"
publisher(\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    headers: Optional[aio_pika.abc.HeadersType] = None,\n    content_type: Optional[str] = None,\n    content_encoding: Optional[str] = None,\n    priority: Optional[int] = None,\n    correlation_id: Optional[str] = None,\n    expiration: Optional[aio_pika.abc.DateType] = None,\n    message_id: Optional[str] = None,\n    timestamp: Optional[aio_pika.abc.DateType] = None,\n    type: Optional[str] = None,\n    user_id: Optional[str] = None,\n    app_id: Optional[str] = None\n) -> Publisher\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    dependencies: Sequence[params.Depends] = (),\n    filter: Filter[RabbitMessage] = default_filter,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    retry: Union[bool, int] = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/rabbit/fastapi/RabbitRouter/#faststream.rabbit.fastapi.RabbitRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/","title":"LogicHandler","text":"","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler","title":"faststream.rabbit.handler.LogicHandler","text":"
LogicHandler(\n    queue: RabbitQueue,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    exchange: Optional[RabbitExchange] = None,\n    consume_args: Optional[AnyDict] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    virtual_host: str = \"/\",\n)\n

Bases: AsyncHandler[IncomingMessage], BaseRMQInformation

A class to handle logic for RabbitMQ message consumption.

METHOD DESCRIPTION __init__

Initializes the LogicHandler object

add_call

Adds a call to be handled by the LogicHandler

start

Starts consuming messages from the queue

close

Closes the consumer and cancels message consumption

Initialize a RabbitMQ consumer.

PARAMETER DESCRIPTION queue

RabbitQueue object representing the queue to consume from

TYPE: RabbitQueue

exchange

RabbitExchange object representing the exchange to bind the queue to (optional)

TYPE: Optional[RabbitExchange] DEFAULT: None

consume_args

Additional arguments for consuming from the queue (optional)

TYPE: Optional[AnyDict] DEFAULT: None

description

Description of the consumer (optional)

TYPE: Optional[str] DEFAULT: None

title

Title of the consumer (optional)

TYPE: Optional[str] DEFAULT: None

Source code in faststream/rabbit/handler.py
def __init__(\n    self,\n    queue: RabbitQueue,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # RMQ information\n    exchange: Optional[RabbitExchange] = None,\n    consume_args: Optional[AnyDict] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n    virtual_host: str = \"/\",\n) -> None:\n    \"\"\"Initialize a RabbitMQ consumer.\n\n    Args:\n        queue: RabbitQueue object representing the queue to consume from\n        exchange: RabbitExchange object representing the exchange to bind the queue to (optional)\n        consume_args: Additional arguments for consuming from the queue (optional)\n        description: Description of the consumer (optional)\n        title: Title of the consumer (optional)\n\n    \"\"\"\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n\n    self.queue = queue\n    self.exchange = exchange\n    self.virtual_host = virtual_host\n    self.consume_args = consume_args or {}\n\n    self._consumer_tag = None\n    self._queue_obj = None\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.consume_args","title":"consume_args instance-attribute","text":"
consume_args: AnyDict = consume_args or {}\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.exchange","title":"exchange instance-attribute","text":"
exchange: Optional[RabbitExchange] = exchange\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.queue","title":"queue instance-attribute","text":"
queue: RabbitQueue = queue\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.virtual_host","title":"virtual_host instance-attribute","text":"
virtual_host = virtual_host\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ],\n    decoder: Optional[CustomDecoder[RabbitMessage]],\n    filter: Filter[RabbitMessage],\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ]\n) -> None\n

Add a call to the handler.

PARAMETER DESCRIPTION handler

The handler for the call.

TYPE: HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn]

dependant

The dependant for the call.

TYPE: CallModel[P_HandlerParams, T_HandlerReturn]

parser

Optional custom parser for the call.

TYPE: Optional[CustomParser[IncomingMessage, RabbitMessage]]

decoder

Optional custom decoder for the call.

TYPE: Optional[CustomDecoder[RabbitMessage]]

filter

The filter for the call.

TYPE: Filter[RabbitMessage]

middlewares

Optional sequence of middlewares for the call.

TYPE: Optional[Sequence[Callable[[IncomingMessage], BaseMiddleware]]]

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[\n        aio_pika.IncomingMessage, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[aio_pika.IncomingMessage, RabbitMessage]],\n    decoder: Optional[CustomDecoder[RabbitMessage]],\n    filter: Filter[RabbitMessage],\n    middlewares: Optional[\n        Sequence[Callable[[aio_pika.IncomingMessage], BaseMiddleware]]\n    ],\n) -> None:\n    \"\"\"Add a call to the handler.\n\n    Args:\n        handler: The handler for the call.\n        dependant: The dependant for the call.\n        parser: Optional custom parser for the call.\n        decoder: Optional custom decoder for the call.\n        filter: The filter for the call.\n        middlewares: Optional sequence of middlewares for the call.\n\n    Returns:\n        None\n\n    \"\"\"\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, AioPikaParser.parse_message),\n        decoder=resolve_custom_func(decoder, AioPikaParser.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/rabbit/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self._queue_obj is not None:\n        if self._consumer_tag is not None:  # pragma: no branch\n            await self._queue_obj.cancel(self._consumer_tag)\n            self._consumer_tag = None\n        self._queue_obj = None\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/rabbit/handler/LogicHandler/#faststream.rabbit.handler.LogicHandler.start","title":"start async","text":"
start(declarer: RabbitDeclarer) -> None\n

Starts the consumer for the RabbitMQ queue.

PARAMETER DESCRIPTION declarer

RabbitDeclarer object used to declare the queue and exchange

TYPE: RabbitDeclarer

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/handler.py
@override\nasync def start(self, declarer: RabbitDeclarer) -> None:  # type: ignore[override]\n    \"\"\"Starts the consumer for the RabbitMQ queue.\n\n    Args:\n        declarer: RabbitDeclarer object used to declare the queue and exchange\n\n    Returns:\n        None\n\n    \"\"\"\n    self._queue_obj = queue = await declarer.declare_queue(self.queue)\n\n    if self.exchange is not None:\n        exchange = await declarer.declare_exchange(self.exchange)\n        await queue.bind(\n            exchange,\n            routing_key=self.queue.routing,\n            arguments=self.queue.bind_arguments,\n        )\n\n    self._consumer_tag = await queue.consume(\n        # NOTE: aio-pika expects AbstractIncomingMessage, not IncomingMessage\n        self.consume,  # type: ignore[arg-type]\n        arguments=self.consume_args,\n    )\n\n    await super().start()\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/","title":"RabbitDeclarer","text":"","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer","title":"faststream.rabbit.helpers.RabbitDeclarer","text":"
RabbitDeclarer(channel: aio_pika.RobustChannel)\n

Bases: Singleton

A class to declare RabbitMQ queues and exchanges.

METHOD DESCRIPTION declare_queue

RabbitQueue) -> aio_pika.RobustQueue Declares a queue and returns the declared queue object.

declare_exchange

RabbitExchange) -> aio_pika.RobustExchange Declares an exchange and returns the declared exchange object.

Initialize the class.

PARAMETER DESCRIPTION channel

Aio_pika RobustChannel object

TYPE: RobustChannel

Source code in faststream/rabbit/helpers.py
def __init__(self, channel: aio_pika.RobustChannel) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        channel: Aio_pika RobustChannel object\n\n    Attributes:\n        channel: Aio_pika RobustChannel object\n        queues: A dictionary to store queues\n        exchanges: A dictionary to store exchanges\n\n    \"\"\"\n    self.channel = channel\n    self.queues = {}\n    self.exchanges = {}\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer.channel","title":"channel instance-attribute","text":"
channel: aio_pika.RobustChannel = channel\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer.exchanges","title":"exchanges instance-attribute","text":"
exchanges: Dict[\n    Union[RabbitExchange, str], aio_pika.RobustExchange\n] = {}\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer.queues","title":"queues instance-attribute","text":"
queues: Dict[\n    Union[RabbitQueue, str], aio_pika.RobustQueue\n] = {}\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer.declare_exchange","title":"declare_exchange async","text":"
declare_exchange(\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange\n

Declare an exchange.

PARAMETER DESCRIPTION exchange

RabbitExchange object representing the exchange to be declared.

TYPE: RabbitExchange

RETURNS DESCRIPTION RobustExchange

aio_pika.RobustExchange: The declared exchange.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/rabbit/helpers.py
async def declare_exchange(\n    self,\n    exchange: RabbitExchange,\n) -> aio_pika.RobustExchange:\n    \"\"\"Declare an exchange.\n\n    Args:\n        exchange: RabbitExchange object representing the exchange to be declared.\n\n    Returns:\n        aio_pika.RobustExchange: The declared exchange.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    exch = self.exchanges.get(exchange)\n\n    if exch is None:\n        exch = cast(\n            aio_pika.RobustExchange,\n            await self.channel.declare_exchange(\n                **model_to_dict(\n                    exchange,\n                    exclude={\n                        \"routing_key\",\n                        \"bind_arguments\",\n                        \"bind_to\",\n                    },\n                )\n            ),\n        )\n        self.exchanges[exchange] = exch\n\n    if exchange.bind_to is not None:\n        parent = await self.declare_exchange(exchange.bind_to)\n        await exch.bind(\n            exchange=parent,\n            routing_key=exchange.routing_key,\n            arguments=exchange.arguments,\n        )\n\n    return exch\n
","boost":0.5},{"location":"api/faststream/rabbit/helpers/RabbitDeclarer/#faststream.rabbit.helpers.RabbitDeclarer.declare_queue","title":"declare_queue async","text":"
declare_queue(queue: RabbitQueue) -> aio_pika.RobustQueue\n

Declare a queue.

PARAMETER DESCRIPTION queue

RabbitQueue object representing the queue to be declared.

TYPE: RabbitQueue

RETURNS DESCRIPTION RobustQueue

aio_pika.RobustQueue: The declared queue.

Source code in faststream/rabbit/helpers.py
async def declare_queue(\n    self,\n    queue: RabbitQueue,\n) -> aio_pika.RobustQueue:\n    \"\"\"Declare a queue.\n\n    Args:\n        queue: RabbitQueue object representing the queue to be declared.\n\n    Returns:\n        aio_pika.RobustQueue: The declared queue.\n\n    \"\"\"\n    q = self.queues.get(queue)\n    if q is None:\n        q = cast(\n            aio_pika.RobustQueue,\n            await self.channel.declare_queue(\n                **model_to_dict(\n                    queue,\n                    exclude={\n                        \"routing_key\",\n                        \"path_regex\",\n                        \"bind_arguments\",\n                    },\n                )\n            ),\n        )\n        self.queues[queue] = q\n    return q\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/","title":"RabbitMessage","text":"","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage","title":"faststream.rabbit.message.RabbitMessage","text":"

Bases: StreamMessage[IncomingMessage]

A message class for working with RabbitMQ messages.

This class extends StreamMessage to provide additional functionality for acknowledging, rejecting, or nack-ing RabbitMQ messages.

METHOD DESCRIPTION ack

Acknowledge the RabbitMQ message.

nack

Negative Acknowledgment of the RabbitMQ message.

reject

Reject the RabbitMQ message.

","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.ack","title":"ack async","text":"
ack(**kwargs: Any) -> None\n

Acknowledge the RabbitMQ message.

Acknowledgment indicates that the message has been successfully processed.

PARAMETER DESCRIPTION **kwargs

Additional keyword arguments (not used).

TYPE: Any DEFAULT: {}

Source code in faststream/rabbit/message.py
async def ack(self, **kwargs: Any) -> None:\n    \"\"\"\n    Acknowledge the RabbitMQ message.\n\n    Acknowledgment indicates that the message has been successfully processed.\n\n    Args:\n        **kwargs (Any): Additional keyword arguments (not used).\n\n    \"\"\"\n    pika_message = self.raw_message\n    await super().ack()\n    if (\n        pika_message._IncomingMessage__processed  # type: ignore[attr-defined]\n        or pika_message._IncomingMessage__no_ack  # type: ignore[attr-defined]\n    ):\n        return\n    await pika_message.ack()\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.nack","title":"nack async","text":"
nack(**kwargs: Any) -> None\n

Negative Acknowledgment of the RabbitMQ message.

Nack-ing a message indicates that the message processing has failed and should be requeued.

PARAMETER DESCRIPTION **kwargs

Additional keyword arguments (not used).

TYPE: Any DEFAULT: {}

Source code in faststream/rabbit/message.py
async def nack(self, **kwargs: Any) -> None:\n    \"\"\"\n    Negative Acknowledgment of the RabbitMQ message.\n\n    Nack-ing a message indicates that the message processing has failed and should be requeued.\n\n    Args:\n        **kwargs (Any): Additional keyword arguments (not used).\n\n    \"\"\"\n    pika_message = self.raw_message\n    await super().nack()\n    if (\n        pika_message._IncomingMessage__processed  # type: ignore[attr-defined]\n        or pika_message._IncomingMessage__no_ack  # type: ignore[attr-defined]\n    ):\n        return\n    await pika_message.nack()\n
","boost":0.5},{"location":"api/faststream/rabbit/message/RabbitMessage/#faststream.rabbit.message.RabbitMessage.reject","title":"reject async","text":"
reject(**kwargs: Any) -> None\n

Reject the RabbitMQ message.

Rejecting a message indicates that the message processing has failed, and it should not be requeued.

PARAMETER DESCRIPTION **kwargs

Additional keyword arguments (not used).

TYPE: Any DEFAULT: {}

Source code in faststream/rabbit/message.py
async def reject(self, **kwargs: Any) -> None:\n    \"\"\"\n    Reject the RabbitMQ message.\n\n    Rejecting a message indicates that the message processing has failed, and it should not be requeued.\n\n    Args:\n        **kwargs (Any): Additional keyword arguments (not used).\n\n    \"\"\"\n    pika_message = self.raw_message\n    await super().reject()\n    if (\n        pika_message._IncomingMessage__processed  # type: ignore[attr-defined]\n        or pika_message._IncomingMessage__no_ack  # type: ignore[attr-defined]\n    ):\n        return\n    await pika_message.reject()\n
","boost":0.5},{"location":"api/faststream/rabbit/parser/AioPikaParser/","title":"AioPikaParser","text":"","boost":0.5},{"location":"api/faststream/rabbit/parser/AioPikaParser/#faststream.rabbit.parser.AioPikaParser","title":"faststream.rabbit.parser.AioPikaParser","text":"

A class for parsing, encoding, and decoding messages using aio-pika.

METHOD DESCRIPTION parse_message

aio_pika.IncomingMessage) -> StreamMessage[aio_pika.IncomingMessage]: Parses an incoming message and returns a StreamMessage object.

decode_message

StreamMessage[aio_pika.IncomingMessage]) -> DecodedMessage: Decodes a StreamMessage object and returns a DecodedMessage object.

encode_message

AioPikaSendableMessage, persist: bool = False, callback_queue: Optional[aio_pika.abc.AbstractRobustQueue] = None, reply_to: Optional[str] = None, **message_kwargs: Any) -> aio_pika.Message: Encodes a message into an aio_pika.Message object.

","boost":0.5},{"location":"api/faststream/rabbit/parser/AioPikaParser/#faststream.rabbit.parser.AioPikaParser.decode_message","title":"decode_message async staticmethod","text":"
decode_message(\n    msg: StreamMessage[aio_pika.IncomingMessage],\n) -> DecodedMessage\n

Decode a message.

PARAMETER DESCRIPTION msg

The message to decode.

TYPE: StreamMessage[IncomingMessage]

RETURNS DESCRIPTION DecodedMessage

The decoded message.

Source code in faststream/rabbit/parser.py
@staticmethod\nasync def decode_message(\n    msg: StreamMessage[aio_pika.IncomingMessage],\n) -> DecodedMessage:\n    \"\"\"Decode a message.\n\n    Args:\n        msg: The message to decode.\n\n    Returns:\n        The decoded message.\n\n    \"\"\"\n    return decode_message(msg)\n
","boost":0.5},{"location":"api/faststream/rabbit/parser/AioPikaParser/#faststream.rabbit.parser.AioPikaParser.encode_message","title":"encode_message staticmethod","text":"
encode_message(\n    message: AioPikaSendableMessage,\n    persist: bool = False,\n    callback_queue: Optional[\n        aio_pika.abc.AbstractRobustQueue\n    ] = None,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any\n) -> aio_pika.Message\n

Encodes a message for sending using AioPika.

PARAMETER DESCRIPTION message

The message to encode.

TYPE: AioPikaSendableMessage

persist

Whether to persist the message. Defaults to False.

TYPE: bool DEFAULT: False

callback_queue

The callback queue to use for replies. Defaults to None.

TYPE: AbstractRobustQueue DEFAULT: None

reply_to

The reply-to queue to use for replies. Defaults to None.

TYPE: str DEFAULT: None

**message_kwargs

Additional keyword arguments to include in the encoded message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Message

aio_pika.Message: The encoded message.

RAISES DESCRIPTION NotImplementedError

If the message is not an instance of aio_pika.Message.

Source code in faststream/rabbit/parser.py
@staticmethod\ndef encode_message(\n    message: AioPikaSendableMessage,\n    persist: bool = False,\n    callback_queue: Optional[aio_pika.abc.AbstractRobustQueue] = None,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any,\n) -> aio_pika.Message:\n    \"\"\"Encodes a message for sending using AioPika.\n\n    Args:\n        message (AioPikaSendableMessage): The message to encode.\n        persist (bool, optional): Whether to persist the message. Defaults to False.\n        callback_queue (aio_pika.abc.AbstractRobustQueue, optional): The callback queue to use for replies. Defaults to None.\n        reply_to (str, optional): The reply-to queue to use for replies. Defaults to None.\n        **message_kwargs (Any): Additional keyword arguments to include in the encoded message.\n\n    Returns:\n        aio_pika.Message: The encoded message.\n\n    Raises:\n        NotImplementedError: If the message is not an instance of aio_pika.Message.\n\n    \"\"\"\n    if isinstance(message, aio_pika.Message):\n        return message\n\n    else:\n        message, content_type = encode_message(message)\n\n        delivery_mode = (\n            DeliveryMode.PERSISTENT if persist else DeliveryMode.NOT_PERSISTENT\n        )\n\n        return aio_pika.Message(\n            message,\n            **{\n                \"delivery_mode\": delivery_mode,\n                \"content_type\": content_type,\n                \"reply_to\": callback_queue or reply_to,\n                \"correlation_id\": str(uuid4()),\n                **message_kwargs,\n            },\n        )\n
","boost":0.5},{"location":"api/faststream/rabbit/parser/AioPikaParser/#faststream.rabbit.parser.AioPikaParser.parse_message","title":"parse_message async staticmethod","text":"
parse_message(\n    message: aio_pika.IncomingMessage,\n) -> StreamMessage[aio_pika.IncomingMessage]\n

Parses an incoming message and returns a RabbitMessage object.

PARAMETER DESCRIPTION message

The incoming message to parse.

TYPE: IncomingMessage

RETURNS DESCRIPTION StreamMessage[IncomingMessage]

A StreamMessage object representing the parsed message.

Source code in faststream/rabbit/parser.py
@staticmethod\nasync def parse_message(\n    message: aio_pika.IncomingMessage,\n) -> StreamMessage[aio_pika.IncomingMessage]:\n    \"\"\"Parses an incoming message and returns a RabbitMessage object.\n\n    Args:\n        message: The incoming message to parse.\n\n    Returns:\n        A StreamMessage object representing the parsed message.\n\n    \"\"\"\n    handler = context.get_local(\"handler_\")\n    path: AnyDict = {}\n    path_re: Optional[Pattern[str]]\n    if (\n        handler\n        and (path_re := handler.queue.path_regex) is not None\n        and (match := path_re.match(message.routing_key or \"\")) is not None\n    ):\n        path = match.groupdict()\n\n    return RabbitMessage(\n        body=message.body,\n        headers=message.headers,\n        reply_to=message.reply_to or \"\",\n        content_type=message.content_type,\n        message_id=message.message_id or str(uuid4()),\n        correlation_id=message.correlation_id or str(uuid4()),\n        path=path,\n        raw_message=message,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/producer/AioPikaFastProducer/","title":"AioPikaFastProducer","text":"","boost":0.5},{"location":"api/faststream/rabbit/producer/AioPikaFastProducer/#faststream.rabbit.producer.AioPikaFastProducer","title":"faststream.rabbit.producer.AioPikaFastProducer","text":"
AioPikaFastProducer(\n    channel: aio_pika.RobustChannel,\n    declarer: RabbitDeclarer,\n    parser: Optional[\n        AsyncCustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ],\n    decoder: Optional[AsyncCustomDecoder[RabbitMessage]],\n)\n

A class for fast producing messages using aio-pika.

METHOD DESCRIPTION publish

Publishes a message to a queue or exchange.

_publish

Publishes a message to an exchange.

Note: This docstring is incomplete as it is difficult to understand the purpose and functionality of the class and its methods without more context.

Initialize a class instance.

PARAMETER DESCRIPTION channel

The aio_pika.RobustChannel object.

TYPE: RobustChannel

declarer

The RabbitDeclarer object.

TYPE: RabbitDeclarer

parser

An optional AsyncCustomParser object for parsing incoming messages.

TYPE: Optional[AsyncCustomParser[IncomingMessage, RabbitMessage]]

decoder

An optional AsyncCustomDecoder object for decoding incoming messages.

TYPE: Optional[AsyncCustomDecoder[RabbitMessage]]

Source code in faststream/rabbit/producer.py
def __init__(\n    self,\n    channel: aio_pika.RobustChannel,\n    declarer: RabbitDeclarer,\n    parser: Optional[AsyncCustomParser[aio_pika.IncomingMessage, RabbitMessage]],\n    decoder: Optional[AsyncCustomDecoder[RabbitMessage]],\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        channel: The aio_pika.RobustChannel object.\n        declarer: The RabbitDeclarer object.\n        parser: An optional AsyncCustomParser object for parsing incoming messages.\n        decoder: An optional AsyncCustomDecoder object for decoding incoming messages.\n\n    \"\"\"\n    self._channel = channel\n    self.declarer = declarer\n    self._parser = resolve_custom_func(parser, AioPikaParser.parse_message)\n    self._decoder = resolve_custom_func(decoder, AioPikaParser.decode_message)\n    self._rpc_lock = anyio.Lock()\n
","boost":0.5},{"location":"api/faststream/rabbit/producer/AioPikaFastProducer/#faststream.rabbit.producer.AioPikaFastProducer.declarer","title":"declarer instance-attribute","text":"
declarer: RabbitDeclarer = declarer\n
","boost":0.5},{"location":"api/faststream/rabbit/producer/AioPikaFastProducer/#faststream.rabbit.producer.AioPikaFastProducer.publish","title":"publish async","text":"
publish(\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any\n) -> Union[\n    aiormq.abc.ConfirmationFrameType, SendableMessage\n]\n

Publish a message to a RabbitMQ queue.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: AioPikaSendableMessage DEFAULT: ''

queue

The queue to publish the message to.

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The exchange to publish the message to.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key for the message.

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory.

TYPE: bool DEFAULT: True

immediate

Whether the message should be delivered immediately.

TYPE: bool DEFAULT: False

timeout

The timeout for the operation.

TYPE: TimeoutType DEFAULT: None

rpc

Whether the message is for RPC.

TYPE: bool DEFAULT: False

rpc_timeout

The timeout for RPC.

TYPE: Optional[float] DEFAULT: 30.0

raise_timeout

Whether to raise an exception on timeout.

TYPE: bool DEFAULT: False

persist

Whether the message should be persisted.

TYPE: bool DEFAULT: False

reply_to

The reply-to queue for RPC.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional keyword arguments for the message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Union[ConfirmationFrameType, SendableMessage]

Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The result of the publish operation.

RAISES DESCRIPTION WRONG_PUBLISH_ARGS

If reply_to is not None when rpc is True.

Source code in faststream/rabbit/producer.py
async def publish(\n    self,\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any,\n) -> Union[aiormq.abc.ConfirmationFrameType, SendableMessage]:\n    \"\"\"Publish a message to a RabbitMQ queue.\n\n    Args:\n        message (AioPikaSendableMessage): The message to be published.\n        queue (Union[RabbitQueue, str]): The queue to publish the message to.\n        exchange (Union[RabbitExchange, str, None]): The exchange to publish the message to.\n        routing_key (str): The routing key for the message.\n        mandatory (bool): Whether the message is mandatory.\n        immediate (bool): Whether the message should be delivered immediately.\n        timeout (TimeoutType): The timeout for the operation.\n        rpc (bool): Whether the message is for RPC.\n        rpc_timeout (Optional[float]): The timeout for RPC.\n        raise_timeout (bool): Whether to raise an exception on timeout.\n        persist (bool): Whether the message should be persisted.\n        reply_to (Optional[str]): The reply-to queue for RPC.\n        **message_kwargs (Any): Additional keyword arguments for the message.\n\n    Returns:\n        Union[aiormq.abc.ConfirmationFrameType, SendableMessage]: The result of the publish operation.\n\n    Raises:\n        WRONG_PUBLISH_ARGS: If reply_to is not None when rpc is True.\n\n    \"\"\"\n    p_queue = RabbitQueue.validate(queue)\n\n    context: AsyncContextManager[\n        Optional[MemoryObjectReceiveStream[aio_pika.IncomingMessage]]\n    ]\n    if rpc is True:\n        if reply_to is not None:\n            raise WRONG_PUBLISH_ARGS\n        else:\n            context = _RPCCallback(\n                self._rpc_lock,\n                self.declarer.queues[RABBIT_REPLY],\n            )\n    else:\n        context = fake_context()\n\n    async with context as response_queue:\n        r = await self._publish(\n            message=message,\n            exchange=exchange,\n            routing_key=routing_key or p_queue.routing or \"\",\n            mandatory=mandatory,\n            immediate=immediate,\n            timeout=timeout,\n            persist=persist,\n            reply_to=RABBIT_REPLY if response_queue else reply_to,\n            **message_kwargs,\n        )\n\n        if response_queue is None:\n            return r\n\n        else:\n            msg: Optional[aio_pika.IncomingMessage] = None\n            with timeout_scope(rpc_timeout, raise_timeout):\n                msg = await response_queue.receive()\n\n            if msg:  # pragma: no branch\n                return await self._decoder(await self._parser(msg))\n\n    return None\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/","title":"LogicPublisher","text":"","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher","title":"faststream.rabbit.publisher.LogicPublisher dataclass","text":"

Bases: ABCPublisher[IncomingMessage]

A class to publish messages for logic processing.

METHOD DESCRIPTION publish

Publishes a message for logic processing.

","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.exchange","title":"exchange class-attribute instance-attribute","text":"
exchange: Optional[RabbitExchange] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.immediate","title":"immediate class-attribute instance-attribute","text":"
immediate: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.message_kwargs","title":"message_kwargs class-attribute instance-attribute","text":"
message_kwargs: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.persist","title":"persist class-attribute instance-attribute","text":"
persist: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.priority","title":"priority class-attribute instance-attribute","text":"
priority: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.queue","title":"queue class-attribute instance-attribute","text":"
queue: RabbitQueue = field(default=RabbitQueue(''))\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.routing","title":"routing property","text":"
routing: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.virtual_host","title":"virtual_host class-attribute instance-attribute","text":"
virtual_host: str = '/'\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/rabbit/publisher.py
Methods:\n    publish : Publishes a message for logic processing.\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.publish","title":"publish async","text":"
publish(\n    message: AioPikaSendableMessage = \"\",\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    correlation_id: Optional[str] = None,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Union[\n    aiormq.abc.ConfirmationFrameType, SendableMessage\n]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: AioPikaSendableMessage DEFAULT: ''

rpc

Whether the message is for RPC (Remote Procedure Call).

TYPE: bool DEFAULT: False

rpc_timeout

Timeout for RPC.

TYPE: Optional[float] DEFAULT: 30.0

raise_timeout

Whether to raise an exception if timeout occurs.

TYPE: bool DEFAULT: False

correlation_id

Correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional keyword arguments for the message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Union[ConfirmationFrameType, SendableMessage]

ConfirmationFrameType or SendableMessage: The result of the publish operation.

RAISES DESCRIPTION AssertionError

If _producer is not set up.

Source code in faststream/rabbit/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: AioPikaSendableMessage = \"\",\n    *,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    correlation_id: Optional[str] = None,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Union[aiormq.abc.ConfirmationFrameType, SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        rpc: Whether the message is for RPC (Remote Procedure Call).\n        rpc_timeout: Timeout for RPC.\n        raise_timeout: Whether to raise an exception if timeout occurs.\n        correlation_id: Correlation ID for the message.\n        **message_kwargs: Additional keyword arguments for the message.\n\n    Returns:\n        ConfirmationFrameType or SendableMessage: The result of the publish operation.\n\n    Raises:\n        AssertionError: If `_producer` is not set up.\n\n    \"\"\"\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(\n        message=message,\n        exchange=self.exchange,\n        routing_key=self.routing,\n        mandatory=self.mandatory,\n        immediate=self.immediate,\n        timeout=self.timeout,\n        rpc=rpc,\n        rpc_timeout=rpc_timeout,\n        raise_timeout=raise_timeout,\n        persist=self.persist,\n        reply_to=self.reply_to,\n        correlation_id=correlation_id,\n        priority=priority or self.priority,\n        **self.message_kwargs,\n        **message_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/rabbit/publisher/LogicPublisher/#faststream.rabbit.publisher.LogicPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/","title":"RabbitRouter","text":"","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter","title":"faststream.rabbit.router.RabbitRouter","text":"
RabbitRouter(\n    prefix: str = \"\",\n    handlers: Sequence[RabbitRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    include_in_schema: bool = True\n)\n

Bases: RabbitRouter

A class representing a RabbitMQ router for publishing messages.

METHOD DESCRIPTION _get_publisher_key

Returns the key for a given Publisher object

_update_publisher_prefix

Updates the prefix of a given Publisher object

publisher

Publishes a message to RabbitMQ

Source code in faststream/rabbit/router.py
_publishers: Dict[int, Publisher]\n\n@staticmethod\ndef _get_publisher_key(publisher: Publisher) -> int:\n    \"\"\"Get the publisher key.\n\n    Args:\n        publisher: The publisher object.\n\n    Returns:\n        The publisher key as an integer.\n\n    \"\"\"\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.publisher","title":"publisher","text":"
publisher(\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any\n) -> Publisher\n

Publishes a message to a RabbitMQ queue or exchange.

PARAMETER DESCRIPTION queue

The RabbitMQ queue to publish the message to. Can be either a RabbitQueue object or a string representing the queue name.

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The RabbitMQ exchange to publish the message to. Can be either a RabbitExchange object, a string representing the exchange name, or None.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key to use when publishing the message.

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory or not.

TYPE: bool DEFAULT: True

immediate

Whether the message should be delivered immediately or not.

TYPE: bool DEFAULT: False

timeout

The timeout for the publish operation.

TYPE: TimeoutType DEFAULT: None

persist

Whether the message should be persisted or not.

TYPE: bool DEFAULT: False

reply_to

The reply-to address for the message.

TYPE: Optional[str] DEFAULT: None

title

The title of the message (AsyncAPI information).

TYPE: Optional[str] DEFAULT: None

description

The description of the message (AsyncAPI information).

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional keyword arguments to include in the message.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Publisher

The Publisher object used to publish the message.

Source code in faststream/rabbit/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n) -> Publisher:\n    \"\"\"Publishes a message to a RabbitMQ queue or exchange.\n\n    Args:\n        queue: The RabbitMQ queue to publish the message to. Can be either a RabbitQueue object or a string representing the queue name.\n        exchange: The RabbitMQ exchange to publish the message to. Can be either a RabbitExchange object, a string representing the exchange name, or None.\n        routing_key: The routing key to use when publishing the message.\n        mandatory: Whether the message is mandatory or not.\n        immediate: Whether the message should be delivered immediately or not.\n        timeout: The timeout for the publish operation.\n        persist: Whether the message should be persisted or not.\n        reply_to: The reply-to address for the message.\n        title: The title of the message (AsyncAPI information).\n        description: The description of the message (AsyncAPI information).\n        **message_kwargs: Additional keyword arguments to include in the message.\n\n    Returns:\n        The Publisher object used to publish the message.\n\n    \"\"\"\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            queue=RabbitQueue.validate(queue),\n            exchange=RabbitExchange.validate(exchange),\n            routing_key=routing_key,\n            mandatory=mandatory,\n            immediate=immediate,\n            timeout=timeout,\n            persist=persist,\n            reply_to=reply_to,\n            priority=priority,\n            message_kwargs=message_kwargs,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[key] = self._publishers.get(key, new_publisher)\n    return publisher\n
","boost":0.5},{"location":"api/faststream/rabbit/router/RabbitRouter/#faststream.rabbit.router.RabbitRouter.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    exchange: Union[str, RabbitExchange, None] = None,\n    *,\n    consume_args: Optional[AnyDict] = None,\n    reply_config: Optional[ReplyConfig] = None,\n    dependencies: Sequence[Depends] = (),\n    filter: Filter[RabbitMessage] = default_filter,\n    parser: Optional[\n        CustomParser[\n            aio_pika.IncomingMessage, RabbitMessage\n        ]\n    ] = None,\n    decoder: Optional[CustomDecoder[RabbitMessage]] = None,\n    middlewares: Optional[\n        Sequence[\n            Callable[\n                [aio_pika.IncomingMessage], BaseMiddleware\n            ]\n        ]\n    ] = None,\n    retry: Union[bool, int] = False,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        aio_pika.IncomingMessage,\n        P_HandlerParams,\n        T_HandlerReturn,\n    ],\n]\n
Source code in faststream/rabbit/router.py
    Returns:\n        Publisher: The updated publisher object.\n\n    Note:\n        This function is intended to be used as a decorator.\n\n    \"\"\"\n    publisher.queue = model_copy(\n        publisher.queue, update={\"name\": prefix + publisher.queue.name}\n    )\n    return publisher\n\n@override\ndef publisher(  # type: ignore[override]\n    self,\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n    priority: Optional[int] = None,\n    **message_kwargs: Any,\n
","boost":0.5},{"location":"api/faststream/rabbit/security/parse_security/","title":"parse_security","text":"","boost":0.5},{"location":"api/faststream/rabbit/security/parse_security/#faststream.rabbit.security.parse_security","title":"faststream.rabbit.security.parse_security","text":"
parse_security(security: Optional[BaseSecurity]) -> AnyDict\n
Source code in faststream/rabbit/security.py
def parse_security(security: Optional[BaseSecurity]) -> AnyDict:\n    if security is None:\n        return {}\n    elif isinstance(security, SASLPlaintext):\n        return _parse_sasl_plaintext(security)\n    elif isinstance(security, BaseSecurity):\n        return _parse_base_security(security)\n    else:\n        raise NotImplementedError(f\"RabbitBroker does not support {type(security)}\")\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/","title":"ExchangeType","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType","title":"faststream.rabbit.shared.constants.ExchangeType","text":"

Bases: str, Enum

A class to represent the exchange type.

","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.DIRECT","title":"DIRECT class-attribute instance-attribute","text":"
DIRECT = 'direct'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.FANOUT","title":"FANOUT class-attribute instance-attribute","text":"
FANOUT = 'fanout'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.HEADERS","title":"HEADERS class-attribute instance-attribute","text":"
HEADERS = 'headers'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.TOPIC","title":"TOPIC class-attribute instance-attribute","text":"
TOPIC = 'topic'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.X_CONSISTENT_HASH","title":"X_CONSISTENT_HASH class-attribute instance-attribute","text":"
X_CONSISTENT_HASH = 'x-consistent-hash'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.X_DELAYED_MESSAGE","title":"X_DELAYED_MESSAGE class-attribute instance-attribute","text":"
X_DELAYED_MESSAGE = 'x-delayed-message'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/constants/ExchangeType/#faststream.rabbit.shared.constants.ExchangeType.X_MODULUS_HASH","title":"X_MODULUS_HASH class-attribute instance-attribute","text":"
X_MODULUS_HASH = 'x-modulus-hash'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/logging/RabbitLoggingMixin/","title":"RabbitLoggingMixin","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/logging/RabbitLoggingMixin/#faststream.rabbit.shared.logging.RabbitLoggingMixin","title":"faststream.rabbit.shared.logging.RabbitLoggingMixin","text":"
RabbitLoggingMixin(\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any\n)\n

Bases: LoggingMixin

A class that extends the LoggingMixin class and adds additional functionality for logging RabbitMQ related information.

METHOD DESCRIPTION __init__

Initializes the RabbitLoggingMixin object.

_get_log_context

Overrides the _get_log_context method of the LoggingMixin class to include RabbitMQ related context information.

fmt

Returns the log format string.

_setup_log_context

Sets up the log context by updating the maximum lengths of the queue and exchange names.

Initialize the class.

PARAMETER DESCRIPTION *args

Variable length argument list

TYPE: Any DEFAULT: ()

logger

Optional logger object

TYPE: Optional[Logger] DEFAULT: access_logger

log_level

Logging level

TYPE: int DEFAULT: INFO

log_fmt

Optional log format

TYPE: Optional[str] DEFAULT: None

**kwargs

Arbitrary keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/shared/logging.py
def __init__(\n    self,\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize the class.\n\n    Args:\n        *args: Variable length argument list\n        logger: Optional logger object\n        log_level: Logging level\n        log_fmt: Optional log format\n        **kwargs: Arbitrary keyword arguments\n\n    Returns:\n        None\n\n    \"\"\"\n    super().__init__(\n        *args,\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n        **kwargs,\n    )\n    self._max_queue_len = 4\n    self._max_exchange_len = 4\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/logging/RabbitLoggingMixin/#faststream.rabbit.shared.logging.RabbitLoggingMixin.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/logging/RabbitLoggingMixin/#faststream.rabbit.shared.logging.RabbitLoggingMixin.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/logging/RabbitLoggingMixin/#faststream.rabbit.shared.logging.RabbitLoggingMixin.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/","title":"ABCPublisher","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher","title":"faststream.rabbit.shared.publisher.ABCPublisher dataclass","text":"

Bases: ABC, BasePublisher[MsgType], BaseRMQInformation

A class representing an ABCPublisher.

","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.exchange","title":"exchange class-attribute instance-attribute","text":"
exchange: Optional[RabbitExchange] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.immediate","title":"immediate class-attribute instance-attribute","text":"
immediate: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.message_kwargs","title":"message_kwargs class-attribute instance-attribute","text":"
message_kwargs: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.persist","title":"persist class-attribute instance-attribute","text":"
persist: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.priority","title":"priority class-attribute instance-attribute","text":"
priority: Optional[int] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.queue","title":"queue class-attribute instance-attribute","text":"
queue: RabbitQueue = field(default=RabbitQueue(''))\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.virtual_host","title":"virtual_host class-attribute instance-attribute","text":"
virtual_host: str = '/'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.publish","title":"publish abstractmethod async","text":"
publish(\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: SendableMessage

correlation_id

Optional correlation ID for the message.

TYPE: Optional[str] DEFAULT: None

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

The published message.

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/publisher.py
@abstractmethod\nasync def publish(\n    self,\n    message: SendableMessage,\n    correlation_id: Optional[str] = None,\n    **kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"Publish a message.\n\n    Args:\n        message: The message to be published.\n        correlation_id: Optional correlation ID for the message.\n        **kwargs: Additional keyword arguments.\n\n    Returns:\n        The published message.\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/publisher/ABCPublisher/#faststream.rabbit.shared.publisher.ABCPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRoute/","title":"RabbitRoute","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/","title":"RabbitRouter","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter","title":"faststream.rabbit.shared.router.RabbitRouter","text":"
RabbitRouter(\n    prefix: str = \"\",\n    handlers: Sequence[\n        RabbitRoute[IncomingMessage, SendableMessage]\n    ] = (),\n    **kwargs: Any\n)\n

Bases: BrokerRouter[int, IncomingMessage]

A class representing a RabbitMQ router for handling incoming messages.

METHOD DESCRIPTION __init__

initializes the RabbitRouter object

subscriber

decorator for subscribing to a queue and registering a handler function

Override the __init__ method of the parent class.

PARAMETER DESCRIPTION prefix

A prefix string

TYPE: str DEFAULT: ''

handlers

A sequence of RabbitRoute objects

TYPE: Sequence[BrokerRoute[IncomingMessage, SendableMessage]] DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported

Source code in faststream/rabbit/shared/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[RabbitRoute[IncomingMessage, SendableMessage]] = (),\n    **kwargs: Any,\n) -> None:\n    \"\"\"Override the `__init__` method of the parent class.\n\n    Args:\n        prefix: A prefix string\n        handlers: A sequence of RabbitRoute objects\n        **kwargs: Additional keyword arguments\n\n    Raises:\n        NotImplementedError: If silent animals are not supported\n\n    \"\"\"\n    for h in handlers:\n        if (q := h.kwargs.pop(\"queue\", None)) is None:\n            q, h.args = h.args[0], h.args[1:]\n        queue = RabbitQueue.validate(q)\n        new_q = model_copy(queue, update={\"name\": prefix + queue.name})\n        h.args = (new_q, *h.args)\n\n    super().__init__(prefix, handlers, **kwargs)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/router/RabbitRouter/#faststream.rabbit.shared.router.RabbitRouter.subscriber","title":"subscriber","text":"
subscriber(\n    queue: Union[str, RabbitQueue],\n    *broker_args: Any,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        IncomingMessage, P_HandlerParams, T_HandlerReturn\n    ],\n]\n

A function to subscribe to a RabbitMQ queue.

PARAMETER DESCRIPTION self

the instance of the class

queue

the queue to subscribe to, can be a string or a RabbitQueue object

*broker_args

additional arguments for the broker

DEFAULT: ()

**broker_kwargs

additional keyword arguments for the broker

DEFAULT: {}

RETURNS DESCRIPTION Callable[[Callable[P_HandlerParams, T_HandlerReturn]], HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn]]

A callable object that wraps the handler function for the incoming messages from the queue.

RAISES DESCRIPTION TypeError

If the queue is not a string or a RabbitQueue object

Source code in faststream/rabbit/shared/router.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    queue: Union[str, RabbitQueue],\n    *broker_args: Any,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[IncomingMessage, P_HandlerParams, T_HandlerReturn],\n]:\n    \"\"\"A function to subscribe to a RabbitMQ queue.\n\n    Args:\n        self : the instance of the class\n        queue : the queue to subscribe to, can be a string or a RabbitQueue object\n        *broker_args : additional arguments for the broker\n        **broker_kwargs : additional keyword arguments for the broker\n\n    Returns:\n        A callable object that wraps the handler function for the incoming messages from the queue.\n\n    Raises:\n        TypeError: If the queue is not a string or a RabbitQueue object\n\n    \"\"\"\n    q = RabbitQueue.validate(queue)\n    new_q = model_copy(q, update={\"name\": self.prefix + q.name})\n    return self._wrap_subscriber(new_q, *broker_args, **broker_kwargs)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/BaseRMQInformation/","title":"BaseRMQInformation","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/BaseRMQInformation/#faststream.rabbit.shared.schemas.BaseRMQInformation","title":"faststream.rabbit.shared.schemas.BaseRMQInformation dataclass","text":"

BaseRMQInformation.

","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/BaseRMQInformation/#faststream.rabbit.shared.schemas.BaseRMQInformation.exchange","title":"exchange class-attribute instance-attribute","text":"
exchange: Optional[RabbitExchange] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/BaseRMQInformation/#faststream.rabbit.shared.schemas.BaseRMQInformation.queue","title":"queue class-attribute instance-attribute","text":"
queue: RabbitQueue = field(default=RabbitQueue(''))\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/BaseRMQInformation/#faststream.rabbit.shared.schemas.BaseRMQInformation.virtual_host","title":"virtual_host class-attribute instance-attribute","text":"
virtual_host: str = '/'\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/","title":"RabbitExchange","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange","title":"faststream.rabbit.shared.schemas.RabbitExchange","text":"
RabbitExchange(\n    name: str,\n    type: ExchangeType = ExchangeType.DIRECT,\n    durable: bool = False,\n    auto_delete: bool = False,\n    internal: bool = False,\n    passive: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_to: Optional[RabbitExchange] = None,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n)\n

Bases: NameRequired

A class to represent a RabbitMQ exchange.

METHOD DESCRIPTION __hash__

returns the hash value of the exchange

__init__

initializes the RabbitExchange object

Initialize a RabbitExchange object.

PARAMETER DESCRIPTION name

Name of the exchange.

TYPE: str

type

Type of the exchange. Defaults to ExchangeType.DIRECT.

TYPE: ExchangeType DEFAULT: DIRECT

durable

Whether the exchange should survive broker restarts. Defaults to False.

TYPE: bool DEFAULT: False

auto_delete

Whether the exchange should be deleted when no longer in use. Defaults to False.

TYPE: bool DEFAULT: False

internal

Whether the exchange is used for internal purposes and should not be published to directly. Defaults to False.

TYPE: bool DEFAULT: False

passive

Whether to check if the exchange exists before creating it. Defaults to False.

TYPE: bool DEFAULT: False

arguments

Additional arguments for the exchange. Defaults to None.

TYPE: Optional[AnyDict] DEFAULT: None

timeout

Timeout for the operation. Defaults to None.

TYPE: TimeoutType DEFAULT: None

robust

Whether to use robust mode for the exchange. Defaults to True.

TYPE: bool DEFAULT: True

bind_to

Exchange to bind to. Defaults to None.

TYPE: Optional[RabbitExchange] DEFAULT: None

bind_arguments

Arguments for the binding. Defaults to None.

TYPE: Optional[AnyDict] DEFAULT: None

routing_key

Routing key for the exchange. Defaults to \"\".

TYPE: str DEFAULT: ''

RAISES DESCRIPTION NotImplementedError Source code in faststream/rabbit/shared/schemas.py
def __init__(\n    self,\n    name: str,\n    type: ExchangeType = ExchangeType.DIRECT,\n    durable: bool = False,\n    auto_delete: bool = False,\n    internal: bool = False,\n    passive: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_to: Optional[\"RabbitExchange\"] = None,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n) -> None:\n    \"\"\"Initialize a RabbitExchange object.\n\n    Args:\n        name (str): Name of the exchange.\n        type (ExchangeType, optional): Type of the exchange. Defaults to ExchangeType.DIRECT.\n        durable (bool, optional): Whether the exchange should survive broker restarts. Defaults to False.\n        auto_delete (bool, optional): Whether the exchange should be deleted when no longer in use. Defaults to False.\n        internal (bool, optional): Whether the exchange is used for internal purposes and should not be published to directly. Defaults to False.\n        passive (bool, optional): Whether to check if the exchange exists before creating it. Defaults to False.\n        arguments (Optional[AnyDict], optional): Additional arguments for the exchange. Defaults to None.\n        timeout (TimeoutType, optional): Timeout for the operation. Defaults to None.\n        robust (bool, optional): Whether to use robust mode for the exchange. Defaults to True.\n        bind_to (Optional[\"RabbitExchange\"], optional): Exchange to bind to. Defaults to None.\n        bind_arguments (Optional[AnyDict], optional): Arguments for the binding. Defaults to None.\n        routing_key (str, optional): Routing key for the exchange. Defaults to \"\".\n\n    Raises:\n        NotImplementedError:\n\n    \"\"\"\n    if routing_key and bind_to is None:  # pragma: no cover\n        warnings.warn(\n            (\n                \"\\nRabbitExchange `routing_key` is using to bind exchange to another one\"\n                \"\\nIt can be used only with the `bind_to` argument, please setup it too\"\n            ),\n            category=RuntimeWarning,\n            stacklevel=1,\n        )\n\n    super().__init__(\n        name=name,\n        type=type.value,\n        durable=durable,\n        auto_delete=auto_delete,\n        routing_key=routing_key,\n        bind_to=bind_to,\n        bind_arguments=bind_arguments,\n        robust=robust,\n        internal=internal,\n        passive=passive,\n        timeout=timeout,\n        arguments=arguments,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.arguments","title":"arguments class-attribute instance-attribute","text":"
arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.auto_delete","title":"auto_delete class-attribute instance-attribute","text":"
auto_delete: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.bind_arguments","title":"bind_arguments class-attribute instance-attribute","text":"
bind_arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.bind_to","title":"bind_to class-attribute instance-attribute","text":"
bind_to: Optional[RabbitExchange] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.durable","title":"durable class-attribute instance-attribute","text":"
durable: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.internal","title":"internal class-attribute instance-attribute","text":"
internal: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.passive","title":"passive class-attribute instance-attribute","text":"
passive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.robust","title":"robust class-attribute instance-attribute","text":"
robust: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.type","title":"type class-attribute instance-attribute","text":"
type: str = ExchangeType.DIRECT.value\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitExchange/#faststream.rabbit.shared.schemas.RabbitExchange.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/","title":"RabbitQueue","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue","title":"faststream.rabbit.shared.schemas.RabbitQueue","text":"
RabbitQueue(\n    name: str,\n    durable: bool = False,\n    exclusive: bool = False,\n    passive: bool = False,\n    auto_delete: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n)\n

Bases: NameRequired

A class to represent a RabbitMQ queue.

METHOD DESCRIPTION __hash__

returns the hash value of the queue

routing

returns the routing key of the queue

__init__

initializes the RabbitQueue object with the given parameters

Initialize a class object.

PARAMETER DESCRIPTION name

The name of the object.

TYPE: str

durable

Whether the object is durable. Defaults to False.

TYPE: bool DEFAULT: False

exclusive

Whether the object is exclusive. Defaults to False.

TYPE: bool DEFAULT: False

passive

Whether the object is passive. Defaults to False.

TYPE: bool DEFAULT: False

auto_delete

Whether the object is auto delete. Defaults to False.

TYPE: bool DEFAULT: False

arguments

Additional arguments for the object. Defaults to None.

TYPE: dict DEFAULT: None

timeout

Timeout for the object. Defaults to None.

TYPE: TimeoutType DEFAULT: None

robust

Whether the object is robust. Defaults to True.

TYPE: bool DEFAULT: True

bind_arguments

Bind arguments for the object. Defaults to None.

TYPE: dict DEFAULT: None

routing_key

Routing key for the object. Defaults to \"\".

TYPE: str DEFAULT: ''

Source code in faststream/rabbit/shared/schemas.py
def __init__(\n    self,\n    name: str,\n    durable: bool = False,\n    exclusive: bool = False,\n    passive: bool = False,\n    auto_delete: bool = False,\n    arguments: Optional[AnyDict] = None,\n    timeout: TimeoutType = None,\n    robust: bool = True,\n    bind_arguments: Optional[AnyDict] = None,\n    routing_key: str = \"\",\n) -> None:\n    \"\"\"Initialize a class object.\n\n    Args:\n        name (str): The name of the object.\n        durable (bool, optional): Whether the object is durable. Defaults to False.\n        exclusive (bool, optional): Whether the object is exclusive. Defaults to False.\n        passive (bool, optional): Whether the object is passive. Defaults to False.\n        auto_delete (bool, optional): Whether the object is auto delete. Defaults to False.\n        arguments (dict, optional): Additional arguments for the object. Defaults to None.\n        timeout (TimeoutType, optional): Timeout for the object. Defaults to None.\n        robust (bool, optional): Whether the object is robust. Defaults to True.\n        bind_arguments (dict, optional): Bind arguments for the object. Defaults to None.\n        routing_key (str, optional): Routing key for the object. Defaults to \"\".\n\n    \"\"\"\n    re, routing_key = compile_path(routing_key, replace_symbol=\"*\")\n    super().__init__(\n        name=name,\n        path_regex=re,\n        durable=durable,\n        exclusive=exclusive,\n        bind_arguments=bind_arguments,\n        routing_key=routing_key,\n        robust=robust,\n        passive=passive,\n        auto_delete=auto_delete,\n        arguments=arguments,\n        timeout=timeout,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.arguments","title":"arguments class-attribute instance-attribute","text":"
arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.auto_delete","title":"auto_delete class-attribute instance-attribute","text":"
auto_delete: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.bind_arguments","title":"bind_arguments class-attribute instance-attribute","text":"
bind_arguments: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.durable","title":"durable class-attribute instance-attribute","text":"
durable: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.exclusive","title":"exclusive class-attribute instance-attribute","text":"
exclusive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'arbitrary_types_allowed': True}\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.name","title":"name class-attribute instance-attribute","text":"
name: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.passive","title":"passive class-attribute instance-attribute","text":"
passive: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.path_regex","title":"path_regex class-attribute instance-attribute","text":"
path_regex: Optional[Pattern[str]] = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.robust","title":"robust class-attribute instance-attribute","text":"
robust: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.routing","title":"routing property","text":"
routing: str\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.routing_key","title":"routing_key class-attribute instance-attribute","text":"
routing_key: str = ''\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.timeout","title":"timeout class-attribute instance-attribute","text":"
timeout: TimeoutType = None\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.Config.arbitrary_types_allowed","title":"arbitrary_types_allowed class-attribute instance-attribute","text":"
arbitrary_types_allowed = True\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/RabbitQueue/#faststream.rabbit.shared.schemas.RabbitQueue.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/ReplyConfig/","title":"ReplyConfig","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/ReplyConfig/#faststream.rabbit.shared.schemas.ReplyConfig","title":"faststream.rabbit.shared.schemas.ReplyConfig","text":"

Bases: BaseModel

","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/ReplyConfig/#faststream.rabbit.shared.schemas.ReplyConfig.immediate","title":"immediate class-attribute instance-attribute","text":"
immediate: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/ReplyConfig/#faststream.rabbit.shared.schemas.ReplyConfig.mandatory","title":"mandatory class-attribute instance-attribute","text":"
mandatory: bool = True\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/ReplyConfig/#faststream.rabbit.shared.schemas.ReplyConfig.persist","title":"persist class-attribute instance-attribute","text":"
persist: bool = False\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/get_routing_hash/","title":"get_routing_hash","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/schemas/get_routing_hash/#faststream.rabbit.shared.schemas.get_routing_hash","title":"faststream.rabbit.shared.schemas.get_routing_hash","text":"
get_routing_hash(\n    queue: RabbitQueue,\n    exchange: Optional[RabbitExchange] = None,\n) -> int\n

Calculate the routing hash for a RabbitMQ queue and exchange.

PARAMETER DESCRIPTION queue

The RabbitMQ queue.

TYPE: RabbitQueue

exchange

The RabbitMQ exchange (optional).

TYPE: Optional[RabbitExchange] DEFAULT: None

RETURNS DESCRIPTION int

The routing hash as an integer.

Source code in faststream/rabbit/shared/schemas.py
def get_routing_hash(\n    queue: RabbitQueue,\n    exchange: Optional[RabbitExchange] = None,\n) -> int:\n    \"\"\"Calculate the routing hash for a RabbitMQ queue and exchange.\n\n    Args:\n        queue: The RabbitMQ queue.\n        exchange: The RabbitMQ exchange (optional).\n\n    Returns:\n        The routing hash as an integer.\n\n    \"\"\"\n    return hash(queue) + hash(exchange or \"\")\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/utils/build_url/","title":"build_url","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/utils/build_url/#faststream.rabbit.shared.utils.build_url","title":"faststream.rabbit.shared.utils.build_url","text":"
build_url(\n    url: Union[str, URL, None] = None,\n    *,\n    host: Optional[str] = None,\n    port: Optional[int] = None,\n    login: Optional[str] = None,\n    password: Optional[str] = None,\n    virtualhost: Optional[str] = None,\n    ssl: Optional[bool] = None,\n    ssl_options: Optional[SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    **kwargs: Any\n) -> URL\n
Source code in faststream/rabbit/shared/utils.py
def build_url(\n    url: Union[str, URL, None] = None,\n    *,\n    host: Optional[str] = None,\n    port: Optional[int] = None,\n    login: Optional[str] = None,\n    password: Optional[str] = None,\n    virtualhost: Optional[str] = None,\n    ssl: Optional[bool] = None,\n    ssl_options: Optional[SSLOptions] = None,\n    client_properties: Optional[FieldTable] = None,\n    **kwargs: Any,\n) -> URL:\n    original_url = make_url(url)\n\n    return make_url(\n        host=host or original_url.host or \"localhost\",\n        port=port or original_url.port or 5672,\n        login=login or original_url.user or \"guest\",\n        password=password or original_url.password or \"guest\",\n        virtualhost=virtualhost or removeprefix(original_url.path, \"/\"),\n        ssl=ssl or original_url.scheme == \"amqps\",\n        ssl_options=ssl_options,\n        client_properties=client_properties,\n        **{\n            **kwargs,\n            **dict(original_url.query),\n        },\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/shared/utils/removeprefix/","title":"removeprefix","text":"","boost":0.5},{"location":"api/faststream/rabbit/shared/utils/removeprefix/#faststream.rabbit.shared.utils.removeprefix","title":"faststream.rabbit.shared.utils.removeprefix","text":"
removeprefix(string: str, prefix: str) -> str\n
Source code in faststream/rabbit/shared/utils.py
def removeprefix(string: str, prefix: str) -> str:\n    if string.startswith(prefix):\n        return string[len(prefix) :]\n    return string\n
","boost":0.5},{"location":"api/faststream/rabbit/test/FakeProducer/","title":"FakeProducer","text":"","boost":0.5},{"location":"api/faststream/rabbit/test/FakeProducer/#faststream.rabbit.test.FakeProducer","title":"faststream.rabbit.test.FakeProducer","text":"
FakeProducer(broker: RabbitBroker)\n

Bases: AioPikaFastProducer

A fake RabbitMQ producer for testing purposes.

This class extends AioPikaFastProducer and is used to simulate RabbitMQ message publishing during tests.

Initialize a FakeProducer instance.

PARAMETER DESCRIPTION broker

The RabbitBroker instance to be used for message publishing.

TYPE: RabbitBroker

Source code in faststream/rabbit/test.py
def __init__(self, broker: RabbitBroker) -> None:\n    \"\"\"\n    Initialize a FakeProducer instance.\n\n    Args:\n        broker (RabbitBroker): The RabbitBroker instance to be used for message publishing.\n    \"\"\"\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/rabbit/test/FakeProducer/#faststream.rabbit.test.FakeProducer.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/rabbit/test/FakeProducer/#faststream.rabbit.test.FakeProducer.declarer","title":"declarer instance-attribute","text":"
declarer: RabbitDeclarer = declarer\n
","boost":0.5},{"location":"api/faststream/rabbit/test/FakeProducer/#faststream.rabbit.test.FakeProducer.publish","title":"publish async","text":"
publish(\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any\n) -> Optional[SendableMessage]\n

Publish a message to a RabbitMQ queue or exchange.

PARAMETER DESCRIPTION message

The message to be published.

TYPE: AioPikaSendableMessage DEFAULT: ''

queue

The target queue for the message.

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The target exchange for the message.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The routing key for the message.

TYPE: str DEFAULT: ''

mandatory

Whether the message is mandatory.

TYPE: bool DEFAULT: True

immediate

Whether the message should be sent immediately.

TYPE: bool DEFAULT: False

timeout

The timeout for the message.

TYPE: TimeoutType DEFAULT: None

rpc

Whether the message is for RPC.

TYPE: bool DEFAULT: False

rpc_timeout

The RPC timeout.

TYPE: float DEFAULT: 30.0

raise_timeout

Whether to raise a timeout exception.

TYPE: bool DEFAULT: False

persist

Whether to persist the message.

TYPE: bool DEFAULT: False

reply_to

The reply-to address for RPC messages.

TYPE: str DEFAULT: None

**message_kwargs

Additional message properties and content.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION Optional[SendableMessage]

Optional[SendableMessage]: The published message if successful, or None if not.

Source code in faststream/rabbit/test.py
async def publish(\n    self,\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    mandatory: bool = True,\n    immediate: bool = False,\n    timeout: TimeoutType = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n    persist: bool = False,\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any,\n) -> Optional[SendableMessage]:\n    \"\"\"\n    Publish a message to a RabbitMQ queue or exchange.\n\n    Args:\n        message (AioPikaSendableMessage, optional): The message to be published.\n        queue (Union[RabbitQueue, str], optional): The target queue for the message.\n        exchange (Union[RabbitExchange, str, None], optional): The target exchange for the message.\n        routing_key (str, optional): The routing key for the message.\n        mandatory (bool, optional): Whether the message is mandatory.\n        immediate (bool, optional): Whether the message should be sent immediately.\n        timeout (TimeoutType, optional): The timeout for the message.\n        rpc (bool, optional): Whether the message is for RPC.\n        rpc_timeout (float, optional): The RPC timeout.\n        raise_timeout (bool, optional): Whether to raise a timeout exception.\n        persist (bool, optional): Whether to persist the message.\n        reply_to (str, optional): The reply-to address for RPC messages.\n        **message_kwargs (Any): Additional message properties and content.\n\n    Returns:\n        Optional[SendableMessage]: The published message if successful, or None if not.\n    \"\"\"\n    exch = RabbitExchange.validate(exchange)\n\n    incoming = build_message(\n        message=message,\n        queue=queue,\n        exchange=exch,\n        routing_key=routing_key,\n        reply_to=reply_to,\n        **message_kwargs,\n    )\n\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        if handler.exchange == exch:\n            call: bool = False\n\n            if (\n                handler.exchange is None\n                or handler.exchange.type == ExchangeType.DIRECT\n            ):\n                call = handler.queue.name == incoming.routing_key\n\n            elif handler.exchange.type == ExchangeType.FANOUT:\n                call = True\n\n            elif handler.exchange.type == ExchangeType.TOPIC:\n                call = bool(\n                    re.match(\n                        handler.queue.routing_key.replace(\".\", r\"\\.\").replace(\n                            \"*\", \".*\"\n                        ),\n                        incoming.routing_key or \"\",\n                    )\n                )\n\n            elif handler.exchange.type == ExchangeType.HEADERS:  # pramga: no branch\n                queue_headers = (handler.queue.bind_arguments or {}).copy()\n                msg_headers = incoming.headers\n\n                if not queue_headers:\n                    call = True\n\n                else:\n                    matcher = queue_headers.pop(\"x-match\", \"all\")\n\n                    full = True\n                    none = True\n                    for k, v in queue_headers.items():\n                        if msg_headers.get(k) != v:\n                            full = False\n                        else:\n                            none = False\n\n                    if not none:\n                        call = (matcher == \"any\") or full\n\n            else:  # pragma: no cover\n                raise AssertionError(\"unreachable\")\n\n            if call:\n                r = await call_handler(\n                    handler=handler,\n                    message=incoming,\n                    rpc=rpc,\n                    rpc_timeout=rpc_timeout,\n                    raise_timeout=raise_timeout,\n                )\n\n                if rpc:  # pragma: no branch\n                    return r\n\n    return None\n
","boost":0.5},{"location":"api/faststream/rabbit/test/PatchedMessage/","title":"PatchedMessage","text":"","boost":0.5},{"location":"api/faststream/rabbit/test/PatchedMessage/#faststream.rabbit.test.PatchedMessage","title":"faststream.rabbit.test.PatchedMessage","text":"

Bases: IncomingMessage

Patched message class for testing purposes.

This class extends aio_pika's IncomingMessage class and is used to simulate RabbitMQ message handling during tests.

","boost":0.5},{"location":"api/faststream/rabbit/test/PatchedMessage/#faststream.rabbit.test.PatchedMessage.ack","title":"ack async","text":"
ack(multiple: bool = False) -> None\n

Asynchronously acknowledge a message.

PARAMETER DESCRIPTION multiple

Whether to acknowledge multiple messages at once. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/test.py
async def ack(self, multiple: bool = False) -> None:\n    \"\"\"Asynchronously acknowledge a message.\n\n    Args:\n        multiple (bool, optional): Whether to acknowledge multiple messages at once. Defaults to False.\n\n    Returns:\n        None\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/rabbit/test/PatchedMessage/#faststream.rabbit.test.PatchedMessage.nack","title":"nack async","text":"
nack(multiple: bool = False, requeue: bool = True) -> None\n

Nack the message.

PARAMETER DESCRIPTION multiple

Whether to nack multiple messages. Default is False.

TYPE: bool DEFAULT: False

requeue

Whether to requeue the message. Default is True.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/test.py
async def nack(self, multiple: bool = False, requeue: bool = True) -> None:\n    \"\"\"Nack the message.\n\n    Args:\n        multiple: Whether to nack multiple messages. Default is False.\n        requeue: Whether to requeue the message. Default is True.\n\n    Returns:\n        None\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/rabbit/test/PatchedMessage/#faststream.rabbit.test.PatchedMessage.reject","title":"reject async","text":"
reject(requeue: bool = False) -> None\n

Rejects a task.

PARAMETER DESCRIPTION requeue

Whether to requeue the task if it fails (default: False)

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION None

None

Source code in faststream/rabbit/test.py
async def reject(self, requeue: bool = False) -> None:\n    \"\"\"Rejects a task.\n\n    Args:\n        requeue: Whether to requeue the task if it fails (default: False)\n\n    Returns:\n        None\n    \"\"\"\n    pass\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/","title":"TestRabbitBroker","text":"","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker","title":"faststream.rabbit.test.TestRabbitBroker","text":"
TestRabbitBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[RabbitBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: RabbitBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: RabbitBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(\n        queue=publisher.queue,\n        exchange=publisher.exchange,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: RabbitBroker, publisher: Any\n) -> None\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef patch_publisher(broker: RabbitBroker, publisher: Any) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/rabbit/test/TestRabbitBroker/#faststream.rabbit.test.TestRabbitBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: RabbitBroker, publisher: Publisher\n) -> None\n
Source code in faststream/rabbit/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: RabbitBroker,\n    publisher: Publisher,\n) -> None:\n    broker.handlers.pop(\n        publisher._get_routing_hash(),\n        None,\n    )\n
","boost":0.5},{"location":"api/faststream/rabbit/test/build_message/","title":"build_message","text":"","boost":0.5},{"location":"api/faststream/rabbit/test/build_message/#faststream.rabbit.test.build_message","title":"faststream.rabbit.test.build_message","text":"
build_message(\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any\n) -> PatchedMessage\n

Build a patched RabbitMQ message for testing.

PARAMETER DESCRIPTION message

The message content.

TYPE: AioPikaSendableMessage DEFAULT: ''

queue

The message queue.

TYPE: Union[RabbitQueue, str] DEFAULT: ''

exchange

The message exchange.

TYPE: Union[RabbitExchange, str, None] DEFAULT: None

routing_key

The message routing key.

TYPE: str DEFAULT: ''

reply_to

The reply-to queue.

TYPE: Optional[str] DEFAULT: None

**message_kwargs

Additional message arguments.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION PatchedMessage

A patched RabbitMQ message.

TYPE: PatchedMessage

Source code in faststream/rabbit/test.py
def build_message(\n    message: AioPikaSendableMessage = \"\",\n    queue: Union[RabbitQueue, str] = \"\",\n    exchange: Union[RabbitExchange, str, None] = None,\n    *,\n    routing_key: str = \"\",\n    reply_to: Optional[str] = None,\n    **message_kwargs: Any,\n) -> PatchedMessage:\n    \"\"\"\n    Build a patched RabbitMQ message for testing.\n\n    Args:\n        message (AioPikaSendableMessage): The message content.\n        queue (Union[RabbitQueue, str]): The message queue.\n        exchange (Union[RabbitExchange, str, None]): The message exchange.\n        routing_key (str): The message routing key.\n        reply_to (Optional[str]): The reply-to queue.\n        **message_kwargs (Any): Additional message arguments.\n\n    Returns:\n        PatchedMessage: A patched RabbitMQ message.\n    \"\"\"\n    que = RabbitQueue.validate(queue)\n    exch = RabbitExchange.validate(exchange)\n    msg = AioPikaParser.encode_message(\n        message=message,\n        persist=False,\n        reply_to=reply_to,\n        callback_queue=None,\n        **message_kwargs,\n    )\n\n    routing = routing_key or (getattr(que, \"name\", \"\"))\n\n    return PatchedMessage(\n        aiormq.abc.DeliveredMessage(\n            delivery=spec.Basic.Deliver(\n                exchange=getattr(exch, \"name\", \"\"),\n                routing_key=routing,\n            ),\n            header=ContentHeader(\n                properties=spec.Basic.Properties(\n                    content_type=msg.content_type,\n                    message_id=str(uuid4()),\n                    headers=msg.headers,\n                    reply_to=reply_to,\n                )\n            ),\n            body=msg.body,\n            channel=AsyncMock(),\n        )\n    )\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/","title":"ListSub","text":"","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub","title":"faststream.redis.ListSub","text":"
ListSub(\n    channel: str,\n    batch: bool = False,\n    max_records: PositiveInt = 10,\n    polling_interval: PositiveFloat = 0.1,\n)\n

Bases: NameRequired

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    channel: str,\n    batch: bool = False,\n    max_records: PositiveInt = 10,\n    polling_interval: PositiveFloat = 0.1,\n) -> None:\n    super().__init__(\n        name=channel,\n        batch=batch,\n        max_records=max_records,\n        polling_interval=polling_interval,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.max_records","title":"max_records class-attribute instance-attribute","text":"
max_records: PositiveInt = 10\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: PositiveFloat = 0.1\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.records","title":"records property","text":"
records: Optional[PositiveInt]\n
","boost":0.5},{"location":"api/faststream/redis/ListSub/#faststream.redis.ListSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/","title":"PubSub","text":"","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub","title":"faststream.redis.PubSub","text":"
PubSub(\n    channel: str,\n    pattern: bool = False,\n    polling_interval: PositiveFloat = 1.0,\n)\n

Bases: NameRequired

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    channel: str,\n    pattern: bool = False,\n    polling_interval: PositiveFloat = 1.0,\n) -> None:\n    reg, path = compile_path(channel, replace_symbol=\"*\")\n\n    if reg is not None:\n        pattern = True\n\n    super().__init__(\n        name=path,\n        path_regex=reg,\n        pattern=pattern,\n        polling_interval=polling_interval,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.last_id","title":"last_id class-attribute instance-attribute","text":"
last_id: str = '$'\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'arbitrary_types_allowed': True}\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.path_regex","title":"path_regex class-attribute instance-attribute","text":"
path_regex: Optional[Pattern[str]] = None\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.pattern","title":"pattern class-attribute instance-attribute","text":"
pattern: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: PositiveFloat = 1.0\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.Config.arbitrary_types_allowed","title":"arbitrary_types_allowed class-attribute instance-attribute","text":"
arbitrary_types_allowed = True\n
","boost":0.5},{"location":"api/faststream/redis/PubSub/#faststream.redis.PubSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/","title":"RedisBroker","text":"","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker","title":"faststream.redis.RedisBroker","text":"
RedisBroker(\n    url: str = \"redis://localhost:6379\",\n    polling_interval: Optional[float] = None,\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"custom\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: RedisLoggingMixin, BrokerAsyncUsecase[AnyRedisDict, 'Redis[bytes]']

Source code in faststream/redis/broker.py
def __init__(\n    self,\n    url: str = \"redis://localhost:6379\",\n    polling_interval: Optional[float] = None,\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"custom\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    self.global_polling_interval = polling_interval\n    self._producer = None\n\n    super().__init__(\n        url=url,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n    )\n\n    url_kwargs = urlparse(self.url)\n    self.protocol = protocol or url_kwargs.scheme\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.global_polling_interval","title":"global_polling_interval instance-attribute","text":"
global_polling_interval = polling_interval\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[int, Handler]\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol or url_kwargs.scheme\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.connect","title":"connect async","text":"
connect(*args: Any, **kwargs: Any) -> Redis[bytes]\n
Source code in faststream/redis/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> \"Redis[bytes]\":\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, **kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.publish_batch","title":"publish_batch async","text":"
publish_batch(*args: Any, **kwargs: Any) -> None\n
Source code in faststream/redis/broker.py
async def publish_batch(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish_batch(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.publisher","title":"publisher","text":"
publisher(\n    channel: Union[Channel, PubSub, None] = None,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/redis/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    channel: Union[Channel, PubSub, None] = None,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    channel = PubSub.validate(channel)\n    list = ListSub.validate(list)\n    stream = StreamSub.validate(stream)\n\n    any_of = channel or list or stream\n    if any_of is None:\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    key = Handler.get_routing_hash(any_of)\n    publisher = self._publishers.get(\n        key,\n        Publisher(\n            channel=channel,\n            list=list,\n            stream=stream,\n            headers=headers,\n            reply_to=reply_to,\n            # AsyncAPI\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(key, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.start","title":"start async","text":"
start() -> None\n
Source code in faststream/redis/broker.py
async def start(self) -> None:\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n    assert self._connection, NOT_CONNECTED_YET  # nosec B101\n\n    for handler in self.handlers.values():\n        if (stream := handler.stream_sub) is not None and stream.group:\n            try:\n                await self._connection.xgroup_create(\n                    name=stream.name,\n                    groupname=stream.group,\n                    mkstream=True,\n                )\n            except ResponseError as e:\n                if \"already exists\" not in str(e):\n                    raise e\n\n        c = self._get_log_context(None, handler.channel_name)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self._connection)\n
","boost":0.5},{"location":"api/faststream/redis/RedisBroker/#faststream.redis.RedisBroker.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Any, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[AnyRedisDict, RedisMessage]] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[Any, P_HandlerParams, T_HandlerReturn],\n]:\n    channel = PubSub.validate(channel)\n    list = ListSub.validate(list)\n    stream = StreamSub.validate(stream)\n\n    if (any_of := channel or list or stream) is None:\n        raise ValueError(\n            \"You should specify `channel`, `list`, `stream` subscriber type\"\n        )\n\n    if all((channel, list)):\n        raise ValueError(\"You can't use `PubSub` and `ListSub` both\")\n    elif all((channel, stream)):\n        raise ValueError(\"You can't use `PubSub` and `StreamSub` both\")\n    elif all((list, stream)):\n        raise ValueError(\"You can't use `ListSub` and `StreamSub` both\")\n\n    self._setup_log_context(channel=any_of.name)\n    super().subscriber()\n\n    key = Handler.get_routing_hash(any_of)\n    handler = self.handlers[key] = self.handlers.get(\n        key,\n        Handler(  # type: ignore[abstract]\n            log_context_builder=partial(\n                self._get_log_context,\n                channel=any_of.name,\n            ),\n            graceful_timeout=self.graceful_timeout,\n            # Redis\n            channel=channel,\n            list=list,\n            stream=stream,\n            # AsyncAPI\n            title=title,\n            description=description,\n            include_in_schema=include_in_schema,\n        ),\n    )\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[AnyRedisDict, P_HandlerParams, T_HandlerReturn,]:\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,  # type: ignore[arg-type]\n            decoder=decoder or self._global_decoder,  # type: ignore[arg-type]\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/redis/RedisRoute/","title":"RedisRoute","text":"","boost":0.5},{"location":"api/faststream/redis/RedisRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/redis/RedisRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/redis/RedisRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/redis/RedisRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/","title":"RedisRouter","text":"","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter","title":"faststream.redis.RedisRouter","text":"
RedisRouter(\n    prefix: str = \"\",\n    handlers: Sequence[RedisRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    include_in_schema: bool = True\n)\n

Bases: RedisRouter

Source code in faststream/redis/router.py
            publisher.list, update={\"name\": prefix + publisher.list.name}\n        )\n    elif publisher.stream is not None:\n        publisher.stream = model_copy(\n            publisher.stream, update={\"name\": prefix + publisher.stream.name}\n        )\n    else:\n        raise AssertionError(\"unreachable\")\n    return publisher\n\n@override\ndef publisher(  # type: ignore[override]\n    self,\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.publisher","title":"publisher","text":"
publisher(\n    channel: Union[str, PubSub, None] = None,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/redis/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    channel: Union[str, PubSub, None] = None,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    if not any((stream, list, channel)):\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            channel=PubSub.validate(channel),\n            list=ListSub.validate(list),\n            stream=StreamSub.validate(stream),\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/redis/RedisRouter/#faststream.redis.RedisRouter.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[str, PubSub, None] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Any, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/router.py
) -> Publisher:\n    if not any((stream, list, channel)):\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            channel=PubSub.validate(channel),\n            list=ListSub.validate(list),\n            stream=StreamSub.validate(stream),\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/","title":"StreamSub","text":"","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub","title":"faststream.redis.StreamSub","text":"
StreamSub(\n    stream: str,\n    polling_interval: Optional[PositiveInt] = 100,\n    group: Optional[str] = None,\n    consumer: Optional[str] = None,\n    batch: bool = False,\n    no_ack: bool = False,\n    last_id: Optional[str] = None,\n)\n

Bases: NameRequired

Redis Stream subscriber parameters

PARAMETER DESCRIPTION stream

(str): Redis Stream name.

TYPE: str

polling_interval

(int:ms | None): wait message block.

TYPE: Optional[PositiveInt] DEFAULT: 100

group

(str | None): consumer group name.

TYPE: Optional[str] DEFAULT: None

consumer

(str | None): consumer name.

TYPE: Optional[str] DEFAULT: None

batch

(bool): consume messages in batches.

TYPE: bool DEFAULT: False

no_ack

(bool): do not add message to PEL.

TYPE: bool DEFAULT: False

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    stream: str,\n    polling_interval: Optional[PositiveInt] = 100,\n    group: Optional[str] = None,\n    consumer: Optional[str] = None,\n    batch: bool = False,\n    no_ack: bool = False,\n    last_id: Optional[str] = None,\n) -> None:\n    \"\"\"\n    Redis Stream subscriber parameters\n\n    Args:\n        stream: (str): Redis Stream name.\n        polling_interval: (int:ms | None): wait message block.\n        group: (str | None): consumer group name.\n        consumer: (str | None): consumer name.\n        batch: (bool): consume messages in batches.\n        no_ack: (bool): do not add message to PEL.\n    \"\"\"\n    if (group and not consumer) or (not group and consumer):\n        raise ValueError(\"You should specify `group` and `consumer` both\")\n\n    if group and consumer:\n        msg: Optional[str] = None\n\n        if last_id:\n            msg = \"`last_id` has no effect with consumer group\"\n\n        if no_ack:\n            msg = \"`no_ack` has no effect with consumer group\"\n\n        if msg:\n            warnings.warn(\n                message=msg,\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n    super().__init__(\n        name=stream,\n        group=group,\n        consumer=consumer,\n        polling_interval=polling_interval,\n        batch=batch,\n        no_ack=no_ack,\n        last_id=last_id or \"$\",\n    )\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.consumer","title":"consumer class-attribute instance-attribute","text":"
consumer: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.group","title":"group class-attribute instance-attribute","text":"
group: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.last_id","title":"last_id class-attribute instance-attribute","text":"
last_id: str = '$'\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.no_ack","title":"no_ack class-attribute instance-attribute","text":"
no_ack: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: Optional[PositiveInt] = Field(\n    default=100, description=\"ms\"\n)\n
","boost":0.5},{"location":"api/faststream/redis/StreamSub/#faststream.redis.StreamSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/TestApp/","title":"TestApp","text":"","boost":0.5},{"location":"api/faststream/redis/TestApp/#faststream.broker.test.TestApp","title":"faststream.broker.test.TestApp","text":"
TestApp(\n    app: FastStream,\n    run_extra_options: Optional[\n        Dict[str, SettingField]\n    ] = None,\n)\n

A class to represent a test application.

METHOD DESCRIPTION __init__

initializes the TestApp object

__aenter__

enters the asynchronous context and starts the FastStream application

__aexit__

exits the asynchronous context and stops the FastStream application

Initialize a class instance.

PARAMETER DESCRIPTION app

An instance of the FastStream class.

TYPE: FastStream

run_extra_options

Optional dictionary of extra options for running the application.

TYPE: Optional[Dict[str, SettingField]] DEFAULT: None

RETURNS DESCRIPTION None

None

Source code in faststream/broker/test.py
def __init__(\n    self,\n    app: FastStream,\n    run_extra_options: Optional[Dict[str, SettingField]] = None,\n) -> None:\n    \"\"\"Initialize a class instance.\n\n    Args:\n        app: An instance of the FastStream class.\n        run_extra_options: Optional dictionary of extra options for running the application.\n\n    Returns:\n        None\n\n    \"\"\"\n    self.app = app\n    self._extra_options = run_extra_options or {}\n
","boost":0.5},{"location":"api/faststream/redis/TestApp/#faststream.broker.test.TestApp.app","title":"app instance-attribute","text":"
app: FastStream = app\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/","title":"TestRedisBroker","text":"","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker","title":"faststream.redis.TestRedisBroker","text":"
TestRedisBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[RedisBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: RedisBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/redis/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: RedisBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(\n        channel=publisher.channel,\n        list=publisher.list,\n        stream=publisher.stream,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: RedisBroker, publisher: Any\n) -> None\n
Source code in faststream/redis/test.py
@staticmethod\ndef patch_publisher(\n    broker: RedisBroker,\n    publisher: Any,\n) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/redis/TestRedisBroker/#faststream.redis.TestRedisBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: RedisBroker, publisher: Publisher\n) -> None\n
Source code in faststream/redis/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: RedisBroker,\n    publisher: Publisher,\n) -> None:\n    any_of = publisher.channel or publisher.list or publisher.stream\n    assert any_of  # nosec B101\n    broker.handlers.pop(Handler.get_routing_hash(any_of), None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/","title":"Handler","text":"","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler","title":"faststream.redis.asyncapi.Handler","text":"
Handler(\n    *,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    channel: Optional[PubSub] = None,\n    list: Optional[ListSub] = None,\n    stream: Optional[StreamSub] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True\n)\n

Bases: LogicRedisHandler

Source code in faststream/redis/handler.py
def __init__(\n    self,\n    *,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # Redis info\n    channel: Optional[PubSub] = None,\n    list: Optional[ListSub] = None,\n    stream: Optional[StreamSub] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    self.channel = channel\n    self.list_sub = list\n    self.stream_sub = stream\n\n    self.subscription = None\n    self.task = None\n\n    self.last_id = stream.last_id if stream else \"$\"\n\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.channel","title":"channel instance-attribute","text":"
channel = channel\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.channel_name","title":"channel_name property","text":"
channel_name: str\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.last_id","title":"last_id instance-attribute","text":"
last_id = stream.last_id if stream else '$'\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.list_sub","title":"list_sub instance-attribute","text":"
list_sub = list\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.name","title":"name property","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.stream_sub","title":"stream_sub instance-attribute","text":"
stream_sub = stream\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.subscription","title":"subscription instance-attribute","text":"
subscription: Optional[RPubSub] = None\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.task","title":"task instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        AnyDict, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[AnyDict, RedisMessage]],\n    decoder: Optional[CustomDecoder[RedisMessage]],\n    filter: Filter[RedisMessage],\n    middlewares: Optional[\n        Sequence[Callable[[AnyDict], BaseMiddleware]]\n    ]\n) -> None\n
Source code in faststream/redis/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[AnyDict, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[AnyDict, RedisMessage]],\n    decoder: Optional[CustomDecoder[RedisMessage]],\n    filter: Filter[RedisMessage],\n    middlewares: Optional[Sequence[Callable[[AnyDict], BaseMiddleware]]],\n) -> None:\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, RedisParser.parse_message),\n        decoder=resolve_custom_func(decoder, RedisParser.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/redis/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.task is not None:\n        if not self.task.done():\n            self.task.cancel()\n        self.task = None\n\n    if self.subscription is not None:\n        await self.subscription.unsubscribe()\n        await self.subscription.aclose()  # type: ignore[attr-defined]\n        self.subscription = None\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(channel: Hashable) -> int\n
Source code in faststream/redis/handler.py
@staticmethod\ndef get_routing_hash(channel: Hashable) -> int:\n    return hash(channel)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/redis/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    method = None\n    if self.list_sub is not None:\n        method = \"lpop\"\n\n    elif (ch := self.channel) is not None:\n        if ch.pattern:\n            method = \"psubscribe\"\n        else:\n            method = \"subscribe\"\n\n    elif (stream := self.stream_sub) is not None:\n        if stream.group:\n            method = \"xreadgroup\"\n        else:\n            method = \"xread\"\n\n    else:\n        raise AssertionError(\"unreachable\")\n\n    return {\n        self.name: Channel(\n            description=self.description,\n            subscribe=Operation(\n                message=Message(\n                    title=f\"{self.name}:Message\",\n                    payload=resolve_payloads(payloads),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                redis=redis.ChannelBinding(\n                    channel=self.channel_name,\n                    group_name=getattr(self.stream_sub, \"group\", None),\n                    consumer_name=getattr(self.stream_sub, \"consumer\", None),\n                    method=method,\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Handler/#faststream.redis.asyncapi.Handler.start","title":"start async","text":"
start(client: Redis[bytes]) -> None\n
Source code in faststream/redis/handler.py
@override\nasync def start(self, client: \"Redis[bytes]\") -> None:  # type: ignore[override]\n    self.started = anyio.Event()\n\n    consume: Union[\n        Callable[[], Awaitable[Optional[AnyRedisDict]]],\n        Callable[[], Awaitable[Optional[Sequence[AnyRedisDict]]]],\n    ]\n    sleep: float\n\n    if (list_sub := self.list_sub) is not None:\n        sleep = list_sub.polling_interval\n        consume = partial(\n            self._consume_list_msg,\n            client=client,\n        )\n        self.started.set()\n\n    elif (channel := self.channel) is not None:\n        self.subscription = psub = client.pubsub()\n\n        if channel.pattern:\n            await psub.psubscribe(channel.name)\n        else:\n            await psub.subscribe(channel.name)\n\n        consume = partial(\n            psub.get_message,\n            ignore_subscribe_messages=True,\n            timeout=channel.polling_interval,\n        )\n        sleep = 0.01\n        self.started.set()\n\n    elif self.stream_sub is not None:\n        consume = partial(  # type: ignore[assignment]\n            self._consume_stream_msg,\n            client=client,\n        )\n        sleep = 0.01\n\n    else:\n        raise AssertionError(\"unreachable\")\n\n    await super().start()\n    self.task = asyncio.create_task(self._consume(consume, sleep))\n    # wait until Stream starts to consume\n    await anyio.sleep(0.01)\n    await self.started.wait()\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/","title":"Publisher","text":"","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher","title":"faststream.redis.asyncapi.Publisher","text":"

Bases: LogicPublisher

","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.channel","title":"channel class-attribute instance-attribute","text":"
channel: Optional[PubSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.channel_name","title":"channel_name property","text":"
channel_name: str\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[AnyDict] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.list","title":"list class-attribute instance-attribute","text":"
list: Optional[ListSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.name","title":"name property","text":"
name: str\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.stream","title":"stream class-attribute instance-attribute","text":"
stream: Optional[StreamSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    channel: Union[str, PubSub, None] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage,\n    channel: Union[str, PubSub, None] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n\n    channel = PubSub.validate(channel or self.channel)\n    list = ListSub.validate(list or self.list)\n    stream = StreamSub.validate(stream or self.stream)\n\n    assert any(\n        (channel, list, stream)\n    ), \"You have to specify outgoing channel\"  # nosec B101\n\n    headers_to_send = (self.headers or {}).copy()\n    if headers is not None:\n        headers_to_send.update(headers)\n\n    if getattr(list, \"batch\", False):\n        await self._producer.publish_batch(\n            *message,\n            list=list.name,  # type: ignore[union-attr]\n        )\n        return None\n\n    else:\n        return await self._producer.publish(\n            message=message,\n            channel=getattr(channel, \"name\", None),\n            list=getattr(list, \"name\", None),\n            stream=getattr(stream, \"name\", None),\n            reply_to=reply_to or self.reply_to,\n            correlation_id=correlation_id,\n            headers=headers_to_send,\n            rpc=rpc,\n            rpc_timeout=rpc_timeout,\n            raise_timeout=raise_timeout,\n        )\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/redis/asyncapi.py
def schema(self) -> Dict[str, Channel]:\n    if not self.include_in_schema:\n        return {}\n\n    payloads = self.get_payloads()\n\n    method = None\n    if self.list is not None:\n        method = \"rpush\"\n    elif self.channel is not None:\n        method = \"publish\"\n    elif self.stream is not None:\n        method = \"xadd\"\n    else:\n        raise AssertionError(\"unreachable\")\n\n    return {\n        self.name: Channel(\n            description=self.description,\n            publish=Operation(\n                message=Message(\n                    title=f\"{self.name}:Message\",\n                    payload=resolve_payloads(payloads, \"Publisher\"),\n                    correlationId=CorrelationId(\n                        location=\"$message.header#/correlation_id\"\n                    ),\n                ),\n            ),\n            bindings=ChannelBinding(\n                redis=redis.ChannelBinding(\n                    channel=self.channel_name,\n                    method=method,\n                )\n            ),\n        )\n    }\n
","boost":0.5},{"location":"api/faststream/redis/asyncapi/Publisher/#faststream.redis.asyncapi.Publisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/","title":"RedisBroker","text":"","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker","title":"faststream.redis.broker.RedisBroker","text":"
RedisBroker(\n    url: str = \"redis://localhost:6379\",\n    polling_interval: Optional[float] = None,\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"custom\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any\n)\n

Bases: RedisLoggingMixin, BrokerAsyncUsecase[AnyRedisDict, 'Redis[bytes]']

Source code in faststream/redis/broker.py
def __init__(\n    self,\n    url: str = \"redis://localhost:6379\",\n    polling_interval: Optional[float] = None,\n    *,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"custom\",\n    security: Optional[BaseSecurity] = None,\n    **kwargs: Any,\n) -> None:\n    self.global_polling_interval = polling_interval\n    self._producer = None\n\n    super().__init__(\n        url=url,\n        protocol_version=protocol_version,\n        security=security,\n        **kwargs,\n    )\n\n    url_kwargs = urlparse(self.url)\n    self.protocol = protocol or url_kwargs.scheme\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.dependencies","title":"dependencies instance-attribute","text":"
dependencies: Sequence[Depends] = dependencies\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.description","title":"description instance-attribute","text":"
description = description\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.global_polling_interval","title":"global_polling_interval instance-attribute","text":"
global_polling_interval = polling_interval\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.handlers","title":"handlers instance-attribute","text":"
handlers: Dict[int, Handler]\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.log_level","title":"log_level instance-attribute","text":"
log_level: int\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.logger","title":"logger instance-attribute","text":"
logger: Optional[logging.Logger]\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.middlewares","title":"middlewares instance-attribute","text":"
middlewares: Sequence[Callable[[MsgType], BaseMiddleware]]\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.protocol","title":"protocol instance-attribute","text":"
protocol = protocol or url_kwargs.scheme\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.protocol_version","title":"protocol_version instance-attribute","text":"
protocol_version = protocol_version\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.security","title":"security instance-attribute","text":"
security = security\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.started","title":"started instance-attribute","text":"
started: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.tags","title":"tags instance-attribute","text":"
tags = tags\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.url","title":"url instance-attribute","text":"
url: str\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.close","title":"close async","text":"
close(\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None\n

Closes the object.

PARAMETER DESCRIPTION exc_type

The type of the exception being handled, if any.

TYPE: Optional[Type[BaseException]] DEFAULT: None

exc_val

The exception instance being handled, if any.

TYPE: Optional[BaseException] DEFAULT: None

exec_tb

The traceback of the exception being handled, if any.

TYPE: Optional[TracebackType] DEFAULT: None

RETURNS DESCRIPTION None

None

RAISES DESCRIPTION NotImplementedError

If the method is not implemented.

Source code in faststream/broker/core/asyncronous.py
async def close(\n    self,\n    exc_type: Optional[Type[BaseException]] = None,\n    exc_val: Optional[BaseException] = None,\n    exec_tb: Optional[TracebackType] = None,\n) -> None:\n    \"\"\"Closes the object.\n\n    Args:\n        exc_type: The type of the exception being handled, if any.\n        exc_val: The exception instance being handled, if any.\n        exec_tb: The traceback of the exception being handled, if any.\n\n    Returns:\n        None\n\n    Raises:\n        NotImplementedError: If the method is not implemented.\n\n    \"\"\"\n    super()._abc_close(exc_type, exc_val, exec_tb)\n\n    for h in self.handlers.values():\n        await h.close()\n\n    if self._connection is not None:\n        await self._close(exc_type, exc_val, exec_tb)\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.connect","title":"connect async","text":"
connect(*args: Any, **kwargs: Any) -> Redis[bytes]\n
Source code in faststream/redis/broker.py
async def connect(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> \"Redis[bytes]\":\n    connection = await super().connect(*args, **kwargs)\n    for p in self._publishers.values():\n        p._producer = self._producer\n    return connection\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.include_router","title":"include_router","text":"
include_router(router: BrokerRouter[Any, MsgType]) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[Any, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_router(self, router: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in router._handlers:\n        self.subscriber(*r.args, **r.kwargs)(r.call)\n\n    self._publishers = {**self._publishers, **router._publishers}\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[Any, MsgType]\n) -> None\n

Includes routers in the current object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[Any, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/core/abc.py
def include_routers(self, *routers: BrokerRouter[Any, MsgType]) -> None:\n    \"\"\"Includes routers in the current object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.publish","title":"publish async","text":"
publish(\n    *args: Any, **kwargs: Any\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/broker.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.publish_batch","title":"publish_batch async","text":"
publish_batch(*args: Any, **kwargs: Any) -> None\n
Source code in faststream/redis/broker.py
async def publish_batch(\n    self,\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n    return await self._producer.publish_batch(*args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.publisher","title":"publisher","text":"
publisher(\n    channel: Union[Channel, PubSub, None] = None,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/redis/broker.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    channel: Union[Channel, PubSub, None] = None,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    channel = PubSub.validate(channel)\n    list = ListSub.validate(list)\n    stream = StreamSub.validate(stream)\n\n    any_of = channel or list or stream\n    if any_of is None:\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    key = Handler.get_routing_hash(any_of)\n    publisher = self._publishers.get(\n        key,\n        Publisher(\n            channel=channel,\n            list=list,\n            stream=stream,\n            headers=headers,\n            reply_to=reply_to,\n            # AsyncAPI\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=include_in_schema,\n        ),\n    )\n    super().publisher(key, publisher)\n    if self._producer is not None:\n        publisher._producer = self._producer\n    return publisher\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.start","title":"start async","text":"
start() -> None\n
Source code in faststream/redis/broker.py
async def start(self) -> None:\n    context.set_global(\n        \"default_log_context\",\n        self._get_log_context(None, \"\"),\n    )\n\n    await super().start()\n    assert self._connection, NOT_CONNECTED_YET  # nosec B101\n\n    for handler in self.handlers.values():\n        if (stream := handler.stream_sub) is not None and stream.group:\n            try:\n                await self._connection.xgroup_create(\n                    name=stream.name,\n                    groupname=stream.group,\n                    mkstream=True,\n                )\n            except ResponseError as e:\n                if \"already exists\" not in str(e):\n                    raise e\n\n        c = self._get_log_context(None, handler.channel_name)\n        self._log(f\"`{handler.call_name}` waiting for messages\", extra=c)\n        await handler.start(self._connection)\n
","boost":0.5},{"location":"api/faststream/redis/broker/RedisBroker/#faststream.redis.broker.RedisBroker.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Any, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/broker.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    # broker arguments\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[CustomParser[AnyRedisDict, RedisMessage]] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **original_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[Any, P_HandlerParams, T_HandlerReturn],\n]:\n    channel = PubSub.validate(channel)\n    list = ListSub.validate(list)\n    stream = StreamSub.validate(stream)\n\n    if (any_of := channel or list or stream) is None:\n        raise ValueError(\n            \"You should specify `channel`, `list`, `stream` subscriber type\"\n        )\n\n    if all((channel, list)):\n        raise ValueError(\"You can't use `PubSub` and `ListSub` both\")\n    elif all((channel, stream)):\n        raise ValueError(\"You can't use `PubSub` and `StreamSub` both\")\n    elif all((list, stream)):\n        raise ValueError(\"You can't use `ListSub` and `StreamSub` both\")\n\n    self._setup_log_context(channel=any_of.name)\n    super().subscriber()\n\n    key = Handler.get_routing_hash(any_of)\n    handler = self.handlers[key] = self.handlers.get(\n        key,\n        Handler(  # type: ignore[abstract]\n            log_context_builder=partial(\n                self._get_log_context,\n                channel=any_of.name,\n            ),\n            graceful_timeout=self.graceful_timeout,\n            # Redis\n            channel=channel,\n            list=list,\n            stream=stream,\n            # AsyncAPI\n            title=title,\n            description=description,\n            include_in_schema=include_in_schema,\n        ),\n    )\n\n    def consumer_wrapper(\n        func: Callable[P_HandlerParams, T_HandlerReturn],\n    ) -> HandlerCallWrapper[AnyRedisDict, P_HandlerParams, T_HandlerReturn,]:\n        handler_call, dependant = self._wrap_handler(\n            func,\n            extra_dependencies=dependencies,\n            **original_kwargs,\n        )\n\n        handler.add_call(\n            handler=handler_call,\n            filter=filter,\n            middlewares=middlewares,\n            parser=parser or self._global_parser,  # type: ignore[arg-type]\n            decoder=decoder or self._global_decoder,  # type: ignore[arg-type]\n            dependant=dependant,\n        )\n\n        return handler_call\n\n    return consumer_wrapper\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/redis/fastapi/Context/#faststream.broker.fastapi.context.Context","title":"faststream.broker.fastapi.context.Context","text":"
Context(name: str) -> Any\n
Source code in faststream/broker/fastapi/context.py
def Context(name: str) -> Any:\n    return params.Depends(\n        lambda: context.resolve(name),\n        use_cache=True,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/","title":"RedisRouter","text":"","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter","title":"faststream.redis.fastapi.RedisRouter","text":"
RedisRouter(\n    url: str = \"redis://localhost:6379\",\n    polling_interval: Optional[float] = None,\n    *,\n    host: str = \"localhost\",\n    port: Union[str, int] = 6379,\n    db: Union[str, int] = 0,\n    client_name: Optional[str] = None,\n    health_check_interval: float = 0,\n    max_connections: Optional[int] = None,\n    socket_timeout: Optional[float] = None,\n    socket_connect_timeout: Optional[float] = None,\n    socket_read_size: int = 65536,\n    socket_keepalive: bool = False,\n    socket_keepalive_options: Optional[\n        Mapping[int, Union[int, bytes]]\n    ] = None,\n    socket_type: int = 0,\n    retry_on_timeout: bool = False,\n    encoding: str = \"utf-8\",\n    encoding_errors: str = \"strict\",\n    decode_responses: bool = False,\n    parser_class: Type[BaseParser] = DefaultParser,\n    connection_class: Type[Connection] = Connection,\n    encoder_class: Type[Encoder] = Encoder,\n    security: Optional[BaseSecurity] = None,\n    graceful_timeout: Optional[float] = None,\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    asyncapi_url: Optional[str] = None,\n    protocol: Optional[str] = None,\n    protocol_version: Optional[str] = \"custom\",\n    description: Optional[str] = None,\n    asyncapi_tags: Optional[Sequence[asyncapi.Tag]] = None,\n    schema_url: Optional[str] = \"/asyncapi\",\n    setup_state: bool = True,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    callbacks: Optional[List[routing.BaseRoute]] = None,\n    routes: Optional[List[routing.BaseRoute]] = None,\n    redirect_slashes: bool = True,\n    default: Optional[ASGIApp] = None,\n    dependency_overrides_provider: Optional[Any] = None,\n    route_class: Type[APIRoute] = APIRoute,\n    on_startup: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    on_shutdown: Optional[\n        Sequence[Callable[[], Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    lifespan: Optional[Lifespan[Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n)\n

Bases: StreamRouter[AnyRedisDict]

Source code in faststream/redis/fastapi.py
@staticmethod\ndef _setup_log_context(  # type: ignore[override]\n    main_broker: RB,\n    including_broker: RB,\n) -> None:\n    for h in including_broker.handlers.values():\n        main_broker._setup_log_context(h.channel_name)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.asyncapi_tags","title":"asyncapi_tags instance-attribute","text":"
asyncapi_tags = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.broker","title":"broker instance-attribute","text":"
broker: BrokerAsyncUsecase[\n    MsgType, Any\n] = self.broker_class(\n    *connection_args,\n    apply_types=False,\n    tags=asyncapi_tags,\n    **connection_kwars\n)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.broker_class","title":"broker_class class-attribute instance-attribute","text":"
broker_class = RB\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.callbacks","title":"callbacks instance-attribute","text":"
callbacks = callbacks or []\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.contact","title":"contact instance-attribute","text":"
contact: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.default","title":"default instance-attribute","text":"
default = self.not_found if default is None else default\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.default_response_class","title":"default_response_class instance-attribute","text":"
default_response_class = default_response_class\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.dependencies","title":"dependencies instance-attribute","text":"
dependencies = list(dependencies or [])\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.dependency_overrides_provider","title":"dependency_overrides_provider instance-attribute","text":"
dependency_overrides_provider = (\n    dependency_overrides_provider\n)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.deprecated","title":"deprecated instance-attribute","text":"
deprecated = deprecated\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.description","title":"description instance-attribute","text":"
description: str = ''\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.docs_router","title":"docs_router instance-attribute","text":"
docs_router: Optional[APIRouter] = self.asyncapi_router(\n    schema_url\n)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.external_docs","title":"external_docs instance-attribute","text":"
external_docs = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.generate_unique_id_function","title":"generate_unique_id_function instance-attribute","text":"
generate_unique_id_function = generate_unique_id_function\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.identifier","title":"identifier instance-attribute","text":"
identifier = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.license","title":"license instance-attribute","text":"
license: Optional[AnyDict] = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.lifespan_context","title":"lifespan_context instance-attribute","text":"
lifespan_context: Lifespan = _DefaultLifespan(self)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.on_shutdown","title":"on_shutdown instance-attribute","text":"
on_shutdown = (\n    [] if on_shutdown is None else list(on_shutdown)\n)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.on_startup","title":"on_startup instance-attribute","text":"
on_startup = [] if on_startup is None else list(on_startup)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.redirect_slashes","title":"redirect_slashes instance-attribute","text":"
redirect_slashes = redirect_slashes\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.responses","title":"responses instance-attribute","text":"
responses = responses or {}\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.route_class","title":"route_class instance-attribute","text":"
route_class = route_class\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.routes","title":"routes instance-attribute","text":"
routes = [] if routes is None else list(routes)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.schema","title":"schema instance-attribute","text":"
schema: Optional[Schema] = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.setup_state","title":"setup_state instance-attribute","text":"
setup_state = setup_state\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.tags","title":"tags instance-attribute","text":"
tags: List[Union[str, Enum]] = tags or []\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.terms_of_service","title":"terms_of_service instance-attribute","text":"
terms_of_service = None\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.title","title":"title instance-attribute","text":"
title: str = ''\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.version","title":"version instance-attribute","text":"
version: str = ''\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_api_mq_route","title":"add_api_mq_route","text":"
add_api_mq_route(\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any\n) -> HandlerCallWrapper[\n    MsgType, P_HandlerParams, T_HandlerReturn\n]\n

Add an API message queue route.

PARAMETER DESCRIPTION path

The path of the route.

TYPE: Union[NameRequired, str]

*extra

Additional path segments.

TYPE: Union[NameRequired, str] DEFAULT: ()

endpoint

The endpoint function to be called for this route.

TYPE: Callable[P_HandlerParams, T_HandlerReturn]

dependencies

The dependencies required by the endpoint function.

TYPE: Sequence[Depends]

**broker_kwargs

Additional keyword arguments to be passed to the broker.

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]

The handler call wrapper for the route.

Source code in faststream/broker/fastapi/router.py
def add_api_mq_route(\n    self,\n    path: Union[NameRequired, str],\n    *extra: Union[NameRequired, str],\n    endpoint: Callable[P_HandlerParams, T_HandlerReturn],\n    dependencies: Sequence[params.Depends],\n    **broker_kwargs: Any,\n) -> HandlerCallWrapper[MsgType, P_HandlerParams, T_HandlerReturn]:\n    \"\"\"Add an API message queue route.\n\n    Args:\n        path: The path of the route.\n        *extra: Additional path segments.\n        endpoint: The endpoint function to be called for this route.\n        dependencies: The dependencies required by the endpoint function.\n        **broker_kwargs: Additional keyword arguments to be passed to the broker.\n\n    Returns:\n        The handler call wrapper for the route.\n\n    \"\"\"\n    route: StreamRoute[MsgType, P_HandlerParams, T_HandlerReturn] = StreamRoute(\n        path,\n        *extra,\n        endpoint=endpoint,\n        dependencies=dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        broker=self.broker,\n        **broker_kwargs,\n    )\n    self.routes.append(route)\n    return route.handler\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_api_route","title":"add_api_route","text":"
add_api_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[\n        Type[Response], DefaultPlaceholder\n    ] = Default(JSONResponse),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id)\n) -> None\n
Source code in fastapi/routing.py
def add_api_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[Union[Set[str], List[str]]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Union[Type[Response], DefaultPlaceholder] = Default(\n        JSONResponse\n    ),\n    name: Optional[str] = None,\n    route_class_override: Optional[Type[APIRoute]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Union[\n        Callable[[APIRoute], str], DefaultPlaceholder\n    ] = Default(generate_unique_id),\n) -> None:\n    route_class = route_class_override or self.route_class\n    responses = responses or {}\n    combined_responses = {**self.responses, **responses}\n    current_response_class = get_value_or_default(\n        response_class, self.default_response_class\n    )\n    current_tags = self.tags.copy()\n    if tags:\n        current_tags.extend(tags)\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n    current_callbacks = self.callbacks.copy()\n    if callbacks:\n        current_callbacks.extend(callbacks)\n    current_generate_unique_id = get_value_or_default(\n        generate_unique_id_function, self.generate_unique_id_function\n    )\n    route = route_class(\n        self.prefix + path,\n        endpoint=endpoint,\n        response_model=response_model,\n        status_code=status_code,\n        tags=current_tags,\n        dependencies=current_dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=combined_responses,\n        deprecated=deprecated or self.deprecated,\n        methods=methods,\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema and self.include_in_schema,\n        response_class=current_response_class,\n        name=name,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n        callbacks=current_callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=current_generate_unique_id,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_api_websocket_route","title":"add_api_websocket_route","text":"
add_api_websocket_route(\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None\n) -> None\n
Source code in fastapi/routing.py
def add_api_websocket_route(\n    self,\n    path: str,\n    endpoint: Callable[..., Any],\n    name: Optional[str] = None,\n    *,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n) -> None:\n    current_dependencies = self.dependencies.copy()\n    if dependencies:\n        current_dependencies.extend(dependencies)\n\n    route = APIWebSocketRoute(\n        self.prefix + path,\n        endpoint=endpoint,\n        name=name,\n        dependencies=current_dependencies,\n        dependency_overrides_provider=self.dependency_overrides_provider,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_event_handler","title":"add_event_handler","text":"
add_event_handler(\n    event_type: str, func: typing.Callable\n) -> None\n
Source code in starlette/routing.py
def add_event_handler(\n    self, event_type: str, func: typing.Callable\n) -> None:  # pragma: no cover\n    assert event_type in (\"startup\", \"shutdown\")\n\n    if event_type == \"startup\":\n        self.on_startup.append(func)\n    else:\n        self.on_shutdown.append(func)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_route","title":"add_route","text":"
add_route(\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None\n
Source code in starlette/routing.py
def add_route(\n    self,\n    path: str,\n    endpoint: typing.Callable,\n    methods: typing.Optional[typing.List[str]] = None,\n    name: typing.Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:  # pragma: nocover\n    route = Route(\n        path,\n        endpoint=endpoint,\n        methods=methods,\n        name=name,\n        include_in_schema=include_in_schema,\n    )\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.add_websocket_route","title":"add_websocket_route","text":"
add_websocket_route(\n    path: str,\n    endpoint: typing.Callable,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def add_websocket_route(\n    self, path: str, endpoint: typing.Callable, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = WebSocketRoute(path, endpoint=endpoint, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.after_startup","title":"after_startup","text":"
after_startup(\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ]\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]\n

Register a function to be executed after startup.

PARAMETER DESCRIPTION func

A function to be executed after startup. It can take an AppType argument and return a mapping of strings to any values, or it can take an AppType argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an AppType argument and return nothing, or it can take an AppType argument and return an awaitable that resolves to nothing.

TYPE: Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

RETURNS DESCRIPTION Union[Callable[[AppType], Mapping[str, Any]], Callable[[AppType], Awaitable[Mapping[str, Any]]], Callable[[AppType], None], Callable[[AppType], Awaitable[None]]]

The registered function.

Source code in faststream/broker/fastapi/router.py
def after_startup(\n    self,\n    func: Union[\n        Callable[[AppType], Mapping[str, Any]],\n        Callable[[AppType], Awaitable[Mapping[str, Any]]],\n        Callable[[AppType], None],\n        Callable[[AppType], Awaitable[None]],\n    ],\n) -> Union[\n    Callable[[AppType], Mapping[str, Any]],\n    Callable[[AppType], Awaitable[Mapping[str, Any]]],\n    Callable[[AppType], None],\n    Callable[[AppType], Awaitable[None]],\n]:\n    \"\"\"Register a function to be executed after startup.\n\n    Args:\n        func: A function to be executed after startup. It can take an `AppType` argument and return a mapping of strings to any values, or it can take an `AppType` argument and return an awaitable that resolves to a mapping of strings to any values, or it can take an `AppType` argument and return nothing, or it can take an `AppType` argument and return an awaitable that resolves to nothing.\n\n    Returns:\n        The registered function.\n\n    \"\"\"\n    self._after_startup_hooks.append(to_async(func))  # type: ignore\n    return func\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.api_route","title":"api_route","text":"
api_route(\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[\n        Dict[Union[int, str], Dict[str, Any]]\n    ] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def api_route(\n    self,\n    path: str,\n    *,\n    response_model: Any = Default(None),\n    status_code: Optional[int] = None,\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    summary: Optional[str] = None,\n    description: Optional[str] = None,\n    response_description: str = \"Successful Response\",\n    responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n    deprecated: Optional[bool] = None,\n    methods: Optional[List[str]] = None,\n    operation_id: Optional[str] = None,\n    response_model_include: Optional[IncEx] = None,\n    response_model_exclude: Optional[IncEx] = None,\n    response_model_by_alias: bool = True,\n    response_model_exclude_unset: bool = False,\n    response_model_exclude_defaults: bool = False,\n    response_model_exclude_none: bool = False,\n    include_in_schema: bool = True,\n    response_class: Type[Response] = Default(JSONResponse),\n    name: Optional[str] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    openapi_extra: Optional[Dict[str, Any]] = None,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_route(\n            path,\n            func,\n            response_model=response_model,\n            status_code=status_code,\n            tags=tags,\n            dependencies=dependencies,\n            summary=summary,\n            description=description,\n            response_description=response_description,\n            responses=responses,\n            deprecated=deprecated,\n            methods=methods,\n            operation_id=operation_id,\n            response_model_include=response_model_include,\n            response_model_exclude=response_model_exclude,\n            response_model_by_alias=response_model_by_alias,\n            response_model_exclude_unset=response_model_exclude_unset,\n            response_model_exclude_defaults=response_model_exclude_defaults,\n            response_model_exclude_none=response_model_exclude_none,\n            include_in_schema=include_in_schema,\n            response_class=response_class,\n            name=name,\n            callbacks=callbacks,\n            openapi_extra=openapi_extra,\n            generate_unique_id_function=generate_unique_id_function,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.asyncapi_router","title":"asyncapi_router","text":"
asyncapi_router(\n    schema_url: Optional[str],\n) -> Optional[APIRouter]\n

Creates an API router for serving AsyncAPI documentation.

PARAMETER DESCRIPTION schema_url

The URL where the AsyncAPI schema will be served.

TYPE: Optional[str]

RETURNS DESCRIPTION Optional[APIRouter]

An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.

RAISES DESCRIPTION AssertionError

If self.schema is not set.

Notes

This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.

Source code in faststream/broker/fastapi/router.py
def asyncapi_router(self, schema_url: Optional[str]) -> Optional[APIRouter]:\n    \"\"\"Creates an API router for serving AsyncAPI documentation.\n\n    Args:\n        schema_url: The URL where the AsyncAPI schema will be served.\n\n    Returns:\n        An instance of APIRouter if include_in_schema and schema_url are both True, otherwise returns None.\n\n    Raises:\n        AssertionError: If self.schema is not set.\n\n    Notes:\n        This function defines three nested functions: download_app_json_schema, download_app_yaml_schema, and serve_asyncapi_schema. These functions are used to handle different routes for serving the AsyncAPI schema and documentation.\n\n    \"\"\"\n    if not self.include_in_schema or not schema_url:\n        return None\n\n    def download_app_json_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=json.dumps(self.schema.to_jsonable(), indent=4),\n            headers={\"Content-Type\": \"application/octet-stream\"},\n        )\n\n    def download_app_yaml_schema() -> Response:\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return Response(\n            content=self.schema.to_yaml(),\n            headers={\n                \"Content-Type\": \"application/octet-stream\",\n            },\n        )\n\n    def serve_asyncapi_schema(\n        sidebar: bool = True,\n        info: bool = True,\n        servers: bool = True,\n        operations: bool = True,\n        messages: bool = True,\n        schemas: bool = True,\n        errors: bool = True,\n        expandMessageExamples: bool = True,\n    ) -> HTMLResponse:\n        \"\"\"Serve the AsyncAPI schema as an HTML response.\n\n        Args:\n            sidebar (bool, optional): Whether to include the sidebar in the HTML. Defaults to True.\n            info (bool, optional): Whether to include the info section in the HTML. Defaults to True.\n            servers (bool, optional): Whether to include the servers section in the HTML. Defaults to True.\n            operations (bool, optional): Whether to include the operations section in the HTML. Defaults to True.\n            messages (bool, optional): Whether to include the messages section in the HTML. Defaults to True.\n            schemas (bool, optional): Whether to include the schemas section in the HTML. Defaults to True.\n            errors (bool, optional): Whether to include the errors section in the HTML. Defaults to True.\n            expandMessageExamples (bool, optional): Whether to expand message examples in the HTML. Defaults to True.\n\n        Returns:\n            HTMLResponse: The HTML response containing the AsyncAPI schema.\n\n        Raises:\n            AssertionError: If the schema is not available.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        assert (  # nosec B101\n            self.schema\n        ), \"You need to run application lifespan at first\"\n\n        return HTMLResponse(\n            content=get_asyncapi_html(\n                self.schema,\n                sidebar=sidebar,\n                info=info,\n                servers=servers,\n                operations=operations,\n                messages=messages,\n                schemas=schemas,\n                errors=errors,\n                expand_message_examples=expandMessageExamples,\n                title=self.schema.info.title,\n            )\n        )\n\n    docs_router = APIRouter(\n        prefix=self.prefix,\n        tags=[\"asyncapi\"],\n        redirect_slashes=self.redirect_slashes,\n        default=self.default,\n        deprecated=self.deprecated,\n    )\n    docs_router.get(schema_url)(serve_asyncapi_schema)\n    docs_router.get(f\"{schema_url}.json\")(download_app_json_schema)\n    docs_router.get(f\"{schema_url}.yaml\")(download_app_yaml_schema)\n    return docs_router\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.delete","title":"delete","text":"
delete(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP DELETE operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.delete--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.delete(\"/items/{item_id}\")\ndef delete_item(item_id: str):\n    return {\"message\": \"Item deleted\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def delete(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP DELETE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.delete(\"/items/{item_id}\")\n    def delete_item(item_id: str):\n        return {\"message\": \"Item deleted\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"DELETE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.get","title":"get","text":"
get(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP GET operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.get--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.get(\"/items/\")\ndef read_items():\n    return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def get(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP GET operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.get(\"/items/\")\n    def read_items():\n        return [{\"name\": \"Empanada\"}, {\"name\": \"Arepa\"}]\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"GET\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.head","title":"head","text":"
head(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP HEAD operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.head--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.head(\"/items/\", status_code=204)\ndef get_items_headers(response: Response):\n    response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def head(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP HEAD operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.head(\"/items/\", status_code=204)\n    def get_items_headers(response: Response):\n        response.headers[\"X-Cat-Dog\"] = \"Alone in the world\"\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"HEAD\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.host","title":"host","text":"
host(\n    host: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def host(\n    self, host: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: no cover\n    route = Host(host, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.include_router","title":"include_router","text":"
include_router(\n    router: APIRouter,\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(\n        JSONResponse\n    ),\n    responses: Optional[\n        Dict[Union[int, str], AnyDict]\n    ] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[\n        [APIRoute], str\n    ] = Default(generate_unique_id)\n) -> None\n

Includes a router in the API.

PARAMETER DESCRIPTION router

The router to include.

TYPE: APIRouter

prefix

The prefix to prepend to all paths defined in the router. Defaults to \"\".

TYPE: str DEFAULT: ''

tags

The tags to assign to all paths defined in the router. Defaults to None.

TYPE: List[Union[str, Enum]] DEFAULT: None

dependencies

The dependencies to apply to all paths defined in the router. Defaults to None.

TYPE: Sequence[Depends] DEFAULT: None

default_response_class

The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).

TYPE: Type[Response] DEFAULT: Default(JSONResponse)

responses

The responses to define for all paths defined in the router. Defaults to None.

TYPE: Dict[Union[int, str], AnyDict] DEFAULT: None

callbacks

The callbacks to apply to all paths defined in the router. Defaults to None.

TYPE: List[BaseRoute] DEFAULT: None

deprecated

Whether the router is deprecated. Defaults to None.

TYPE: bool DEFAULT: None

include_in_schema

Whether to include the router in the API schema. Defaults to True.

TYPE: bool DEFAULT: True

generate_unique_id_function

The function to generate unique IDs for

TYPE: Callable[[APIRoute], str] DEFAULT: Default(generate_unique_id)

Source code in faststream/broker/fastapi/router.py
def include_router(\n    self,\n    router: \"APIRouter\",\n    *,\n    prefix: str = \"\",\n    tags: Optional[List[Union[str, Enum]]] = None,\n    dependencies: Optional[Sequence[params.Depends]] = None,\n    default_response_class: Type[Response] = Default(JSONResponse),\n    responses: Optional[Dict[Union[int, str], AnyDict]] = None,\n    callbacks: Optional[List[BaseRoute]] = None,\n    deprecated: Optional[bool] = None,\n    include_in_schema: bool = True,\n    generate_unique_id_function: Callable[[APIRoute], str] = Default(\n        generate_unique_id\n    ),\n) -> None:\n    \"\"\"Includes a router in the API.\n\n    Args:\n        router (APIRouter): The router to include.\n        prefix (str, optional): The prefix to prepend to all paths defined in the router. Defaults to \"\".\n        tags (List[Union[str, Enum]], optional): The tags to assign to all paths defined in the router. Defaults to None.\n        dependencies (Sequence[params.Depends], optional): The dependencies to apply to all paths defined in the router. Defaults to None.\n        default_response_class (Type[Response], optional): The default response class to use for all paths defined in the router. Defaults to Default(JSONResponse).\n        responses (Dict[Union[int, str], AnyDict], optional): The responses to define for all paths defined in the router. Defaults to None.\n        callbacks (List[BaseRoute], optional): The callbacks to apply to all paths defined in the router. Defaults to None.\n        deprecated (bool, optional): Whether the router is deprecated. Defaults to None.\n        include_in_schema (bool, optional): Whether to include the router in the API schema. Defaults to True.\n        generate_unique_id_function (Callable[[APIRoute], str], optional): The function to generate unique IDs for\n\n    \"\"\"\n    if isinstance(router, StreamRouter):  # pragma: no branch\n        self._setup_log_context(self.broker, router.broker)\n        self.broker.handlers = {**self.broker.handlers, **router.broker.handlers}\n        self.broker._publishers = {\n            **self.broker._publishers,\n            **router.broker._publishers,\n        }\n\n    super().include_router(\n        router=router,\n        prefix=prefix,\n        tags=tags,\n        dependencies=dependencies,\n        default_response_class=default_response_class,\n        responses=responses,\n        callbacks=callbacks,\n        deprecated=deprecated,\n        include_in_schema=include_in_schema,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.lifespan","title":"lifespan async","text":"
lifespan(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n

Handle ASGI lifespan messages, which allows us to manage application startup and shutdown events.

Source code in starlette/routing.py
async def lifespan(self, scope: Scope, receive: Receive, send: Send) -> None:\n    \"\"\"\n    Handle ASGI lifespan messages, which allows us to manage application\n    startup and shutdown events.\n    \"\"\"\n    started = False\n    app: typing.Any = scope.get(\"app\")\n    await receive()\n    try:\n        async with self.lifespan_context(app) as maybe_state:\n            if maybe_state is not None:\n                if \"state\" not in scope:\n                    raise RuntimeError(\n                        'The server does not support \"state\" in the lifespan scope.'\n                    )\n                scope[\"state\"].update(maybe_state)\n            await send({\"type\": \"lifespan.startup.complete\"})\n            started = True\n            await receive()\n    except BaseException:\n        exc_text = traceback.format_exc()\n        if started:\n            await send({\"type\": \"lifespan.shutdown.failed\", \"message\": exc_text})\n        else:\n            await send({\"type\": \"lifespan.startup.failed\", \"message\": exc_text})\n        raise\n    else:\n        await send({\"type\": \"lifespan.shutdown.complete\"})\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.mount","title":"mount","text":"
mount(\n    path: str,\n    app: ASGIApp,\n    name: typing.Optional[str] = None,\n) -> None\n
Source code in starlette/routing.py
def mount(\n    self, path: str, app: ASGIApp, name: typing.Optional[str] = None\n) -> None:  # pragma: nocover\n    route = Mount(path, app=app, name=name)\n    self.routes.append(route)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.not_found","title":"not_found async","text":"
not_found(\n    scope: Scope, receive: Receive, send: Send\n) -> None\n
Source code in starlette/routing.py
async def not_found(self, scope: Scope, receive: Receive, send: Send) -> None:\n    if scope[\"type\"] == \"websocket\":\n        websocket_close = WebSocketClose()\n        await websocket_close(scope, receive, send)\n        return\n\n    # If we're running inside a starlette application then raise an\n    # exception, so that the configurable exception handler can deal with\n    # returning the response. For plain ASGI apps, just return the response.\n    if \"app\" in scope:\n        raise HTTPException(status_code=404)\n    else:\n        response = PlainTextResponse(\"Not Found\", status_code=404)\n    await response(scope, receive, send)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.on_event","title":"on_event","text":"
on_event(\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\\n                The type of event. `startup` or `shutdown`.\\n                \"\n        ),\n    ]\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add an event handler for the router.

on_event is deprecated, use lifespan event handlers instead.

Read more about it in the FastAPI docs for Lifespan Events.

Source code in fastapi/routing.py
@deprecated(\n    \"\"\"\n    on_event is deprecated, use lifespan event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/).\n    \"\"\"\n)\ndef on_event(\n    self,\n    event_type: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The type of event. `startup` or `shutdown`.\n            \"\"\"\n        ),\n    ],\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add an event handler for the router.\n\n    `on_event` is deprecated, use `lifespan` event handlers instead.\n\n    Read more about it in the\n    [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_event_handler(event_type, func)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.options","title":"options","text":"
options(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP OPTIONS operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.options--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.options(\"/items/\")\ndef get_item_options():\n    return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def options(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP OPTIONS operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.options(\"/items/\")\n    def get_item_options():\n        return {\"additions\": [\"Aji\", \"Guacamole\"]}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"OPTIONS\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.patch","title":"patch","text":"
patch(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PATCH operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.patch--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.patch(\"/items/\")\ndef update_item(item: Item):\n    return {\"message\": \"Item updated in place\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def patch(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PATCH operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.patch(\"/items/\")\n    def update_item(item: Item):\n        return {\"message\": \"Item updated in place\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PATCH\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.post","title":"post","text":"
post(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP POST operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.post--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.post(\"/items/\")\ndef create_item(item: Item):\n    return {\"message\": \"Item created\"}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def post(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP POST operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.post(\"/items/\")\n    def create_item(item: Item):\n        return {\"message\": \"Item created\"}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"POST\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.publisher","title":"publisher","text":"
publisher(\n    channel: Union[Channel, PubSub, None] = None,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.put","title":"put","text":"
put(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP PUT operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.put--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef replace_item(item_id: str, item: Item):\n    return {\"message\": \"Item replaced\", \"id\": item_id}\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def put(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP PUT operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def replace_item(item_id: str, item: Item):\n        return {\"message\": \"Item replaced\", \"id\": item_id}\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"PUT\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.route","title":"route","text":"
route(\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def route(\n    self,\n    path: str,\n    methods: Optional[List[str]] = None,\n    name: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_route(\n            path,\n            func,\n            methods=methods,\n            name=name,\n            include_in_schema=include_in_schema,\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Run any .on_shutdown event handlers.

Source code in starlette/routing.py
async def shutdown(self) -> None:\n    \"\"\"\n    Run any `.on_shutdown` event handlers.\n    \"\"\"\n    for handler in self.on_shutdown:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.startup","title":"startup async","text":"
startup() -> None\n

Run any .on_startup event handlers.

Source code in starlette/routing.py
async def startup(self) -> None:\n    \"\"\"\n    Run any `.on_startup` event handlers.\n    \"\"\"\n    for handler in self.on_startup:\n        if is_async_callable(handler):\n            await handler()\n        else:\n            handler()\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    dependencies: Sequence[Depends] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Any, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/fastapi.py
def subscriber(\n    self,\n    channel: Union[str, PubSub, None] = None,\n    *,\n    dependencies: Optional[Sequence[Depends]] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[AnyRedisDict, P_HandlerParams, T_HandlerReturn],\n]:\n    return super().subscriber(\n        path=channel,\n        dependencies=dependencies,\n        **broker_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.trace","title":"trace","text":"
trace(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                The URL path to be used for this *path operation*.\\n\\n                For example, in `http://example.com/items`, the path is `/items`.\\n                \"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\\n                The type to use for the response.\\n\\n                It could be any valid Pydantic *field* type. So, it doesn't have to\\n                be a Pydantic model, it could be other things, like a `list`, `dict`,\\n                etc.\\n\\n                It will be used for:\\n\\n                * Documentation: the generated OpenAPI (and the UI at `/docs`) will\\n                    show it as the response (JSON Schema).\\n                * Serialization: you could return an arbitrary object and the\\n                    `response_model` would be used to serialize that object into the\\n                    corresponding JSON.\\n                * Filtering: the JSON sent to the client will only contain the data\\n                    (fields) defined in the `response_model`. If you returned an object\\n                    that contains an attribute `password` but the `response_model` does\\n                    not include that field, the JSON sent to the client would not have\\n                    that `password`.\\n                * Validation: whatever you return will be serialized with the\\n                    `response_model`, converting any data as necessary to generate the\\n                    corresponding JSON. But if the data in the object returned is not\\n                    valid, that would mean a violation of the contract with the client,\\n                    so it's an error from the API developer. So, FastAPI will raise an\\n                    error and return a 500 error code (Internal Server Error).\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\\n                \"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\\n                The default status code to be used for the response.\\n\\n                You could override the status code by returning a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\\n                \"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\\n                A list of tags to be applied to the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\\n                \"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be applied to the\\n                *path operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\\n                \"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A summary for the *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A description for the *path operation*.\\n\\n                If not provided, it will be extracted automatically from the docstring\\n                of the *path operation function*.\\n\\n                It can contain Markdown.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\\n                \"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\\n                The description for the default response.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\\n                Additional responses that could be returned by this *path operation*.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\\n                Mark this *path operation* as deprecated.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n                \"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Custom operation ID to be used by this *path operation*.\\n\\n                By default, it is generated automatically.\\n\\n                If you provide a custom operation ID, you need to make sure it is\\n                unique for the whole API.\\n\\n                You can customize the\\n                operation ID generation with the parameter\\n                `generate_unique_id_function` in the `FastAPI` class.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to include only certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\\n                Configuration passed to Pydantic to exclude certain fields in the\\n                response data.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response model\\n                should be serialized by alias when an alias is used.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\\n                \"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that were not set and\\n                have their default values. This is different from\\n                `response_model_exclude_defaults` in that if the fields are set,\\n                they will be included in the response, even if the value is the same\\n                as the default.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data\\n                should have all the fields, including the ones that have the same value\\n                as the default. This is different from `response_model_exclude_unset`\\n                in that if the fields are set but contain the same default values,\\n                they will be excluded from the response.\\n\\n                When `True`, default values are omitted from the response.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\\n                \"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\\n                Configuration passed to Pydantic to define if the response data should\\n                exclude fields set to `None`.\\n\\n                This is much simpler (less smart) than `response_model_exclude_unset`\\n                and `response_model_exclude_defaults`. You probably want to use one of\\n                those two instead of this one, as those allow returning `None` values\\n                when it makes sense.\\n\\n                Read more about it in the\\n                [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\\n                \"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\\n                Include this *path operation* in the generated OpenAPI schema.\\n\\n                This affects the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\\n                \"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\\n                Response class to be used for this *path operation*.\\n\\n                This will not be used if you return a response directly.\\n\\n                Read more about it in the\\n                [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\\n                \"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                Name for this *path operation*. Only used internally.\\n                \"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\\n                List of *path operations* that will be used as OpenAPI callbacks.\\n\\n                This is only for OpenAPI documentation, the callbacks won't be used\\n                directly.\\n\\n                It will be added to the generated OpenAPI (e.g. visible at `/docs`).\\n\\n                Read more about it in the\\n                [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\\n                \"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\\n                Extra metadata to be included in the OpenAPI schema for this *path\\n                operation*.\\n\\n                Read more about it in the\\n                [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\\n                \"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\\n                Customize the function used to generate unique IDs for the *path\\n                operations* shown in the generated OpenAPI.\\n\\n                This is particularly useful when automatically generating clients or\\n                SDKs for your API.\\n\\n                Read more about it in the\\n                [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\\n                \"\n        ),\n    ] = Default(generate_unique_id)\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Add a path operation using an HTTP TRACE operation.

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.trace--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n    name: str\n    description: str | None = None\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.put(\"/items/{item_id}\")\ndef trace_item(item_id: str):\n    return None\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def trace(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The URL path to be used for this *path operation*.\n\n            For example, in `http://example.com/items`, the path is `/items`.\n            \"\"\"\n        ),\n    ],\n    *,\n    response_model: Annotated[\n        Any,\n        Doc(\n            \"\"\"\n            The type to use for the response.\n\n            It could be any valid Pydantic *field* type. So, it doesn't have to\n            be a Pydantic model, it could be other things, like a `list`, `dict`,\n            etc.\n\n            It will be used for:\n\n            * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n                show it as the response (JSON Schema).\n            * Serialization: you could return an arbitrary object and the\n                `response_model` would be used to serialize that object into the\n                corresponding JSON.\n            * Filtering: the JSON sent to the client will only contain the data\n                (fields) defined in the `response_model`. If you returned an object\n                that contains an attribute `password` but the `response_model` does\n                not include that field, the JSON sent to the client would not have\n                that `password`.\n            * Validation: whatever you return will be serialized with the\n                `response_model`, converting any data as necessary to generate the\n                corresponding JSON. But if the data in the object returned is not\n                valid, that would mean a violation of the contract with the client,\n                so it's an error from the API developer. So, FastAPI will raise an\n                error and return a 500 error code (Internal Server Error).\n\n            Read more about it in the\n            [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n            \"\"\"\n        ),\n    ] = Default(None),\n    status_code: Annotated[\n        Optional[int],\n        Doc(\n            \"\"\"\n            The default status code to be used for the response.\n\n            You could override the status code by returning a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n            \"\"\"\n        ),\n    ] = None,\n    tags: Annotated[\n        Optional[List[Union[str, Enum]]],\n        Doc(\n            \"\"\"\n            A list of tags to be applied to the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n            \"\"\"\n        ),\n    ] = None,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be applied to the\n            *path operation*.\n\n            Read more about it in the\n            [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n            \"\"\"\n        ),\n    ] = None,\n    summary: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A summary for the *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    description: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A description for the *path operation*.\n\n            If not provided, it will be extracted automatically from the docstring\n            of the *path operation function*.\n\n            It can contain Markdown.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n            \"\"\"\n        ),\n    ] = None,\n    response_description: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            The description for the default response.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = \"Successful Response\",\n    responses: Annotated[\n        Optional[Dict[Union[int, str], Dict[str, Any]]],\n        Doc(\n            \"\"\"\n            Additional responses that could be returned by this *path operation*.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    deprecated: Annotated[\n        Optional[bool],\n        Doc(\n            \"\"\"\n            Mark this *path operation* as deprecated.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n            \"\"\"\n        ),\n    ] = None,\n    operation_id: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Custom operation ID to be used by this *path operation*.\n\n            By default, it is generated automatically.\n\n            If you provide a custom operation ID, you need to make sure it is\n            unique for the whole API.\n\n            You can customize the\n            operation ID generation with the parameter\n            `generate_unique_id_function` in the `FastAPI` class.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_include: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to include only certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_exclude: Annotated[\n        Optional[IncEx],\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to exclude certain fields in the\n            response data.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = None,\n    response_model_by_alias: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response model\n            should be serialized by alias when an alias is used.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n            \"\"\"\n        ),\n    ] = True,\n    response_model_exclude_unset: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that were not set and\n            have their default values. This is different from\n            `response_model_exclude_defaults` in that if the fields are set,\n            they will be included in the response, even if the value is the same\n            as the default.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_defaults: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data\n            should have all the fields, including the ones that have the same value\n            as the default. This is different from `response_model_exclude_unset`\n            in that if the fields are set but contain the same default values,\n            they will be excluded from the response.\n\n            When `True`, default values are omitted from the response.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n            \"\"\"\n        ),\n    ] = False,\n    response_model_exclude_none: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Configuration passed to Pydantic to define if the response data should\n            exclude fields set to `None`.\n\n            This is much simpler (less smart) than `response_model_exclude_unset`\n            and `response_model_exclude_defaults`. You probably want to use one of\n            those two instead of this one, as those allow returning `None` values\n            when it makes sense.\n\n            Read more about it in the\n            [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n            \"\"\"\n        ),\n    ] = False,\n    include_in_schema: Annotated[\n        bool,\n        Doc(\n            \"\"\"\n            Include this *path operation* in the generated OpenAPI schema.\n\n            This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-from-openapi).\n            \"\"\"\n        ),\n    ] = True,\n    response_class: Annotated[\n        Type[Response],\n        Doc(\n            \"\"\"\n            Response class to be used for this *path operation*.\n\n            This will not be used if you return a response directly.\n\n            Read more about it in the\n            [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n            \"\"\"\n        ),\n    ] = Default(JSONResponse),\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            Name for this *path operation*. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    callbacks: Annotated[\n        Optional[List[BaseRoute]],\n        Doc(\n            \"\"\"\n            List of *path operations* that will be used as OpenAPI callbacks.\n\n            This is only for OpenAPI documentation, the callbacks won't be used\n            directly.\n\n            It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n            Read more about it in the\n            [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n            \"\"\"\n        ),\n    ] = None,\n    openapi_extra: Annotated[\n        Optional[Dict[str, Any]],\n        Doc(\n            \"\"\"\n            Extra metadata to be included in the OpenAPI schema for this *path\n            operation*.\n\n            Read more about it in the\n            [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n            \"\"\"\n        ),\n    ] = None,\n    generate_unique_id_function: Annotated[\n        Callable[[APIRoute], str],\n        Doc(\n            \"\"\"\n            Customize the function used to generate unique IDs for the *path\n            operations* shown in the generated OpenAPI.\n\n            This is particularly useful when automatically generating clients or\n            SDKs for your API.\n\n            Read more about it in the\n            [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n            \"\"\"\n        ),\n    ] = Default(generate_unique_id),\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Add a *path operation* using an HTTP TRACE operation.\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI\n    from pydantic import BaseModel\n\n    class Item(BaseModel):\n        name: str\n        description: str | None = None\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.put(\"/items/{item_id}\")\n    def trace_item(item_id: str):\n        return None\n\n    app.include_router(router)\n    ```\n    \"\"\"\n    return self.api_route(\n        path=path,\n        response_model=response_model,\n        status_code=status_code,\n        tags=tags,\n        dependencies=dependencies,\n        summary=summary,\n        description=description,\n        response_description=response_description,\n        responses=responses,\n        deprecated=deprecated,\n        methods=[\"TRACE\"],\n        operation_id=operation_id,\n        response_model_include=response_model_include,\n        response_model_exclude=response_model_exclude,\n        response_model_by_alias=response_model_by_alias,\n        response_model_exclude_unset=response_model_exclude_unset,\n        response_model_exclude_defaults=response_model_exclude_defaults,\n        response_model_exclude_none=response_model_exclude_none,\n        include_in_schema=include_in_schema,\n        response_class=response_class,\n        name=name,\n        callbacks=callbacks,\n        openapi_extra=openapi_extra,\n        generate_unique_id_function=generate_unique_id_function,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.url_path_for","title":"url_path_for","text":"
url_path_for(\n    __name: str, **path_params: typing.Any\n) -> URLPath\n
Source code in starlette/routing.py
def url_path_for(self, __name: str, **path_params: typing.Any) -> URLPath:\n    for route in self.routes:\n        try:\n            return route.url_path_for(__name, **path_params)\n        except NoMatchFound:\n            pass\n    raise NoMatchFound(__name, path_params)\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.websocket","title":"websocket","text":"
websocket(\n    path: Annotated[\n        str,\n        Doc(\n            \"\\n                WebSocket path.\\n                \"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\\n                A name for the WebSocket. Only used internally.\\n                \"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\\n                A list of dependencies (using `Depends()`) to be used for this\\n                WebSocket.\\n\\n                Read more about it in the\\n                [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\\n                \"\n        ),\n    ] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n

Decorate a WebSocket function.

Read more about it in the FastAPI docs for WebSockets.

Example

","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.websocket--example","title":"Example","text":"
from fastapi import APIRouter, FastAPI, WebSocket\n\napp = FastAPI()\nrouter = APIRouter()\n\n@router.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(f\"Message text was: {data}\")\n\napp.include_router(router)\n
Source code in fastapi/routing.py
def websocket(\n    self,\n    path: Annotated[\n        str,\n        Doc(\n            \"\"\"\n            WebSocket path.\n            \"\"\"\n        ),\n    ],\n    name: Annotated[\n        Optional[str],\n        Doc(\n            \"\"\"\n            A name for the WebSocket. Only used internally.\n            \"\"\"\n        ),\n    ] = None,\n    *,\n    dependencies: Annotated[\n        Optional[Sequence[params.Depends]],\n        Doc(\n            \"\"\"\n            A list of dependencies (using `Depends()`) to be used for this\n            WebSocket.\n\n            Read more about it in the\n            [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n            \"\"\"\n        ),\n    ] = None,\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    \"\"\"\n    Decorate a WebSocket function.\n\n    Read more about it in the\n    [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n\n    **Example**\n\n    ## Example\n\n    ```python\n    from fastapi import APIRouter, FastAPI, WebSocket\n\n    app = FastAPI()\n    router = APIRouter()\n\n    @router.websocket(\"/ws\")\n    async def websocket_endpoint(websocket: WebSocket):\n        await websocket.accept()\n        while True:\n            data = await websocket.receive_text()\n            await websocket.send_text(f\"Message text was: {data}\")\n\n    app.include_router(router)\n    ```\n    \"\"\"\n\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_api_websocket_route(\n            path, func, name=name, dependencies=dependencies\n        )\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.websocket_route","title":"websocket_route","text":"
websocket_route(\n    path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]\n
Source code in fastapi/routing.py
def websocket_route(\n    self, path: str, name: Union[str, None] = None\n) -> Callable[[DecoratedCallable], DecoratedCallable]:\n    def decorator(func: DecoratedCallable) -> DecoratedCallable:\n        self.add_websocket_route(path, func, name=name)\n        return func\n\n    return decorator\n
","boost":0.5},{"location":"api/faststream/redis/fastapi/RedisRouter/#faststream.redis.fastapi.RedisRouter.wrap_lifespan","title":"wrap_lifespan","text":"
wrap_lifespan(\n    lifespan: Optional[Lifespan[Any]] = None,\n) -> Lifespan[Any]\n

Wrap the lifespan of the application.

PARAMETER DESCRIPTION lifespan

Optional lifespan object.

TYPE: Optional[Lifespan[Any]] DEFAULT: None

RETURNS DESCRIPTION Lifespan[Any]

The wrapped lifespan object.

RAISES DESCRIPTION NotImplementedError

If silent animals are not supported.

Source code in faststream/broker/fastapi/router.py
def wrap_lifespan(self, lifespan: Optional[Lifespan[Any]] = None) -> Lifespan[Any]:\n    \"\"\"Wrap the lifespan of the application.\n\n    Args:\n        lifespan: Optional lifespan object.\n\n    Returns:\n        The wrapped lifespan object.\n\n    Raises:\n        NotImplementedError: If silent animals are not supported.\n\n    \"\"\"\n    if lifespan is not None:\n        lifespan_context = lifespan\n    else:\n        lifespan_context = _DefaultLifespan(self)\n\n    @asynccontextmanager\n    async def start_broker_lifespan(\n        app: FastAPI,\n    ) -> AsyncIterator[Mapping[str, Any]]:\n        \"\"\"Starts the lifespan of a broker.\n\n        Args:\n            app (FastAPI): The FastAPI application.\n\n        Yields:\n            AsyncIterator[Mapping[str, Any]]: A mapping of context information during the lifespan of the broker.\n\n        Raises:\n            NotImplementedError: If silent animals are not supported.\n        !!! note\n\n            The above docstring is autogenerated by docstring-gen library (https://docstring-gen.airt.ai)\n        \"\"\"\n        from faststream.asyncapi.generate import get_app_schema\n\n        self.title = app.title\n        self.description = app.description\n        self.version = app.version\n        self.contact = app.contact\n        self.license = app.license_info\n\n        self.schema = get_app_schema(self)\n        if self.docs_router:\n            app.include_router(self.docs_router)\n\n        async with lifespan_context(app) as maybe_context:\n            if maybe_context is None:\n                context: AnyDict = {}\n            else:\n                context = dict(maybe_context)\n\n            context.update({\"broker\": self.broker})\n            await self.broker.start()\n\n            for h in self._after_startup_hooks:\n                h_context = await h(app)\n                if h_context:  # pragma: no branch\n                    context.update(h_context)\n\n            try:\n                if self.setup_state:\n                    yield context\n                else:\n                    # NOTE: old asgi compatibility\n                    yield  # type: ignore\n\n            finally:\n                await self.broker.close()\n\n    return start_broker_lifespan\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/","title":"LogicRedisHandler","text":"","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler","title":"faststream.redis.handler.LogicRedisHandler","text":"
LogicRedisHandler(\n    *,\n    log_context_builder: Callable[\n        [StreamMessage[Any]], Dict[str, str]\n    ],\n    graceful_timeout: Optional[float] = None,\n    channel: Optional[PubSub] = None,\n    list: Optional[ListSub] = None,\n    stream: Optional[StreamSub] = None,\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True\n)\n

Bases: AsyncHandler[AnyRedisDict]

Source code in faststream/redis/handler.py
def __init__(\n    self,\n    *,\n    log_context_builder: Callable[[StreamMessage[Any]], Dict[str, str]],\n    graceful_timeout: Optional[float] = None,\n    # Redis info\n    channel: Optional[PubSub] = None,\n    list: Optional[ListSub] = None,\n    stream: Optional[StreamSub] = None,\n    # AsyncAPI information\n    description: Optional[str] = None,\n    title: Optional[str] = None,\n    include_in_schema: bool = True,\n) -> None:\n    self.channel = channel\n    self.list_sub = list\n    self.stream_sub = stream\n\n    self.subscription = None\n    self.task = None\n\n    self.last_id = stream.last_id if stream else \"$\"\n\n    super().__init__(\n        log_context_builder=log_context_builder,\n        description=description,\n        title=title,\n        include_in_schema=include_in_schema,\n        graceful_timeout=graceful_timeout,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.call_name","title":"call_name property","text":"
call_name: str\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.calls","title":"calls instance-attribute","text":"
calls: List[\n    Tuple[\n        HandlerCallWrapper[MsgType, Any, SendableMessage],\n        Callable[[StreamMessage[MsgType]], Awaitable[bool]],\n        AsyncParser[MsgType, Any],\n        AsyncDecoder[StreamMessage[MsgType]],\n        Sequence[Callable[[Any], BaseMiddleware]],\n        CallModel[Any, SendableMessage],\n    ]\n]\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.channel","title":"channel instance-attribute","text":"
channel = channel\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.channel_name","title":"channel_name property","text":"
channel_name: str\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.global_middlewares","title":"global_middlewares instance-attribute","text":"
global_middlewares: Sequence[\n    Callable[[Any], BaseMiddleware]\n] = []\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.graceful_timeout","title":"graceful_timeout instance-attribute","text":"
graceful_timeout = graceful_timeout\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.last_id","title":"last_id instance-attribute","text":"
last_id = stream.last_id if stream else '$'\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.list_sub","title":"list_sub instance-attribute","text":"
list_sub = list\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.lock","title":"lock instance-attribute","text":"
lock = MultiLock()\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.log_context_builder","title":"log_context_builder instance-attribute","text":"
log_context_builder = log_context_builder\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.running","title":"running instance-attribute","text":"
running = False\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.stream_sub","title":"stream_sub instance-attribute","text":"
stream_sub = stream\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.subscription","title":"subscription instance-attribute","text":"
subscription: Optional[RPubSub] = None\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.task","title":"task instance-attribute","text":"
task: Optional[asyncio.Task[Any]] = None\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.add_call","title":"add_call","text":"
add_call(\n    *,\n    handler: HandlerCallWrapper[\n        AnyDict, P_HandlerParams, T_HandlerReturn\n    ],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[AnyDict, RedisMessage]],\n    decoder: Optional[CustomDecoder[RedisMessage]],\n    filter: Filter[RedisMessage],\n    middlewares: Optional[\n        Sequence[Callable[[AnyDict], BaseMiddleware]]\n    ]\n) -> None\n
Source code in faststream/redis/handler.py
def add_call(\n    self,\n    *,\n    handler: HandlerCallWrapper[AnyDict, P_HandlerParams, T_HandlerReturn],\n    dependant: CallModel[P_HandlerParams, T_HandlerReturn],\n    parser: Optional[CustomParser[AnyDict, RedisMessage]],\n    decoder: Optional[CustomDecoder[RedisMessage]],\n    filter: Filter[RedisMessage],\n    middlewares: Optional[Sequence[Callable[[AnyDict], BaseMiddleware]]],\n) -> None:\n    super().add_call(\n        handler=handler,\n        parser=resolve_custom_func(parser, RedisParser.parse_message),\n        decoder=resolve_custom_func(decoder, RedisParser.decode_message),\n        filter=filter,  # type: ignore[arg-type]\n        dependant=dependant,\n        middlewares=middlewares,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.close","title":"close async","text":"
close() -> None\n
Source code in faststream/redis/handler.py
async def close(self) -> None:\n    await super().close()\n\n    if self.task is not None:\n        if not self.task.done():\n            self.task.cancel()\n        self.task = None\n\n    if self.subscription is not None:\n        await self.subscription.unsubscribe()\n        await self.subscription.aclose()  # type: ignore[attr-defined]\n        self.subscription = None\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.consume","title":"consume async","text":"
consume(msg: MsgType) -> SendableMessage\n

Consume a message asynchronously.

PARAMETER DESCRIPTION msg

The message to be consumed.

TYPE: MsgType

RETURNS DESCRIPTION SendableMessage

The sendable message.

RAISES DESCRIPTION StopConsume

If the consumption needs to be stopped.

RAISES DESCRIPTION Exception

If an error occurs during consumption.

Source code in faststream/broker/handler.py
@override\nasync def consume(self, msg: MsgType) -> SendableMessage:  # type: ignore[override]\n    \"\"\"Consume a message asynchronously.\n\n    Args:\n        msg: The message to be consumed.\n\n    Returns:\n        The sendable message.\n\n    Raises:\n        StopConsume: If the consumption needs to be stopped.\n\n    Raises:\n        Exception: If an error occurs during consumption.\n\n    \"\"\"\n    result: Optional[WrappedReturn[SendableMessage]] = None\n    result_msg: SendableMessage = None\n\n    if not self.running:\n        return result_msg\n\n    async with AsyncExitStack() as stack:\n        stack.enter_context(self.lock)\n\n        gl_middlewares: List[BaseMiddleware] = []\n\n        stack.enter_context(context.scope(\"handler_\", self))\n\n        for m in self.global_middlewares:\n            gl_middlewares.append(await stack.enter_async_context(m(msg)))\n\n        logged = False\n        processed = False\n        for handler, filter_, parser, decoder, middlewares, _ in self.calls:\n            local_middlewares: List[BaseMiddleware] = []\n            for local_m in middlewares:\n                local_middlewares.append(\n                    await stack.enter_async_context(local_m(msg))\n                )\n\n            all_middlewares = gl_middlewares + local_middlewares\n\n            # TODO: add parser & decoder caches\n            message = await parser(msg)\n\n            if not logged:  # pragma: no branch\n                log_context_tag = context.set_local(\n                    \"log_context\", self.log_context_builder(message)\n                )\n\n            message.decoded_body = await decoder(message)\n            message.processed = processed\n\n            if await filter_(message):\n                assert (  # nosec B101\n                    not processed\n                ), \"You can't proccess a message with multiple consumers\"\n\n                try:\n                    async with AsyncExitStack() as consume_stack:\n                        for m_consume in all_middlewares:\n                            message.decoded_body = (\n                                await consume_stack.enter_async_context(\n                                    m_consume.consume_scope(message.decoded_body)\n                                )\n                            )\n\n                        result = await cast(\n                            Awaitable[Optional[WrappedReturn[SendableMessage]]],\n                            handler.call_wrapped(message),\n                        )\n\n                    if result is not None:\n                        result_msg, pub_response = result\n\n                        # TODO: suppress all publishing errors and raise them after all publishers will be tried\n                        for publisher in (pub_response, *handler._publishers):\n                            if publisher is not None:\n                                async with AsyncExitStack() as pub_stack:\n                                    result_to_send = result_msg\n\n                                    for m_pub in all_middlewares:\n                                        result_to_send = (\n                                            await pub_stack.enter_async_context(\n                                                m_pub.publish_scope(result_to_send)\n                                            )\n                                        )\n\n                                    await publisher.publish(\n                                        message=result_to_send,\n                                        correlation_id=message.correlation_id,\n                                    )\n\n                except StopConsume:\n                    await self.close()\n                    handler.trigger()\n\n                except HandlerException as e:  # pragma: no cover\n                    handler.trigger()\n                    raise e\n\n                except Exception as e:\n                    handler.trigger(error=e)\n                    raise e\n\n                else:\n                    handler.trigger(result=result[0] if result else None)\n                    message.processed = processed = True\n                    if IS_OPTIMIZED:  # pragma: no cover\n                        break\n\n        assert (\n            not self.running or processed\n        ), \"You have to consume message\"  # nosec B101\n\n    context.reset_local(\"log_context\", log_context_tag)\n\n    return result_msg\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/handler.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    for h, _, _, _, _, dep in self.calls:\n        body = parse_handler_params(\n            dep, prefix=f\"{self._title or self.call_name}:Message\"\n        )\n        payloads.append((body, to_camelcase(unwrap(h._original_call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.get_routing_hash","title":"get_routing_hash staticmethod","text":"
get_routing_hash(channel: Hashable) -> int\n
Source code in faststream/redis/handler.py
@staticmethod\ndef get_routing_hash(channel: Hashable) -> int:\n    return hash(channel)\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/redis/handler/LogicRedisHandler/#faststream.redis.handler.LogicRedisHandler.start","title":"start async","text":"
start(client: Redis[bytes]) -> None\n
Source code in faststream/redis/handler.py
@override\nasync def start(self, client: \"Redis[bytes]\") -> None:  # type: ignore[override]\n    self.started = anyio.Event()\n\n    consume: Union[\n        Callable[[], Awaitable[Optional[AnyRedisDict]]],\n        Callable[[], Awaitable[Optional[Sequence[AnyRedisDict]]]],\n    ]\n    sleep: float\n\n    if (list_sub := self.list_sub) is not None:\n        sleep = list_sub.polling_interval\n        consume = partial(\n            self._consume_list_msg,\n            client=client,\n        )\n        self.started.set()\n\n    elif (channel := self.channel) is not None:\n        self.subscription = psub = client.pubsub()\n\n        if channel.pattern:\n            await psub.psubscribe(channel.name)\n        else:\n            await psub.subscribe(channel.name)\n\n        consume = partial(\n            psub.get_message,\n            ignore_subscribe_messages=True,\n            timeout=channel.polling_interval,\n        )\n        sleep = 0.01\n        self.started.set()\n\n    elif self.stream_sub is not None:\n        consume = partial(  # type: ignore[assignment]\n            self._consume_stream_msg,\n            client=client,\n        )\n        sleep = 0.01\n\n    else:\n        raise AssertionError(\"unreachable\")\n\n    await super().start()\n    self.task = asyncio.create_task(self._consume(consume, sleep))\n    # wait until Stream starts to consume\n    await anyio.sleep(0.01)\n    await self.started.wait()\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/","title":"AnyRedisDict","text":"","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict","title":"faststream.redis.message.AnyRedisDict","text":"

Bases: PubSubMessage

","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.channel","title":"channel instance-attribute","text":"
channel: bytes\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.data","title":"data instance-attribute","text":"
data: Union[bytes, List[bytes]]\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.message_id","title":"message_id instance-attribute","text":"
message_id: NotRequired[str]\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.message_ids","title":"message_ids instance-attribute","text":"
message_ids: NotRequired[List[str]]\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.pattern","title":"pattern instance-attribute","text":"
pattern: NotRequired[Optional[bytes]]\n
","boost":0.5},{"location":"api/faststream/redis/message/AnyRedisDict/#faststream.redis.message.AnyRedisDict.type","title":"type instance-attribute","text":"
type: Literal['stream', 'list', 'message', 'batch']\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/","title":"BatchMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage","title":"faststream.redis.message.BatchMessage","text":"

Bases: PubSubMessage

","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage.channel","title":"channel instance-attribute","text":"
channel: bytes\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage.data","title":"data instance-attribute","text":"
data: List[bytes]\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage.message_id","title":"message_id instance-attribute","text":"
message_id: NotRequired[str]\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage.message_ids","title":"message_ids instance-attribute","text":"
message_ids: NotRequired[List[str]]\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchMessage/#faststream.redis.message.BatchMessage.type","title":"type instance-attribute","text":"
type: Literal['batch']\n
","boost":0.5},{"location":"api/faststream/redis/message/BatchRedisMessage/","title":"BatchRedisMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/BatchRedisMessage/#faststream.redis.message.BatchRedisMessage","title":"faststream.redis.message.BatchRedisMessage","text":"

Bases: RedisAckMixin[BatchMessage]

","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/","title":"OneMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage","title":"faststream.redis.message.OneMessage","text":"

Bases: PubSubMessage

","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.channel","title":"channel instance-attribute","text":"
channel: bytes\n
","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.data","title":"data instance-attribute","text":"
data: bytes\n
","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.message_id","title":"message_id instance-attribute","text":"
message_id: NotRequired[str]\n
","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.message_ids","title":"message_ids instance-attribute","text":"
message_ids: NotRequired[List[str]]\n
","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.pattern","title":"pattern instance-attribute","text":"
pattern: NotRequired[Optional[bytes]]\n
","boost":0.5},{"location":"api/faststream/redis/message/OneMessage/#faststream.redis.message.OneMessage.type","title":"type instance-attribute","text":"
type: Literal['stream', 'list', 'message']\n
","boost":0.5},{"location":"api/faststream/redis/message/OneRedisMessage/","title":"OneRedisMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/OneRedisMessage/#faststream.redis.message.OneRedisMessage","title":"faststream.redis.message.OneRedisMessage","text":"

Bases: RedisAckMixin[OneMessage]

","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/","title":"PubSubMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage","title":"faststream.redis.message.PubSubMessage","text":"

Bases: TypedDict

","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage.channel","title":"channel instance-attribute","text":"
channel: bytes\n
","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage.data","title":"data instance-attribute","text":"
data: Union[bytes, List[bytes]]\n
","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage.message_id","title":"message_id instance-attribute","text":"
message_id: NotRequired[str]\n
","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage.message_ids","title":"message_ids instance-attribute","text":"
message_ids: NotRequired[List[str]]\n
","boost":0.5},{"location":"api/faststream/redis/message/PubSubMessage/#faststream.redis.message.PubSubMessage.type","title":"type instance-attribute","text":"
type: str\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/","title":"RedisAckMixin","text":"","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin","title":"faststream.redis.message.RedisAckMixin","text":"

Bases: StreamMessage[MsgType]

","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.body","title":"body instance-attribute","text":"
body: Union[bytes, Any]\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.commited","title":"commited class-attribute instance-attribute","text":"
commited: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.content_type","title":"content_type class-attribute instance-attribute","text":"
content_type: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.correlation_id","title":"correlation_id class-attribute instance-attribute","text":"
correlation_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.decoded_body","title":"decoded_body class-attribute instance-attribute","text":"
decoded_body: Optional[DecodedMessage] = None\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.message_id","title":"message_id class-attribute instance-attribute","text":"
message_id: str = field(\n    default_factory=lambda: str(uuid4())\n)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.path","title":"path class-attribute instance-attribute","text":"
path: AnyDict = field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.processed","title":"processed class-attribute instance-attribute","text":"
processed: bool = field(default=False, init=False)\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.raw_message","title":"raw_message instance-attribute","text":"
raw_message: Msg\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = ''\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.ack","title":"ack async","text":"
ack(redis: Redis[bytes], **kwargs: Any) -> None\n
Source code in faststream/redis/message.py
@override\nasync def ack(  # type: ignore[override]\n    self,\n    redis: \"Redis[bytes]\",\n    **kwargs: Any,\n) -> None:\n    if (\n        not self.commited\n        and (ids := self.raw_message.get(\"message_ids\"))\n        and (handler := context.get_local(\"handler_\"))\n        and (stream := handler.stream_sub)\n        and (group := stream.group)\n    ):\n        await redis.xack(self.raw_message[\"channel\"], group, *ids)  # type: ignore[no-untyped-call]\n        await super().ack()\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.nack","title":"nack async","text":"
nack(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def nack(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisAckMixin/#faststream.redis.message.RedisAckMixin.reject","title":"reject async","text":"
reject(**kwargs: Any) -> None\n
Source code in faststream/broker/message.py
async def reject(self, **kwargs: Any) -> None:\n    self.commited = True\n
","boost":0.5},{"location":"api/faststream/redis/message/RedisMessage/","title":"RedisMessage","text":"","boost":0.5},{"location":"api/faststream/redis/message/RedisMessage/#faststream.redis.message.RedisMessage","title":"faststream.redis.message.RedisMessage","text":"

Bases: RedisAckMixin[AnyRedisDict]

","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/","title":"RawMessage","text":"","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/#faststream.redis.parser.RawMessage","title":"faststream.redis.parser.RawMessage","text":"

Bases: BaseModel

","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/#faststream.redis.parser.RawMessage.data","title":"data instance-attribute","text":"
data: bytes\n
","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/#faststream.redis.parser.RawMessage.headers","title":"headers class-attribute instance-attribute","text":"
headers: AnyDict = Field(default_factory=dict)\n
","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/#faststream.redis.parser.RawMessage.build","title":"build classmethod","text":"
build(\n    message: SendableMessage,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n) -> RawMessage\n
Source code in faststream/redis/parser.py
@classmethod\ndef build(\n    cls,\n    message: SendableMessage,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n) -> \"RawMessage\":\n    payload, content_type = encode_message(message)\n\n    headers_to_send = {\n        \"correlation_id\": correlation_id or str(uuid4()),\n    }\n\n    if content_type:\n        headers_to_send[\"content-type\"] = content_type\n\n    if reply_to:\n        headers_to_send[\"reply_to\"] = reply_to\n\n    if headers is not None:\n        headers_to_send.update(headers)\n\n    return cls(\n        data=payload,\n        headers=headers_to_send,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/parser/RawMessage/#faststream.redis.parser.RawMessage.encode","title":"encode classmethod","text":"
encode(\n    message: SendableMessage,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n) -> str\n
Source code in faststream/redis/parser.py
@classmethod\ndef encode(\n    cls,\n    message: SendableMessage,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n) -> str:\n    return model_to_json(\n        cls.build(\n            message=message,\n            reply_to=reply_to,\n            headers=headers,\n            correlation_id=correlation_id,\n        )\n    )\n
","boost":0.5},{"location":"api/faststream/redis/parser/RedisParser/","title":"RedisParser","text":"","boost":0.5},{"location":"api/faststream/redis/parser/RedisParser/#faststream.redis.parser.RedisParser","title":"faststream.redis.parser.RedisParser","text":"","boost":0.5},{"location":"api/faststream/redis/parser/RedisParser/#faststream.redis.parser.RedisParser.decode_message","title":"decode_message async staticmethod","text":"
decode_message(msg: OneRedisMessage) -> DecodedMessage\n
Source code in faststream/redis/parser.py
@staticmethod\nasync def decode_message(\n    msg: OneRedisMessage,\n) -> DecodedMessage:\n    return decode_message(msg)\n
","boost":0.5},{"location":"api/faststream/redis/parser/RedisParser/#faststream.redis.parser.RedisParser.parse_message","title":"parse_message async classmethod","text":"
parse_message(\n    message: Union[OneMessage, BatchMessage]\n) -> Union[OneRedisMessage, BatchRedisMessage]\n
Source code in faststream/redis/parser.py
@classmethod\nasync def parse_message(\n    cls,\n    message: Union[OneMessage, BatchMessage],\n) -> Union[OneRedisMessage, BatchRedisMessage]:\n    id_ = str(uuid4())\n\n    if message[\"type\"] == \"batch\":\n        data = dump_json(\n            [cls.parse_one_msg(x)[0] for x in message[\"data\"]]\n        ).encode()\n\n        return BatchRedisMessage(\n            raw_message=message,\n            body=data,\n            content_type=\"application/json\",\n            message_id=id_,\n            correlation_id=id_,\n        )\n\n    else:\n        data, headers = cls.parse_one_msg(message[\"data\"])\n\n        channel = message.get(\"channel\", b\"\").decode()\n\n        handler = context.get_local(\"handler_\")\n        path_re: Optional[Pattern[str]]\n        path: AnyDict = {}\n        if (\n            handler\n            and handler.channel is not None\n            and (path_re := handler.channel.path_regex) is not None\n            and (match := path_re.match(channel)) is not None\n        ):\n            path = match.groupdict()\n\n        return OneRedisMessage(\n            raw_message=message,\n            body=data,\n            path=path,\n            headers=headers,\n            reply_to=headers.get(\"reply_to\", \"\"),\n            content_type=headers.get(\"content-type\", \"\"),\n            message_id=message.get(\"message_id\", id_),\n            correlation_id=headers.get(\"correlation_id\", id_),\n        )\n
","boost":0.5},{"location":"api/faststream/redis/parser/RedisParser/#faststream.redis.parser.RedisParser.parse_one_msg","title":"parse_one_msg staticmethod","text":"
parse_one_msg(raw_data: bytes) -> Tuple[bytes, AnyDict]\n
Source code in faststream/redis/parser.py
@staticmethod\ndef parse_one_msg(raw_data: bytes) -> Tuple[bytes, AnyDict]:\n    try:\n        obj = model_parse(RawMessage, raw_data)\n    except Exception:\n        # Raw Redis message format\n        data = raw_data\n        headers: AnyDict = {}\n    else:\n        # FastStream message format\n        data = obj.data\n        headers = obj.headers\n\n    return data, headers\n
","boost":0.5},{"location":"api/faststream/redis/producer/RedisFastProducer/","title":"RedisFastProducer","text":"","boost":0.5},{"location":"api/faststream/redis/producer/RedisFastProducer/#faststream.redis.producer.RedisFastProducer","title":"faststream.redis.producer.RedisFastProducer","text":"
RedisFastProducer(\n    connection: Redis[bytes],\n    parser: Union[\n        None,\n        AsyncCustomParser[OneMessage, OneRedisMessage],\n        AsyncCustomParser[BatchMessage, BatchRedisMessage],\n    ],\n    decoder: Union[\n        None,\n        AsyncCustomDecoder[OneRedisMessage],\n        AsyncCustomDecoder[BatchRedisMessage],\n    ],\n)\n
Source code in faststream/redis/producer.py
def __init__(\n    self,\n    connection: \"Redis[bytes]\",\n    parser: Union[\n        None,\n        AsyncCustomParser[OneMessage, OneRedisMessage],\n        AsyncCustomParser[BatchMessage, BatchRedisMessage],\n    ],\n    decoder: Union[\n        None,\n        AsyncCustomDecoder[OneRedisMessage],\n        AsyncCustomDecoder[BatchRedisMessage],\n    ],\n) -> None:\n    self._connection = connection\n    self._parser = resolve_custom_func(\n        parser,  # type: ignore[arg-type,assignment]\n        RedisParser.parse_message,\n    )\n    self._decoder = resolve_custom_func(decoder, RedisParser.decode_message)\n
","boost":0.5},{"location":"api/faststream/redis/producer/RedisFastProducer/#faststream.redis.producer.RedisFastProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    channel: Optional[str] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Optional[str] = None,\n    stream: Optional[str] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/producer.py
async def publish(\n    self,\n    message: SendableMessage,\n    channel: Optional[str] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Optional[str] = None,\n    stream: Optional[str] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    if not any((channel, list, stream)):\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    psub: Optional[PubSub] = None\n    if rpc is True:\n        if reply_to:\n            raise WRONG_PUBLISH_ARGS\n\n        reply_to = str(uuid4())\n        psub = self._connection.pubsub()\n        await psub.subscribe(reply_to)\n\n    msg = RawMessage.encode(\n        message=message,\n        reply_to=reply_to,\n        headers=headers,\n        correlation_id=correlation_id,\n    )\n\n    if channel is not None:\n        await self._connection.publish(channel, msg)\n    elif list is not None:\n        await self._connection.rpush(list, msg)\n    elif stream is not None:\n        await self._connection.xadd(stream, {DATA_KEY: msg})\n    else:\n        raise AssertionError(\"unreachable\")\n\n    if psub is None:\n        return None\n\n    else:\n        m = None\n        with timeout_scope(rpc_timeout, raise_timeout):\n            # skip subscribe message\n            await psub.get_message(\n                ignore_subscribe_messages=True,\n                timeout=rpc_timeout or 0.0,\n            )\n\n            # get real response\n            m = await psub.get_message(\n                ignore_subscribe_messages=True,\n                timeout=rpc_timeout or 0.0,\n            )\n\n        await psub.unsubscribe()\n        await psub.aclose()  # type: ignore[attr-defined]\n\n        if m is None:\n            if raise_timeout:\n                raise TimeoutError()\n            else:\n                return None\n        else:\n            return await self._decoder(await self._parser(m))\n
","boost":0.5},{"location":"api/faststream/redis/producer/RedisFastProducer/#faststream.redis.producer.RedisFastProducer.publish_batch","title":"publish_batch async","text":"
publish_batch(*msgs: SendableMessage, list: str) -> None\n
Source code in faststream/redis/producer.py
async def publish_batch(\n    self,\n    *msgs: SendableMessage,\n    list: str,\n) -> None:\n    batch = (encode_message(msg)[0] for msg in msgs)\n    await self._connection.rpush(list, *batch)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/","title":"LogicPublisher","text":"","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher","title":"faststream.redis.publisher.LogicPublisher dataclass","text":"

Bases: BasePublisher[AnyRedisDict]

","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.calls","title":"calls class-attribute instance-attribute","text":"
calls: List[Callable[..., Any]] = field(\n    init=False, default_factory=list, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.channel","title":"channel class-attribute instance-attribute","text":"
channel: Optional[PubSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.channel_name","title":"channel_name property","text":"
channel_name: str\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.description","title":"description property","text":"
description: Optional[str]\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.headers","title":"headers class-attribute instance-attribute","text":"
headers: Optional[AnyDict] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.include_in_schema","title":"include_in_schema class-attribute instance-attribute","text":"
include_in_schema: bool = field(default=True)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.list","title":"list class-attribute instance-attribute","text":"
list: Optional[ListSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.mock","title":"mock class-attribute instance-attribute","text":"
mock: Optional[MagicMock] = field(\n    init=False, default=None, repr=False\n)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.reply_to","title":"reply_to class-attribute instance-attribute","text":"
reply_to: str = field(default='')\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.stream","title":"stream class-attribute instance-attribute","text":"
stream: Optional[StreamSub] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.title","title":"title class-attribute instance-attribute","text":"
title: Optional[str] = field(default=None)\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.get_payloads","title":"get_payloads","text":"
get_payloads() -> List[Tuple[AnyDict, str]]\n
Source code in faststream/broker/publisher.py
def get_payloads(self) -> List[Tuple[AnyDict, str]]:\n    payloads: List[Tuple[AnyDict, str]] = []\n\n    if self._schema:\n        call_model: CallModel[Any, Any] = CallModel(\n            call=lambda: None,\n            model=create_model(\"Fake\"),\n            response_model=create_model(\n                \"\",\n                __config__=get_config_base(),  # type: ignore[arg-type]\n                response__=(self._schema, ...),\n            ),\n        )\n\n        body = get_response_schema(\n            call_model,\n            prefix=f\"{self.name}:Message\",\n        )\n        if body:  # pragma: no branch\n            payloads.append((body, \"\"))\n\n    else:\n        for call in self.calls:\n            call_model = build_call_model(call)\n            body = get_response_schema(\n                call_model,\n                prefix=f\"{self.name}:Message\",\n            )\n            if body:\n                payloads.append((body, to_camelcase(unwrap(call).__name__)))\n\n    return payloads\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.name","title":"name","text":"
name() -> str\n
Source code in faststream/asyncapi/base.py
@abstractproperty\ndef name(self) -> str:\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    channel: Union[str, PubSub, None] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/publisher.py
@override\nasync def publish(  # type: ignore[override]\n    self,\n    message: SendableMessage,\n    channel: Union[str, PubSub, None] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    assert self._producer, NOT_CONNECTED_YET  # nosec B101\n\n    channel = PubSub.validate(channel or self.channel)\n    list = ListSub.validate(list or self.list)\n    stream = StreamSub.validate(stream or self.stream)\n\n    assert any(\n        (channel, list, stream)\n    ), \"You have to specify outgoing channel\"  # nosec B101\n\n    headers_to_send = (self.headers or {}).copy()\n    if headers is not None:\n        headers_to_send.update(headers)\n\n    if getattr(list, \"batch\", False):\n        await self._producer.publish_batch(\n            *message,\n            list=list.name,  # type: ignore[union-attr]\n        )\n        return None\n\n    else:\n        return await self._producer.publish(\n            message=message,\n            channel=getattr(channel, \"name\", None),\n            list=getattr(list, \"name\", None),\n            stream=getattr(stream, \"name\", None),\n            reply_to=reply_to or self.reply_to,\n            correlation_id=correlation_id,\n            headers=headers_to_send,\n            rpc=rpc,\n            rpc_timeout=rpc_timeout,\n            raise_timeout=raise_timeout,\n        )\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.reset_test","title":"reset_test","text":"
reset_test() -> None\n
Source code in faststream/broker/publisher.py
def reset_test(self) -> None:\n    self._fake_handler = False\n    self.mock = None\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.schema","title":"schema","text":"
schema() -> Dict[str, Channel]\n
Source code in faststream/asyncapi/base.py
def schema(self) -> Dict[str, Channel]:  # pragma: no cover\n    return {}\n
","boost":0.5},{"location":"api/faststream/redis/publisher/LogicPublisher/#faststream.redis.publisher.LogicPublisher.set_test","title":"set_test","text":"
set_test(mock: MagicMock, with_fake: bool) -> None\n
Source code in faststream/broker/publisher.py
def set_test(\n    self,\n    mock: MagicMock,\n    with_fake: bool,\n) -> None:\n    self.mock = mock\n    self._fake_handler = with_fake\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/","title":"RedisRouter","text":"","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter","title":"faststream.redis.router.RedisRouter","text":"
RedisRouter(\n    prefix: str = \"\",\n    handlers: Sequence[RedisRoute] = (),\n    *,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    include_in_schema: bool = True\n)\n

Bases: RedisRouter

Source code in faststream/redis/router.py
            publisher.list, update={\"name\": prefix + publisher.list.name}\n        )\n    elif publisher.stream is not None:\n        publisher.stream = model_copy(\n            publisher.stream, update={\"name\": prefix + publisher.stream.name}\n        )\n    else:\n        raise AssertionError(\"unreachable\")\n    return publisher\n\n@override\ndef publisher(  # type: ignore[override]\n    self,\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.publisher","title":"publisher","text":"
publisher(\n    channel: Union[str, PubSub, None] = None,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher\n
Source code in faststream/redis/router.py
@override\ndef publisher(  # type: ignore[override]\n    self,\n    channel: Union[str, PubSub, None] = None,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    headers: Optional[AnyDict] = None,\n    reply_to: str = \"\",\n    # AsyncAPI information\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    schema: Optional[Any] = None,\n    include_in_schema: bool = True,\n) -> Publisher:\n    if not any((stream, list, channel)):\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            channel=PubSub.validate(channel),\n            list=ListSub.validate(list),\n            stream=StreamSub.validate(stream),\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n    )\n    return publisher\n
","boost":0.5},{"location":"api/faststream/redis/router/RedisRouter/#faststream.redis.router.RedisRouter.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[str, PubSub, None] = None,\n    *,\n    list: Union[str, ListSub, None] = None,\n    stream: Union[str, StreamSub, None] = None,\n    dependencies: Sequence[Depends] = (),\n    parser: Optional[\n        CustomParser[AnyRedisDict, RedisMessage]\n    ] = None,\n    decoder: Optional[CustomDecoder[RedisMessage]] = None,\n    middlewares: Optional[\n        Sequence[Callable[[AnyRedisDict], BaseMiddleware]]\n    ] = None,\n    filter: Filter[RedisMessage] = default_filter,\n    no_ack: bool = False,\n    title: Optional[str] = None,\n    description: Optional[str] = None,\n    include_in_schema: bool = True,\n    **__service_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        Any, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/router.py
) -> Publisher:\n    if not any((stream, list, channel)):\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    new_publisher = self._update_publisher_prefix(\n        self.prefix,\n        Publisher(\n            channel=PubSub.validate(channel),\n            list=ListSub.validate(list),\n            stream=StreamSub.validate(stream),\n            reply_to=reply_to,\n            headers=headers,\n            title=title,\n            _description=description,\n            _schema=schema,\n            include_in_schema=(\n                include_in_schema\n                if self.include_in_schema is None\n                else self.include_in_schema\n            ),\n        ),\n    )\n    publisher_key = self._get_publisher_key(new_publisher)\n    publisher = self._publishers[publisher_key] = self._publishers.get(\n        publisher_key, new_publisher\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/","title":"ListSub","text":"","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub","title":"faststream.redis.schemas.ListSub","text":"
ListSub(\n    channel: str,\n    batch: bool = False,\n    max_records: PositiveInt = 10,\n    polling_interval: PositiveFloat = 0.1,\n)\n

Bases: NameRequired

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    channel: str,\n    batch: bool = False,\n    max_records: PositiveInt = 10,\n    polling_interval: PositiveFloat = 0.1,\n) -> None:\n    super().__init__(\n        name=channel,\n        batch=batch,\n        max_records=max_records,\n        polling_interval=polling_interval,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.max_records","title":"max_records class-attribute instance-attribute","text":"
max_records: PositiveInt = 10\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: PositiveFloat = 0.1\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.records","title":"records property","text":"
records: Optional[PositiveInt]\n
","boost":0.5},{"location":"api/faststream/redis/schemas/ListSub/#faststream.redis.schemas.ListSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/","title":"PubSub","text":"","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub","title":"faststream.redis.schemas.PubSub","text":"
PubSub(\n    channel: str,\n    pattern: bool = False,\n    polling_interval: PositiveFloat = 1.0,\n)\n

Bases: NameRequired

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    channel: str,\n    pattern: bool = False,\n    polling_interval: PositiveFloat = 1.0,\n) -> None:\n    reg, path = compile_path(channel, replace_symbol=\"*\")\n\n    if reg is not None:\n        pattern = True\n\n    super().__init__(\n        name=path,\n        path_regex=reg,\n        pattern=pattern,\n        polling_interval=polling_interval,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.last_id","title":"last_id class-attribute instance-attribute","text":"
last_id: str = '$'\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.model_config","title":"model_config class-attribute instance-attribute","text":"
model_config = {'arbitrary_types_allowed': True}\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.path_regex","title":"path_regex class-attribute instance-attribute","text":"
path_regex: Optional[Pattern[str]] = None\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.pattern","title":"pattern class-attribute instance-attribute","text":"
pattern: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: PositiveFloat = 1.0\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.Config","title":"Config","text":"","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.Config.arbitrary_types_allowed","title":"arbitrary_types_allowed class-attribute instance-attribute","text":"
arbitrary_types_allowed = True\n
","boost":0.5},{"location":"api/faststream/redis/schemas/PubSub/#faststream.redis.schemas.PubSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/","title":"StreamSub","text":"","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub","title":"faststream.redis.schemas.StreamSub","text":"
StreamSub(\n    stream: str,\n    polling_interval: Optional[PositiveInt] = 100,\n    group: Optional[str] = None,\n    consumer: Optional[str] = None,\n    batch: bool = False,\n    no_ack: bool = False,\n    last_id: Optional[str] = None,\n)\n

Bases: NameRequired

Redis Stream subscriber parameters

PARAMETER DESCRIPTION stream

(str): Redis Stream name.

TYPE: str

polling_interval

(int:ms | None): wait message block.

TYPE: Optional[PositiveInt] DEFAULT: 100

group

(str | None): consumer group name.

TYPE: Optional[str] DEFAULT: None

consumer

(str | None): consumer name.

TYPE: Optional[str] DEFAULT: None

batch

(bool): consume messages in batches.

TYPE: bool DEFAULT: False

no_ack

(bool): do not add message to PEL.

TYPE: bool DEFAULT: False

Source code in faststream/redis/schemas.py
def __init__(\n    self,\n    stream: str,\n    polling_interval: Optional[PositiveInt] = 100,\n    group: Optional[str] = None,\n    consumer: Optional[str] = None,\n    batch: bool = False,\n    no_ack: bool = False,\n    last_id: Optional[str] = None,\n) -> None:\n    \"\"\"\n    Redis Stream subscriber parameters\n\n    Args:\n        stream: (str): Redis Stream name.\n        polling_interval: (int:ms | None): wait message block.\n        group: (str | None): consumer group name.\n        consumer: (str | None): consumer name.\n        batch: (bool): consume messages in batches.\n        no_ack: (bool): do not add message to PEL.\n    \"\"\"\n    if (group and not consumer) or (not group and consumer):\n        raise ValueError(\"You should specify `group` and `consumer` both\")\n\n    if group and consumer:\n        msg: Optional[str] = None\n\n        if last_id:\n            msg = \"`last_id` has no effect with consumer group\"\n\n        if no_ack:\n            msg = \"`no_ack` has no effect with consumer group\"\n\n        if msg:\n            warnings.warn(\n                message=msg,\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n    super().__init__(\n        name=stream,\n        group=group,\n        consumer=consumer,\n        polling_interval=polling_interval,\n        batch=batch,\n        no_ack=no_ack,\n        last_id=last_id or \"$\",\n    )\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.batch","title":"batch class-attribute instance-attribute","text":"
batch: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.consumer","title":"consumer class-attribute instance-attribute","text":"
consumer: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.group","title":"group class-attribute instance-attribute","text":"
group: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.last_id","title":"last_id class-attribute instance-attribute","text":"
last_id: str = '$'\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.name","title":"name class-attribute instance-attribute","text":"
name: str = Field(...)\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.no_ack","title":"no_ack class-attribute instance-attribute","text":"
no_ack: bool = False\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.polling_interval","title":"polling_interval class-attribute instance-attribute","text":"
polling_interval: Optional[PositiveInt] = Field(\n    default=100, description=\"ms\"\n)\n
","boost":0.5},{"location":"api/faststream/redis/schemas/StreamSub/#faststream.redis.schemas.StreamSub.validate","title":"validate classmethod","text":"
validate(\n    value: Union[str, NameRequiredCls, None], **kwargs: Any\n) -> Optional[NameRequiredCls]\n

Validates a value.

PARAMETER DESCRIPTION value

The value to be validated.

TYPE: Union[str, NameRequiredCls, None]

RETURNS DESCRIPTION Optional[NameRequiredCls]

The validated value.

Source code in faststream/broker/schemas.py
@classmethod\ndef validate(\n    cls: Type[NameRequiredCls],\n    value: Union[str, NameRequiredCls, None],\n    **kwargs: Any,\n) -> Optional[NameRequiredCls]:\n    \"\"\"Validates a value.\n\n    Args:\n        value: The value to be validated.\n\n    Returns:\n        The validated value.\n\n    \"\"\"\n    if value is not None:\n        if isinstance(value, str):\n            value = cls(value, **kwargs)\n    return value\n
","boost":0.5},{"location":"api/faststream/redis/security/parse_security/","title":"parse_security","text":"","boost":0.5},{"location":"api/faststream/redis/security/parse_security/#faststream.redis.security.parse_security","title":"faststream.redis.security.parse_security","text":"
parse_security(security: Optional[BaseSecurity]) -> AnyDict\n
Source code in faststream/redis/security.py
def parse_security(security: Optional[BaseSecurity]) -> AnyDict:\n    if security is None:\n        return {}\n    elif isinstance(security, SASLPlaintext):\n        return _parse_sasl_plaintext(security)\n    elif isinstance(security, BaseSecurity):\n        return _parse_base_security(security)\n    else:\n        raise NotImplementedError(f\"RedisBroker does not support {type(security)}\")\n
","boost":0.5},{"location":"api/faststream/redis/shared/logging/RedisLoggingMixin/","title":"RedisLoggingMixin","text":"","boost":0.5},{"location":"api/faststream/redis/shared/logging/RedisLoggingMixin/#faststream.redis.shared.logging.RedisLoggingMixin","title":"faststream.redis.shared.logging.RedisLoggingMixin","text":"
RedisLoggingMixin(\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any\n)\n

Bases: LoggingMixin

Source code in faststream/redis/shared/logging.py
def __init__(\n    self,\n    *args: Any,\n    logger: Optional[logging.Logger] = access_logger,\n    log_level: int = logging.INFO,\n    log_fmt: Optional[str] = None,\n    **kwargs: Any,\n) -> None:\n    super().__init__(\n        *args,\n        logger=logger,\n        log_level=log_level,\n        log_fmt=log_fmt,\n        **kwargs,\n    )\n    self._message_id_ln = 15\n    self._max_channel_name = 4\n
","boost":0.5},{"location":"api/faststream/redis/shared/logging/RedisLoggingMixin/#faststream.redis.shared.logging.RedisLoggingMixin.fmt","title":"fmt property","text":"
fmt: str\n
","boost":0.5},{"location":"api/faststream/redis/shared/logging/RedisLoggingMixin/#faststream.redis.shared.logging.RedisLoggingMixin.log_level","title":"log_level instance-attribute","text":"
log_level = log_level\n
","boost":0.5},{"location":"api/faststream/redis/shared/logging/RedisLoggingMixin/#faststream.redis.shared.logging.RedisLoggingMixin.logger","title":"logger instance-attribute","text":"
logger = logger\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRoute/","title":"RedisRoute","text":"","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRoute/#faststream.broker.router.BrokerRoute","title":"faststream.broker.router.BrokerRoute","text":"
BrokerRoute(\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any\n)\n

Bases: Generic[MsgType, T_HandlerReturn]

A generic class to represent a broker route.

PARAMETER DESCRIPTION call

callable object representing the route

*args

variable length arguments for the route

DEFAULT: ()

**kwargs

variable length keyword arguments for the route

DEFAULT: {}

Initialize a callable object with arguments and keyword arguments.

PARAMETER DESCRIPTION call

A callable object.

TYPE: Callable[..., T_HandlerReturn]

*args

Positional arguments to be passed to the callable object.

TYPE: Any DEFAULT: ()

**kwargs

Keyword arguments to be passed to the callable object.

TYPE: Any DEFAULT: {}

Source code in faststream/broker/router.py
def __init__(\n    self,\n    call: Callable[..., T_HandlerReturn],\n    *args: Any,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Initialize a callable object with arguments and keyword arguments.\n\n    Args:\n        call: A callable object.\n        *args: Positional arguments to be passed to the callable object.\n        **kwargs: Keyword arguments to be passed to the callable object.\n\n    \"\"\"\n    self.call = call\n    self.args = args\n    self.kwargs = kwargs\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRoute/#faststream.broker.router.BrokerRoute.args","title":"args instance-attribute","text":"
args: Tuple[Any, ...] = args\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRoute/#faststream.broker.router.BrokerRoute.call","title":"call instance-attribute","text":"
call: Callable[..., T_HandlerReturn] = call\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRoute/#faststream.broker.router.BrokerRoute.kwargs","title":"kwargs instance-attribute","text":"
kwargs: AnyDict = kwargs\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/","title":"RedisRouter","text":"","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter","title":"faststream.redis.shared.router.RedisRouter","text":"
RedisRouter(\n    prefix: str = \"\",\n    handlers: Sequence[\n        RedisRoute[AnyRedisDict, SendableMessage]\n    ] = (),\n    **kwargs: Any\n)\n

Bases: BrokerRouter[int, AnyRedisDict]

Source code in faststream/redis/shared/router.py
def __init__(\n    self,\n    prefix: str = \"\",\n    handlers: Sequence[RedisRoute[AnyRedisDict, SendableMessage]] = (),\n    **kwargs: Any,\n) -> None:\n    for h in handlers:\n        if not (channel := h.kwargs.pop(\"channel\", None)):\n            if list := h.kwargs.pop(\"list\", None):\n                h.kwargs[\"list\"] = prefix + list\n                continue\n\n            elif stream := h.kwargs.pop(\"stream\", None):\n                h.kwargs[\"stream\"] = prefix + stream\n                continue\n\n            channel, h.args = h.args[0], h.args[1:]\n\n        h.args = (prefix + channel, *h.args)\n\n    super().__init__(prefix, handlers, **kwargs)\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.include_in_schema","title":"include_in_schema instance-attribute","text":"
include_in_schema = include_in_schema\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.prefix","title":"prefix instance-attribute","text":"
prefix: str = prefix\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.include_router","title":"include_router","text":"
include_router(\n    router: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes a router in the current object.

PARAMETER DESCRIPTION router

The router to be included.

TYPE: BrokerRouter[PublisherKeyType, MsgType]

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_router(self, router: \"BrokerRouter[PublisherKeyType, MsgType]\") -> None:\n    \"\"\"Includes a router in the current object.\n\n    Args:\n        router: The router to be included.\n\n    Returns:\n        None\n\n    \"\"\"\n    for h in router._handlers:\n        self.subscriber(*h.args, **h.kwargs)(h.call)\n\n    for p in router._publishers.values():\n        p = self._update_publisher_prefix(self.prefix, p)\n        key = self._get_publisher_key(p)\n        self._publishers[key] = self._publishers.get(key, p)\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.include_routers","title":"include_routers","text":"
include_routers(\n    *routers: BrokerRouter[PublisherKeyType, MsgType]\n) -> None\n

Includes routers in the object.

PARAMETER DESCRIPTION *routers

Variable length argument list of routers to include.

TYPE: BrokerRouter[PublisherKeyType, MsgType] DEFAULT: ()

RETURNS DESCRIPTION None

None

Source code in faststream/broker/router.py
def include_routers(\n    self, *routers: \"BrokerRouter[PublisherKeyType, MsgType]\"\n) -> None:\n    \"\"\"Includes routers in the object.\n\n    Args:\n        *routers: Variable length argument list of routers to include.\n\n    Returns:\n        None\n\n    \"\"\"\n    for r in routers:\n        self.include_router(r)\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.publisher","title":"publisher abstractmethod","text":"
publisher(\n    subj: str, *args: Any, **kwargs: Any\n) -> BasePublisher[MsgType]\n

Publishes a message.

PARAMETER DESCRIPTION subj

Subject of the message

TYPE: str

*args

Additional arguments

TYPE: Any DEFAULT: ()

**kwargs

Additional keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION BasePublisher[MsgType]

The published message

RAISES DESCRIPTION NotImplementedError

If the method is not implemented

Source code in faststream/broker/router.py
@abstractmethod\ndef publisher(\n    self,\n    subj: str,\n    *args: Any,\n    **kwargs: Any,\n) -> BasePublisher[MsgType]:\n    \"\"\"Publishes a message.\n\n    Args:\n        subj: Subject of the message\n        *args: Additional arguments\n        **kwargs: Additional keyword arguments\n\n    Returns:\n        The published message\n\n    Raises:\n        NotImplementedError: If the method is not implemented\n\n    \"\"\"\n    raise NotImplementedError()\n
","boost":0.5},{"location":"api/faststream/redis/shared/router/RedisRouter/#faststream.redis.shared.router.RedisRouter.subscriber","title":"subscriber","text":"
subscriber(\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    **broker_kwargs: Any\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[\n        AnyRedisDict, P_HandlerParams, T_HandlerReturn\n    ],\n]\n
Source code in faststream/redis/shared/router.py
@override\ndef subscriber(  # type: ignore[override]\n    self,\n    channel: Union[Channel, PubSub, None] = None,\n    *,\n    list: Union[Channel, ListSub, None] = None,\n    stream: Union[Channel, StreamSub, None] = None,\n    **broker_kwargs: Any,\n) -> Callable[\n    [Callable[P_HandlerParams, T_HandlerReturn]],\n    HandlerCallWrapper[AnyRedisDict, P_HandlerParams, T_HandlerReturn],\n]:\n    channel = PubSub.validate(channel)\n    list = ListSub.validate(list)\n    stream = StreamSub.validate(stream)\n\n    return self._wrap_subscriber(\n        channel=model_copy(channel, update={\"name\": self.prefix + channel.name})\n        if channel\n        else None,\n        list=model_copy(list, update={\"name\": self.prefix + list.name})\n        if list\n        else None,\n        stream=model_copy(stream, update={\"name\": self.prefix + stream.name})\n        if stream\n        else None,\n        **broker_kwargs,\n    )\n
","boost":0.5},{"location":"api/faststream/redis/test/FakeProducer/","title":"FakeProducer","text":"","boost":0.5},{"location":"api/faststream/redis/test/FakeProducer/#faststream.redis.test.FakeProducer","title":"faststream.redis.test.FakeProducer","text":"
FakeProducer(broker: RedisBroker)\n

Bases: RedisFastProducer

Source code in faststream/redis/test.py
def __init__(self, broker: RedisBroker) -> None:\n    self.broker = broker\n
","boost":0.5},{"location":"api/faststream/redis/test/FakeProducer/#faststream.redis.test.FakeProducer.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/redis/test/FakeProducer/#faststream.redis.test.FakeProducer.publish","title":"publish async","text":"
publish(\n    message: SendableMessage,\n    channel: Optional[str] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Optional[str] = None,\n    stream: Optional[str] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False\n) -> Optional[DecodedMessage]\n
Source code in faststream/redis/test.py
@override\nasync def publish(\n    self,\n    message: SendableMessage,\n    channel: Optional[str] = None,\n    reply_to: str = \"\",\n    headers: Optional[AnyDict] = None,\n    correlation_id: Optional[str] = None,\n    *,\n    list: Optional[str] = None,\n    stream: Optional[str] = None,\n    rpc: bool = False,\n    rpc_timeout: Optional[float] = 30.0,\n    raise_timeout: bool = False,\n) -> Optional[DecodedMessage]:\n    any_of = channel or list or stream\n    if any_of is None:\n        raise ValueError(INCORRECT_SETUP_MSG)\n\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        call = False\n        batch = False\n\n        if channel and (ch := handler.channel) is not None:\n            call = bool(\n                (not ch.pattern and ch.name == channel)\n                or (\n                    ch.pattern\n                    and re.match(\n                        ch.name.replace(\".\", \"\\\\.\").replace(\"*\", \".*\"),\n                        channel,\n                    )\n                )\n            )\n\n        if list and (ls := handler.list_sub) is not None:\n            batch = ls.batch\n            call = list == ls.name\n\n        if stream and (st := handler.stream_sub) is not None:\n            batch = st.batch\n            call = stream == st.name\n\n        if call:\n            r = await call_handler(\n                handler=handler,\n                message=build_message(\n                    message=[message] if batch else message,\n                    channel=any_of,\n                    headers=headers,\n                    correlation_id=correlation_id,\n                    reply_to=reply_to,\n                ),\n                rpc=rpc,\n                rpc_timeout=rpc_timeout,\n                raise_timeout=raise_timeout,\n            )\n\n            if rpc:  # pragma: no branch\n                return r\n\n    return None\n
","boost":0.5},{"location":"api/faststream/redis/test/FakeProducer/#faststream.redis.test.FakeProducer.publish_batch","title":"publish_batch async","text":"
publish_batch(*msgs: SendableMessage, list: str) -> None\n
Source code in faststream/redis/test.py
async def publish_batch(\n    self,\n    *msgs: SendableMessage,\n    list: str,\n) -> None:\n    for handler in self.broker.handlers.values():  # pragma: no branch\n        if handler.list_sub and handler.list_sub.name == list:\n            await call_handler(\n                handler=handler,\n                message=build_message(\n                    message=msgs,\n                    channel=list,\n                ),\n            )\n\n    return None\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/","title":"TestRedisBroker","text":"","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker","title":"faststream.redis.test.TestRedisBroker","text":"
TestRedisBroker(\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n)\n

Bases: TestBroker[RedisBroker]

Source code in faststream/broker/test.py
def __init__(\n    self,\n    broker: Broker,\n    with_real: bool = False,\n    connect_only: Optional[bool] = None,\n) -> None:\n    self.with_real = with_real\n    self.broker = broker\n\n    if connect_only is None:\n        try:\n            connect_only = is_contains_context_name(\n                self.__class__.__name__,\n                TestApp.__name__,\n            )\n\n        except Exception as e:  # pragma: no cover\n            # TODO: remove with 0.5.0\n            warnings.warn(\n                (\n                    f\"\\nError `{repr(e)}` occured at `{self.__class__.__name__}` AST parsing\"\n                    \"\\nPlease, report us by creating an Issue with your TestClient usecase\"\n                    \"\\nhttps://github.com/airtai/faststream/issues/new?labels=bug&template=bug_report.md&title=Bug:%20TestClient%20AST%20parsing\"\n                ),\n                category=RuntimeWarning,\n                stacklevel=1,\n            )\n\n            connect_only = False\n\n    self.connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.broker","title":"broker instance-attribute","text":"
broker = broker\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.connect_only","title":"connect_only instance-attribute","text":"
connect_only = connect_only\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.with_real","title":"with_real instance-attribute","text":"
with_real = with_real\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.create_publisher_fake_subscriber","title":"create_publisher_fake_subscriber staticmethod","text":"
create_publisher_fake_subscriber(\n    broker: RedisBroker, publisher: Publisher\n) -> HandlerCallWrapper[Any, Any, Any]\n
Source code in faststream/redis/test.py
@staticmethod\ndef create_publisher_fake_subscriber(\n    broker: RedisBroker,\n    publisher: Publisher,\n) -> HandlerCallWrapper[Any, Any, Any]:\n    @broker.subscriber(\n        channel=publisher.channel,\n        list=publisher.list,\n        stream=publisher.stream,\n        _raw=True,\n    )\n    def f(msg: Any) -> None:\n        pass\n\n    return f\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.patch_publisher","title":"patch_publisher staticmethod","text":"
patch_publisher(\n    broker: RedisBroker, publisher: Any\n) -> None\n
Source code in faststream/redis/test.py
@staticmethod\ndef patch_publisher(\n    broker: RedisBroker,\n    publisher: Any,\n) -> None:\n    publisher._producer = broker._producer\n
","boost":0.5},{"location":"api/faststream/redis/test/TestRedisBroker/#faststream.redis.test.TestRedisBroker.remove_publisher_fake_subscriber","title":"remove_publisher_fake_subscriber staticmethod","text":"
remove_publisher_fake_subscriber(\n    broker: RedisBroker, publisher: Publisher\n) -> None\n
Source code in faststream/redis/test.py
@staticmethod\ndef remove_publisher_fake_subscriber(\n    broker: RedisBroker,\n    publisher: Publisher,\n) -> None:\n    any_of = publisher.channel or publisher.list or publisher.stream\n    assert any_of  # nosec B101\n    broker.handlers.pop(Handler.get_routing_hash(any_of), None)\n
","boost":0.5},{"location":"api/faststream/redis/test/build_message/","title":"build_message","text":"","boost":0.5},{"location":"api/faststream/redis/test/build_message/#faststream.redis.test.build_message","title":"faststream.redis.test.build_message","text":"
build_message(\n    message: SendableMessage,\n    channel: str,\n    *,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[AnyDict] = None\n) -> AnyRedisDict\n
Source code in faststream/redis/test.py
def build_message(\n    message: SendableMessage,\n    channel: str,\n    *,\n    reply_to: str = \"\",\n    correlation_id: Optional[str] = None,\n    headers: Optional[AnyDict] = None,\n) -> AnyRedisDict:\n    data = RawMessage.encode(\n        message=message,\n        reply_to=reply_to,\n        headers=headers,\n        correlation_id=correlation_id,\n    )\n    return AnyRedisDict(\n        channel=channel.encode(),\n        data=data.encode(),\n        type=\"message\",\n    )\n
","boost":0.5},{"location":"api/faststream/security/BaseSecurity/","title":"BaseSecurity","text":"","boost":0.5},{"location":"api/faststream/security/BaseSecurity/#faststream.security.BaseSecurity","title":"faststream.security.BaseSecurity","text":"
BaseSecurity(\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Base class for defining security configurations.

This class provides a base for defining security configurations for communication with a broker. It allows setting SSL encryption and provides methods to retrieve security requirements and schemas.

PARAMETER DESCRIPTION ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements in the form of a list of dictionaries.

get_schema

Get the security schema as a dictionary.

Source code in faststream/security.py
def __init__(\n    self,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    if ssl_context is not None:\n        use_ssl = True\n\n    self.use_ssl = use_ssl\n    self.ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/security/BaseSecurity/#faststream.security.BaseSecurity.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/security/BaseSecurity/#faststream.security.BaseSecurity.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/security/BaseSecurity/#faststream.security.BaseSecurity.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return []\n
","boost":0.5},{"location":"api/faststream/security/BaseSecurity/#faststream.security.BaseSecurity.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {}\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/","title":"SASLPlaintext","text":"","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext","title":"faststream.security.SASLPlaintext","text":"
SASLPlaintext(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/PLAINTEXT authentication.

This class defines security configuration for SASL/PLAINTEXT authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/PLAINTEXT authentication.

get_schema

Get the security schema for SASL/PLAINTEXT authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/PLAINTEXT authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/PLAINTEXT authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"user-password\": []}]\n
","boost":0.5},{"location":"api/faststream/security/SASLPlaintext/#faststream.security.SASLPlaintext.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/PLAINTEXT authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/PLAINTEXT authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"user-password\": {\"type\": \"userPassword\"}}\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/","title":"SASLScram256","text":"","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256","title":"faststream.security.SASLScram256","text":"
SASLScram256(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/SCRAM-SHA-256 authentication.

This class defines security configuration for SASL/SCRAM-SHA-256 authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/SCRAM-SHA-256 authentication.

get_schema

Get the security schema for SASL/SCRAM-SHA-256 authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/SCRAM-SHA-256 authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/SCRAM-SHA-256 authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"scram256\": []}]\n
","boost":0.5},{"location":"api/faststream/security/SASLScram256/#faststream.security.SASLScram256.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/SCRAM-SHA-256 authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/SCRAM-SHA-256 authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"scram256\": {\"type\": \"scramSha256\"}}\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/","title":"SASLScram512","text":"","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512","title":"faststream.security.SASLScram512","text":"
SASLScram512(\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n)\n

Bases: BaseSecurity

Security configuration for SASL/SCRAM-SHA-512 authentication.

This class defines security configuration for SASL/SCRAM-SHA-512 authentication, which includes a username and password.

PARAMETER DESCRIPTION username

The username for authentication.

TYPE: str

password

The password for authentication.

TYPE: str

ssl_context

An SSLContext object for SSL encryption. If None, SSL encryption is disabled.

TYPE: Optional[SSLContext] DEFAULT: None

use_ssl

A boolean indicating whether to use SSL encryption. Defaults to True.

TYPE: Optional[bool] DEFAULT: None

METHOD DESCRIPTION get_requirement

Get the security requirements for SASL/SCRAM-SHA-512 authentication.

get_schema

Get the security schema for SASL/SCRAM-SHA-512 authentication.

Source code in faststream/security.py
def __init__(\n    self,\n    username: str,\n    password: str,\n    ssl_context: Optional[SSLContext] = None,\n    use_ssl: Optional[bool] = None,\n) -> None:\n    super().__init__(ssl_context, use_ssl)\n    self.username = username\n    self.password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.password","title":"password instance-attribute","text":"
password = password\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.ssl_context","title":"ssl_context instance-attribute","text":"
ssl_context = ssl_context\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.use_ssl","title":"use_ssl instance-attribute","text":"
use_ssl = use_ssl\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.username","title":"username instance-attribute","text":"
username = username\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.get_requirement","title":"get_requirement","text":"
get_requirement() -> List[AnyDict]\n

Get the security requirements for SASL/SCRAM-SHA-512 authentication.

RETURNS DESCRIPTION List[AnyDict]

List[AnyDict]: A list of dictionaries representing security requirements.

Source code in faststream/security.py
def get_requirement(self) -> List[AnyDict]:\n    \"\"\"\n    Get the security requirements for SASL/SCRAM-SHA-512 authentication.\n\n    Returns:\n        List[AnyDict]: A list of dictionaries representing security requirements.\n    \"\"\"\n    return [{\"scram512\": []}]\n
","boost":0.5},{"location":"api/faststream/security/SASLScram512/#faststream.security.SASLScram512.get_schema","title":"get_schema","text":"
get_schema() -> Dict[str, Dict[str, str]]\n

Get the security schema for SASL/SCRAM-SHA-512 authentication.

RETURNS DESCRIPTION Dict[str, Dict[str, str]]

Dict[str, Dict[str, str]]: A dictionary representing the security schema.

Source code in faststream/security.py
def get_schema(self) -> Dict[str, Dict[str, str]]:\n    \"\"\"\n    Get the security schema for SASL/SCRAM-SHA-512 authentication.\n\n    Returns:\n        Dict[str, Dict[str, str]]: A dictionary representing the security schema.\n    \"\"\"\n    return {\"scram512\": {\"type\": \"scramSha512\"}}\n
","boost":0.5},{"location":"api/faststream/utils/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/utils/Context/#faststream.utils.Context","title":"faststream.utils.Context","text":"
Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n    )\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/","title":"ContextRepo","text":"","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo","title":"faststream.utils.ContextRepo","text":"
ContextRepo()\n

Bases: Singleton

A class to represent a context repository.

METHOD DESCRIPTION __init__

initializes the ContextRepo object

set_global

sets a global context variable

reset_global

resets a global context variable

set_local

sets a local context variable

reset_local

resets a local context variable

get_local

gets the value of a local context variable

clear

clears the global and scope context

get

gets the value of a context variable

__getattr__

gets the value of a context variable using attribute access

context

gets the current context as a dictionary

scope

creates a context scope for a specific key and value

Initialize the class.

Source code in faststream/utils/context/main.py
def __init__(self) -> None:\n    \"\"\"Initialize the class.\n\n    Attributes:\n        _global_context : a dictionary representing the global context\n        _scope_context : a dictionary representing the scope context\n    \"\"\"\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.context","title":"context property","text":"
context: AnyDict\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.clear","title":"clear","text":"
clear() -> None\n
Source code in faststream/utils/context/main.py
def clear(self) -> None:\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.get","title":"get","text":"
get(key: str, default: Any = None) -> Any\n

Get the value associated with a key.

PARAMETER DESCRIPTION key

The key to retrieve the value for.

TYPE: str

RETURNS DESCRIPTION Any

The value associated with the key.

Source code in faststream/utils/context/main.py
def get(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value associated with a key.\n\n    Args:\n        key: The key to retrieve the value for.\n\n    Returns:\n        The value associated with the key.\n    \"\"\"\n    return self._global_context.get(key, self.get_local(key, default))\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.get_local","title":"get_local","text":"
get_local(key: str, default: Any = None) -> Any\n

Get the value of a local variable.

PARAMETER DESCRIPTION key

The key of the local variable to retrieve.

TYPE: str

RETURNS DESCRIPTION Any

The value of the local variable.

Source code in faststream/utils/context/main.py
def get_local(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value of a local variable.\n\n    Args:\n        key: The key of the local variable to retrieve.\n\n    Returns:\n        The value of the local variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is not None:  # pragma: no branch\n        return context_var.get()\n    else:\n        return default\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.reset_global","title":"reset_global","text":"
reset_global(key: str) -> None\n

Resets a key in the global context.

PARAMETER DESCRIPTION key

The key to reset in the global context.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_global(self, key: str) -> None:\n    \"\"\"Resets a key in the global context.\n\n    Args:\n        key (str): The key to reset in the global context.\n\n    Returns:\n        None\n    \"\"\"\n    self._global_context.pop(key, None)\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.reset_local","title":"reset_local","text":"
reset_local(key: str, tag: Token[Any]) -> None\n

Resets the local context for a given key.

PARAMETER DESCRIPTION key

The key to reset the local context for.

TYPE: str

tag

The tag associated with the local context.

TYPE: Token[Any]

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_local(self, key: str, tag: \"Token[Any]\") -> None:\n    \"\"\"Resets the local context for a given key.\n\n    Args:\n        key (str): The key to reset the local context for.\n        tag (Token[Any]): The tag associated with the local context.\n\n    Returns:\n        None\n    \"\"\"\n    self._scope_context[key].reset(tag)\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.resolve","title":"resolve","text":"
resolve(argument: str) -> Any\n

Resolve the context of an argument.

PARAMETER DESCRIPTION argument

A string representing the argument.

TYPE: str

RETURNS DESCRIPTION Any

The resolved context of the argument.

RAISES DESCRIPTION AttributeError

If the attribute does not exist in the context.

Source code in faststream/utils/context/main.py
def resolve(self, argument: str) -> Any:\n    \"\"\"Resolve the context of an argument.\n\n    Args:\n        argument: A string representing the argument.\n\n    Returns:\n        The resolved context of the argument.\n\n    Raises:\n        AttributeError: If the attribute does not exist in the context.\n    \"\"\"\n    first, *keys = argument.split(\".\")\n\n    if (v := self.get(first, _empty)) is _empty:\n        raise KeyError(f\"`{self.context}` does not contains `{first}` key\")\n\n    for i in keys:\n        if isinstance(v, Mapping):\n            v = v[i]\n        else:\n            v = getattr(v, i)\n    return v\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.scope","title":"scope","text":"
scope(key: str, value: Any) -> Iterator[None]\n

Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.

PARAMETER DESCRIPTION key

The key of the local variable

TYPE: str

value

The value to set the local variable to

TYPE: Any

YIELDS DESCRIPTION Iterator[None]

None

RETURNS DESCRIPTION Iterator[None]

An iterator that yields None

Source code in faststream/utils/context/main.py
@contextmanager\ndef scope(self, key: str, value: Any) -> Iterator[None]:\n    \"\"\"Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.\n\n    Args:\n        key: The key of the local variable\n        value: The value to set the local variable to\n\n    Yields:\n        None\n\n    Returns:\n        An iterator that yields None\n    \"\"\"\n    token = self.set_local(key, value)\n    try:\n        yield\n    finally:\n        self.reset_local(key, token)\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.set_global","title":"set_global","text":"
set_global(key: str, v: Any) -> None\n

Sets a value in the global context.

PARAMETER DESCRIPTION key

The key to set in the global context.

TYPE: str

v

The value to set.

TYPE: Any

RETURNS DESCRIPTION None

None.

Source code in faststream/utils/context/main.py
def set_global(self, key: str, v: Any) -> None:\n    \"\"\"Sets a value in the global context.\n\n    Args:\n        key: The key to set in the global context.\n        v: The value to set.\n\n    Returns:\n        None.\n    \"\"\"\n    self._global_context[key] = v\n
","boost":0.5},{"location":"api/faststream/utils/ContextRepo/#faststream.utils.ContextRepo.set_local","title":"set_local","text":"
set_local(key: str, value: T) -> Token[T]\n

Set a local context variable.

PARAMETER DESCRIPTION key

The key for the context variable.

TYPE: str

value

The value to set for the context variable.

TYPE: T

RETURNS DESCRIPTION Token[T]

Token[T]: A token representing the context variable.

Source code in faststream/utils/context/main.py
def set_local(self, key: str, value: T) -> \"Token[T]\":\n    \"\"\"Set a local context variable.\n\n    Args:\n        key (str): The key for the context variable.\n        value (T): The value to set for the context variable.\n\n    Returns:\n        Token[T]: A token representing the context variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is None:\n        context_var = ContextVar(key, default=None)\n        self._scope_context[key] = context_var\n    return context_var.set(value)\n
","boost":0.5},{"location":"api/faststream/utils/Depends/","title":"Depends","text":"","boost":0.5},{"location":"api/faststream/utils/Depends/#fast_depends.use.Depends","title":"fast_depends.use.Depends","text":"
Depends(\n    dependency: Callable[P, T],\n    *,\n    use_cache: bool = True,\n    cast: bool = True\n) -> Any\n
Source code in fast_depends/use.py
def Depends(\n    dependency: Callable[P, T],\n    *,\n    use_cache: bool = True,\n    cast: bool = True,\n) -> Any:\n    return model.Depends(\n        dependency=dependency,\n        use_cache=use_cache,\n        cast=cast,\n    )\n
","boost":0.5},{"location":"api/faststream/utils/Header/","title":"Header","text":"","boost":0.5},{"location":"api/faststream/utils/Header/#faststream.utils.Header","title":"faststream.utils.Header","text":"
Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.headers.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/","title":"NoCast","text":"","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast","title":"faststream.utils.NoCast","text":"
NoCast()\n

Bases: CustomField

A class that represents a custom field without casting.

METHOD DESCRIPTION __init__

Initializes the NoCast object.

use

Returns the provided keyword arguments as a dictionary.

Source code in faststream/utils/no_cast.py
def __init__(self) -> None:\n    super().__init__(cast=False)\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast.cast","title":"cast instance-attribute","text":"
cast: bool = cast\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast.param_name","title":"param_name instance-attribute","text":"
param_name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast.required","title":"required instance-attribute","text":"
required: bool = required\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast.set_param_name","title":"set_param_name","text":"
set_param_name(name: str) -> Cls\n
Source code in fast_depends/library/model.py
def set_param_name(self: Cls, name: str) -> Cls:\n    self.param_name = name\n    return self\n
","boost":0.5},{"location":"api/faststream/utils/NoCast/#faststream.utils.NoCast.use","title":"use","text":"
use(**kwargs: Any) -> AnyDict\n

Return a dictionary containing the keyword arguments passed to the function.

PARAMETER DESCRIPTION **kwargs

Keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION AnyDict

Dictionary containing the keyword arguments

Source code in faststream/utils/no_cast.py
def use(self, **kwargs: Any) -> AnyDict:\n    \"\"\"Return a dictionary containing the keyword arguments passed to the function.\n\n    Args:\n        **kwargs: Keyword arguments\n\n    Returns:\n        Dictionary containing the keyword arguments\n    \"\"\"\n    return kwargs\n
","boost":0.5},{"location":"api/faststream/utils/Path/","title":"Path","text":"","boost":0.5},{"location":"api/faststream/utils/Path/#faststream.utils.Path","title":"faststream.utils.Path","text":"
Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.path.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/apply_types/","title":"apply_types","text":"","boost":0.5},{"location":"api/faststream/utils/apply_types/#fast_depends.use.inject","title":"fast_depends.use.inject","text":"
inject(\n    func: Optional[Callable[P, T]] = None,\n    *,\n    cast: bool = True,\n    extra_dependencies: Sequence[model.Depends] = (),\n    pydantic_config: Optional[ConfigDict] = None,\n    dependency_overrides_provider: Optional[\n        Any\n    ] = dependency_provider,\n    wrap_model: Callable[\n        [CallModel[P, T]], CallModel[P, T]\n    ] = lambda: x\n) -> Union[Callable[P, T], _InjectWrapper[P, T]]\n
Source code in fast_depends/use.py
def inject(\n    func: Optional[Callable[P, T]] = None,\n    *,\n    cast: bool = True,\n    extra_dependencies: Sequence[model.Depends] = (),\n    pydantic_config: Optional[ConfigDict] = None,\n    dependency_overrides_provider: Optional[Any] = dependency_provider,\n    wrap_model: Callable[[CallModel[P, T]], CallModel[P, T]] = lambda x: x,\n) -> Union[Callable[P, T], _InjectWrapper[P, T],]:\n    decorator = _wrap_inject(\n        dependency_overrides_provider=dependency_overrides_provider,\n        wrap_model=wrap_model,\n        extra_dependencies=extra_dependencies,\n        cast=cast,\n        pydantic_config=pydantic_config,\n    )\n\n    if func is None:\n        return decorator\n\n    else:\n        return decorator(func)\n
","boost":0.5},{"location":"api/faststream/utils/ast/find_ast_node/","title":"find_ast_node","text":"","boost":0.5},{"location":"api/faststream/utils/ast/find_ast_node/#faststream.utils.ast.find_ast_node","title":"faststream.utils.ast.find_ast_node","text":"
find_ast_node(\n    module: ast.Module, lineno: Optional[int]\n) -> Optional[ast.AST]\n
Source code in faststream/utils/ast.py
def find_ast_node(module: ast.Module, lineno: Optional[int]) -> Optional[ast.AST]:\n    if lineno is not None:  # pragma: no branch\n        for i in getattr(module, \"body\", ()):\n            if i.lineno == lineno:\n                return cast(ast.AST, i)\n\n            r = find_ast_node(i, lineno)\n            if r is not None:\n                return r\n\n    return None\n
","boost":0.5},{"location":"api/faststream/utils/ast/find_withitems/","title":"find_withitems","text":"","boost":0.5},{"location":"api/faststream/utils/ast/find_withitems/#faststream.utils.ast.find_withitems","title":"faststream.utils.ast.find_withitems","text":"
find_withitems(\n    node: Union[ast.With, ast.AsyncWith]\n) -> Iterator[ast.withitem]\n
Source code in faststream/utils/ast.py
def find_withitems(node: Union[ast.With, ast.AsyncWith]) -> Iterator[ast.withitem]:\n    if isinstance(node, (ast.With, ast.AsyncWith)):\n        yield from node.items\n\n    for i in getattr(node, \"body\", ()):\n        yield from find_withitems(i)\n
","boost":0.5},{"location":"api/faststream/utils/ast/get_withitem_calls/","title":"get_withitem_calls","text":"","boost":0.5},{"location":"api/faststream/utils/ast/get_withitem_calls/#faststream.utils.ast.get_withitem_calls","title":"faststream.utils.ast.get_withitem_calls","text":"
get_withitem_calls(\n    node: Union[ast.With, ast.AsyncWith]\n) -> List[str]\n
Source code in faststream/utils/ast.py
def get_withitem_calls(node: Union[ast.With, ast.AsyncWith]) -> List[str]:\n    return [\n        id\n        for i in find_withitems(node)\n        if (id := getattr(i.context_expr.func, \"id\", None))  # type: ignore[attr-defined]\n    ]\n
","boost":0.5},{"location":"api/faststream/utils/ast/is_contains_context_name/","title":"is_contains_context_name","text":"","boost":0.5},{"location":"api/faststream/utils/ast/is_contains_context_name/#faststream.utils.ast.is_contains_context_name","title":"faststream.utils.ast.is_contains_context_name","text":"
is_contains_context_name(scip_name: str, name: str) -> bool\n
Source code in faststream/utils/ast.py
def is_contains_context_name(scip_name: str, name: str) -> bool:\n    stack = traceback.extract_stack()[-3]\n    tree = read_source_ast(stack.filename)\n    node = cast(Union[ast.With, ast.AsyncWith], find_ast_node(tree, stack.lineno))\n    context_calls = get_withitem_calls(node)\n\n    try:\n        pos = context_calls.index(scip_name)\n    except ValueError:\n        pos = 1\n\n    return name in context_calls[pos:]\n
","boost":0.5},{"location":"api/faststream/utils/classes/Singleton/","title":"Singleton","text":"","boost":0.5},{"location":"api/faststream/utils/classes/Singleton/#faststream.utils.classes.Singleton","title":"faststream.utils.classes.Singleton","text":"

A class to implement the Singleton design pattern.

METHOD DESCRIPTION __new__

creates a new instance of the class if it doesn't exist, otherwise returns the existing instance

_drop

sets the instance to None, allowing a new instance to be created

","boost":0.5},{"location":"api/faststream/utils/context/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/utils/context/Context/#faststream.utils.context.Context","title":"faststream.utils.context.Context","text":"
Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/","title":"ContextRepo","text":"","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo","title":"faststream.utils.context.ContextRepo","text":"
ContextRepo()\n

Bases: Singleton

A class to represent a context repository.

METHOD DESCRIPTION __init__

initializes the ContextRepo object

set_global

sets a global context variable

reset_global

resets a global context variable

set_local

sets a local context variable

reset_local

resets a local context variable

get_local

gets the value of a local context variable

clear

clears the global and scope context

get

gets the value of a context variable

__getattr__

gets the value of a context variable using attribute access

context

gets the current context as a dictionary

scope

creates a context scope for a specific key and value

Initialize the class.

Source code in faststream/utils/context/main.py
def __init__(self) -> None:\n    \"\"\"Initialize the class.\n\n    Attributes:\n        _global_context : a dictionary representing the global context\n        _scope_context : a dictionary representing the scope context\n    \"\"\"\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.context","title":"context property","text":"
context: AnyDict\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.clear","title":"clear","text":"
clear() -> None\n
Source code in faststream/utils/context/main.py
def clear(self) -> None:\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.get","title":"get","text":"
get(key: str, default: Any = None) -> Any\n

Get the value associated with a key.

PARAMETER DESCRIPTION key

The key to retrieve the value for.

TYPE: str

RETURNS DESCRIPTION Any

The value associated with the key.

Source code in faststream/utils/context/main.py
def get(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value associated with a key.\n\n    Args:\n        key: The key to retrieve the value for.\n\n    Returns:\n        The value associated with the key.\n    \"\"\"\n    return self._global_context.get(key, self.get_local(key, default))\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.get_local","title":"get_local","text":"
get_local(key: str, default: Any = None) -> Any\n

Get the value of a local variable.

PARAMETER DESCRIPTION key

The key of the local variable to retrieve.

TYPE: str

RETURNS DESCRIPTION Any

The value of the local variable.

Source code in faststream/utils/context/main.py
def get_local(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value of a local variable.\n\n    Args:\n        key: The key of the local variable to retrieve.\n\n    Returns:\n        The value of the local variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is not None:  # pragma: no branch\n        return context_var.get()\n    else:\n        return default\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.reset_global","title":"reset_global","text":"
reset_global(key: str) -> None\n

Resets a key in the global context.

PARAMETER DESCRIPTION key

The key to reset in the global context.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_global(self, key: str) -> None:\n    \"\"\"Resets a key in the global context.\n\n    Args:\n        key (str): The key to reset in the global context.\n\n    Returns:\n        None\n    \"\"\"\n    self._global_context.pop(key, None)\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.reset_local","title":"reset_local","text":"
reset_local(key: str, tag: Token[Any]) -> None\n

Resets the local context for a given key.

PARAMETER DESCRIPTION key

The key to reset the local context for.

TYPE: str

tag

The tag associated with the local context.

TYPE: Token[Any]

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_local(self, key: str, tag: \"Token[Any]\") -> None:\n    \"\"\"Resets the local context for a given key.\n\n    Args:\n        key (str): The key to reset the local context for.\n        tag (Token[Any]): The tag associated with the local context.\n\n    Returns:\n        None\n    \"\"\"\n    self._scope_context[key].reset(tag)\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.resolve","title":"resolve","text":"
resolve(argument: str) -> Any\n

Resolve the context of an argument.

PARAMETER DESCRIPTION argument

A string representing the argument.

TYPE: str

RETURNS DESCRIPTION Any

The resolved context of the argument.

RAISES DESCRIPTION AttributeError

If the attribute does not exist in the context.

Source code in faststream/utils/context/main.py
def resolve(self, argument: str) -> Any:\n    \"\"\"Resolve the context of an argument.\n\n    Args:\n        argument: A string representing the argument.\n\n    Returns:\n        The resolved context of the argument.\n\n    Raises:\n        AttributeError: If the attribute does not exist in the context.\n    \"\"\"\n    first, *keys = argument.split(\".\")\n\n    if (v := self.get(first, _empty)) is _empty:\n        raise KeyError(f\"`{self.context}` does not contains `{first}` key\")\n\n    for i in keys:\n        if isinstance(v, Mapping):\n            v = v[i]\n        else:\n            v = getattr(v, i)\n    return v\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.scope","title":"scope","text":"
scope(key: str, value: Any) -> Iterator[None]\n

Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.

PARAMETER DESCRIPTION key

The key of the local variable

TYPE: str

value

The value to set the local variable to

TYPE: Any

YIELDS DESCRIPTION Iterator[None]

None

RETURNS DESCRIPTION Iterator[None]

An iterator that yields None

Source code in faststream/utils/context/main.py
@contextmanager\ndef scope(self, key: str, value: Any) -> Iterator[None]:\n    \"\"\"Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.\n\n    Args:\n        key: The key of the local variable\n        value: The value to set the local variable to\n\n    Yields:\n        None\n\n    Returns:\n        An iterator that yields None\n    \"\"\"\n    token = self.set_local(key, value)\n    try:\n        yield\n    finally:\n        self.reset_local(key, token)\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.set_global","title":"set_global","text":"
set_global(key: str, v: Any) -> None\n

Sets a value in the global context.

PARAMETER DESCRIPTION key

The key to set in the global context.

TYPE: str

v

The value to set.

TYPE: Any

RETURNS DESCRIPTION None

None.

Source code in faststream/utils/context/main.py
def set_global(self, key: str, v: Any) -> None:\n    \"\"\"Sets a value in the global context.\n\n    Args:\n        key: The key to set in the global context.\n        v: The value to set.\n\n    Returns:\n        None.\n    \"\"\"\n    self._global_context[key] = v\n
","boost":0.5},{"location":"api/faststream/utils/context/ContextRepo/#faststream.utils.context.ContextRepo.set_local","title":"set_local","text":"
set_local(key: str, value: T) -> Token[T]\n

Set a local context variable.

PARAMETER DESCRIPTION key

The key for the context variable.

TYPE: str

value

The value to set for the context variable.

TYPE: T

RETURNS DESCRIPTION Token[T]

Token[T]: A token representing the context variable.

Source code in faststream/utils/context/main.py
def set_local(self, key: str, value: T) -> \"Token[T]\":\n    \"\"\"Set a local context variable.\n\n    Args:\n        key (str): The key for the context variable.\n        value (T): The value to set for the context variable.\n\n    Returns:\n        Token[T]: A token representing the context variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is None:\n        context_var = ContextVar(key, default=None)\n        self._scope_context[key] = context_var\n    return context_var.set(value)\n
","boost":0.5},{"location":"api/faststream/utils/context/Header/","title":"Header","text":"","boost":0.5},{"location":"api/faststream/utils/context/Header/#faststream.utils.context.Header","title":"faststream.utils.context.Header","text":"
Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.headers.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/Path/","title":"Path","text":"","boost":0.5},{"location":"api/faststream/utils/context/Path/#faststream.utils.context.Path","title":"faststream.utils.context.Path","text":"
Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.path.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/builders/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/utils/context/builders/Context/#faststream.utils.context.builders.Context","title":"faststream.utils.context.builders.Context","text":"
Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/builders/Header/","title":"Header","text":"","boost":0.5},{"location":"api/faststream/utils/context/builders/Header/#faststream.utils.context.builders.Header","title":"faststream.utils.context.builders.Header","text":"
Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Header(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.headers.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/builders/Path/","title":"Path","text":"","boost":0.5},{"location":"api/faststream/utils/context/builders/Path/#faststream.utils.context.builders.Path","title":"faststream.utils.context.builders.Path","text":"
Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty\n) -> Any\n
Source code in faststream/utils/context/builders.py
def Path(\n    real_name: str = \"\",\n    *,\n    cast: bool = True,\n    default: Any = _empty,\n) -> Any:\n    return Context_(\n        real_name=real_name,\n        cast=cast,\n        default=default,\n        prefix=\"message.path.\",\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/","title":"ContextRepo","text":"","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo","title":"faststream.utils.context.main.ContextRepo","text":"
ContextRepo()\n

Bases: Singleton

A class to represent a context repository.

METHOD DESCRIPTION __init__

initializes the ContextRepo object

set_global

sets a global context variable

reset_global

resets a global context variable

set_local

sets a local context variable

reset_local

resets a local context variable

get_local

gets the value of a local context variable

clear

clears the global and scope context

get

gets the value of a context variable

__getattr__

gets the value of a context variable using attribute access

context

gets the current context as a dictionary

scope

creates a context scope for a specific key and value

Initialize the class.

Source code in faststream/utils/context/main.py
def __init__(self) -> None:\n    \"\"\"Initialize the class.\n\n    Attributes:\n        _global_context : a dictionary representing the global context\n        _scope_context : a dictionary representing the scope context\n    \"\"\"\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.context","title":"context property","text":"
context: AnyDict\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.clear","title":"clear","text":"
clear() -> None\n
Source code in faststream/utils/context/main.py
def clear(self) -> None:\n    self._global_context = {\"context\": self}\n    self._scope_context = {}\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.get","title":"get","text":"
get(key: str, default: Any = None) -> Any\n

Get the value associated with a key.

PARAMETER DESCRIPTION key

The key to retrieve the value for.

TYPE: str

RETURNS DESCRIPTION Any

The value associated with the key.

Source code in faststream/utils/context/main.py
def get(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value associated with a key.\n\n    Args:\n        key: The key to retrieve the value for.\n\n    Returns:\n        The value associated with the key.\n    \"\"\"\n    return self._global_context.get(key, self.get_local(key, default))\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.get_local","title":"get_local","text":"
get_local(key: str, default: Any = None) -> Any\n

Get the value of a local variable.

PARAMETER DESCRIPTION key

The key of the local variable to retrieve.

TYPE: str

RETURNS DESCRIPTION Any

The value of the local variable.

Source code in faststream/utils/context/main.py
def get_local(self, key: str, default: Any = None) -> Any:\n    \"\"\"Get the value of a local variable.\n\n    Args:\n        key: The key of the local variable to retrieve.\n\n    Returns:\n        The value of the local variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is not None:  # pragma: no branch\n        return context_var.get()\n    else:\n        return default\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.reset_global","title":"reset_global","text":"
reset_global(key: str) -> None\n

Resets a key in the global context.

PARAMETER DESCRIPTION key

The key to reset in the global context.

TYPE: str

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_global(self, key: str) -> None:\n    \"\"\"Resets a key in the global context.\n\n    Args:\n        key (str): The key to reset in the global context.\n\n    Returns:\n        None\n    \"\"\"\n    self._global_context.pop(key, None)\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.reset_local","title":"reset_local","text":"
reset_local(key: str, tag: Token[Any]) -> None\n

Resets the local context for a given key.

PARAMETER DESCRIPTION key

The key to reset the local context for.

TYPE: str

tag

The tag associated with the local context.

TYPE: Token[Any]

RETURNS DESCRIPTION None

None

Source code in faststream/utils/context/main.py
def reset_local(self, key: str, tag: \"Token[Any]\") -> None:\n    \"\"\"Resets the local context for a given key.\n\n    Args:\n        key (str): The key to reset the local context for.\n        tag (Token[Any]): The tag associated with the local context.\n\n    Returns:\n        None\n    \"\"\"\n    self._scope_context[key].reset(tag)\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.resolve","title":"resolve","text":"
resolve(argument: str) -> Any\n

Resolve the context of an argument.

PARAMETER DESCRIPTION argument

A string representing the argument.

TYPE: str

RETURNS DESCRIPTION Any

The resolved context of the argument.

RAISES DESCRIPTION AttributeError

If the attribute does not exist in the context.

Source code in faststream/utils/context/main.py
def resolve(self, argument: str) -> Any:\n    \"\"\"Resolve the context of an argument.\n\n    Args:\n        argument: A string representing the argument.\n\n    Returns:\n        The resolved context of the argument.\n\n    Raises:\n        AttributeError: If the attribute does not exist in the context.\n    \"\"\"\n    first, *keys = argument.split(\".\")\n\n    if (v := self.get(first, _empty)) is _empty:\n        raise KeyError(f\"`{self.context}` does not contains `{first}` key\")\n\n    for i in keys:\n        if isinstance(v, Mapping):\n            v = v[i]\n        else:\n            v = getattr(v, i)\n    return v\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.scope","title":"scope","text":"
scope(key: str, value: Any) -> Iterator[None]\n

Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.

PARAMETER DESCRIPTION key

The key of the local variable

TYPE: str

value

The value to set the local variable to

TYPE: Any

YIELDS DESCRIPTION Iterator[None]

None

RETURNS DESCRIPTION Iterator[None]

An iterator that yields None

Source code in faststream/utils/context/main.py
@contextmanager\ndef scope(self, key: str, value: Any) -> Iterator[None]:\n    \"\"\"Sets a local variable and yields control to the caller. After the caller is done, the local variable is reset.\n\n    Args:\n        key: The key of the local variable\n        value: The value to set the local variable to\n\n    Yields:\n        None\n\n    Returns:\n        An iterator that yields None\n    \"\"\"\n    token = self.set_local(key, value)\n    try:\n        yield\n    finally:\n        self.reset_local(key, token)\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.set_global","title":"set_global","text":"
set_global(key: str, v: Any) -> None\n

Sets a value in the global context.

PARAMETER DESCRIPTION key

The key to set in the global context.

TYPE: str

v

The value to set.

TYPE: Any

RETURNS DESCRIPTION None

None.

Source code in faststream/utils/context/main.py
def set_global(self, key: str, v: Any) -> None:\n    \"\"\"Sets a value in the global context.\n\n    Args:\n        key: The key to set in the global context.\n        v: The value to set.\n\n    Returns:\n        None.\n    \"\"\"\n    self._global_context[key] = v\n
","boost":0.5},{"location":"api/faststream/utils/context/main/ContextRepo/#faststream.utils.context.main.ContextRepo.set_local","title":"set_local","text":"
set_local(key: str, value: T) -> Token[T]\n

Set a local context variable.

PARAMETER DESCRIPTION key

The key for the context variable.

TYPE: str

value

The value to set for the context variable.

TYPE: T

RETURNS DESCRIPTION Token[T]

Token[T]: A token representing the context variable.

Source code in faststream/utils/context/main.py
def set_local(self, key: str, value: T) -> \"Token[T]\":\n    \"\"\"Set a local context variable.\n\n    Args:\n        key (str): The key for the context variable.\n        value (T): The value to set for the context variable.\n\n    Returns:\n        Token[T]: A token representing the context variable.\n    \"\"\"\n    context_var = self._scope_context.get(key)\n    if context_var is None:\n        context_var = ContextVar(key, default=None)\n        self._scope_context[key] = context_var\n    return context_var.set(value)\n
","boost":0.5},{"location":"api/faststream/utils/context/path/compile_path/","title":"compile_path","text":"","boost":0.5},{"location":"api/faststream/utils/context/path/compile_path/#faststream.utils.context.path.compile_path","title":"faststream.utils.context.path.compile_path","text":"
compile_path(\n    path: str, replace_symbol: str\n) -> Tuple[Optional[Pattern[str]], str]\n
Source code in faststream/utils/context/path.py
def compile_path(\n    path: str,\n    replace_symbol: str,\n) -> Tuple[Optional[Pattern[str]], str]:\n    path_regex = \"^\"\n    path_format = \"\"\n\n    idx = 0\n    params = set()\n    duplicated_params = set()\n    for match in PARAM_REGEX.finditer(path):\n        param_name = match.groups(\"str\")[0]\n\n        path_regex += re.escape(path[idx : match.start()])\n        path_regex += f\"(?P<{param_name.replace('+', '')}>[^/]+)\"\n\n        path_format += path[idx : match.start()]\n        path_format += replace_symbol\n\n        if param_name in params:\n            duplicated_params.add(param_name)\n        else:\n            params.add(param_name)\n\n        idx = match.end()\n\n    if duplicated_params:\n        names = \", \".join(sorted(duplicated_params))\n        ending = \"s\" if len(duplicated_params) > 1 else \"\"\n        raise ValueError(f\"Duplicated param name{ending} {names} at path {path}\")\n\n    if idx == 0:\n        regex = None\n    else:\n        path_regex += re.escape(path[idx:]) + \"$\"\n        regex = re.compile(path_regex)\n\n    path_format += path[idx:]\n    return regex, path_format\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/","title":"Context","text":"","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context","title":"faststream.utils.context.types.Context","text":"
Context(\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n    prefix: str = \"\"\n)\n

Bases: CustomField

A class to represent a context.

METHOD DESCRIPTION __init__

constructor method

use

method to use the context

Initialize the object.

PARAMETER DESCRIPTION real_name

The real name of the object.

TYPE: str DEFAULT: ''

cast

Whether to cast the object.

TYPE: bool DEFAULT: False

default

The default value of the object.

TYPE: Any DEFAULT: _empty

RAISES DESCRIPTION TypeError

If the default value is not provided.

Source code in faststream/utils/context/types.py
def __init__(\n    self,\n    real_name: str = \"\",\n    *,\n    cast: bool = False,\n    default: Any = _empty,\n    prefix: str = \"\",\n) -> None:\n    \"\"\"Initialize the object.\n\n    Args:\n        real_name: The real name of the object.\n        cast: Whether to cast the object.\n        default: The default value of the object.\n\n    Raises:\n        TypeError: If the default value is not provided.\n    \"\"\"\n    self.name = real_name\n    self.default = default\n    self.prefix = prefix\n    super().__init__(\n        cast=cast,\n        required=(default is _empty),\n    )\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.cast","title":"cast instance-attribute","text":"
cast: bool = cast\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.default","title":"default instance-attribute","text":"
default = default\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.name","title":"name instance-attribute","text":"
name = real_name\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.param_name","title":"param_name instance-attribute","text":"
param_name: str\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.prefix","title":"prefix instance-attribute","text":"
prefix = prefix\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.required","title":"required instance-attribute","text":"
required: bool = required\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.set_param_name","title":"set_param_name","text":"
set_param_name(name: str) -> Cls\n
Source code in fast_depends/library/model.py
def set_param_name(self: Cls, name: str) -> Cls:\n    self.param_name = name\n    return self\n
","boost":0.5},{"location":"api/faststream/utils/context/types/Context/#faststream.utils.context.types.Context.use","title":"use","text":"
use(**kwargs: Any) -> AnyDict\n

Use the given keyword arguments.

PARAMETER DESCRIPTION **kwargs

Keyword arguments to be used

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION AnyDict

A dictionary containing the updated keyword arguments

RAISES DESCRIPTION KeyError

If the parameter name is not found in the keyword arguments

AttributeError

If the parameter name is not a valid attribute

Source code in faststream/utils/context/types.py
def use(self, /, **kwargs: Any) -> AnyDict:\n    \"\"\"Use the given keyword arguments.\n\n    Args:\n        **kwargs: Keyword arguments to be used\n\n    Returns:\n        A dictionary containing the updated keyword arguments\n\n    Raises:\n        KeyError: If the parameter name is not found in the keyword arguments\n        AttributeError: If the parameter name is not a valid attribute\n    \"\"\"\n    name = f\"{self.prefix}{self.name or self.param_name}\"\n\n    try:\n        kwargs[self.param_name] = context.resolve(name)\n    except (KeyError, AttributeError):\n        if self.required is False:\n            kwargs[self.param_name] = self.default\n\n    return kwargs\n
","boost":0.5},{"location":"api/faststream/utils/data/filter_by_dict/","title":"filter_by_dict","text":"","boost":0.5},{"location":"api/faststream/utils/data/filter_by_dict/#faststream.utils.data.filter_by_dict","title":"faststream.utils.data.filter_by_dict","text":"
filter_by_dict(\n    typed_dict: Type[TypedDictCls], data: AnyDict\n) -> TypedDictCls\n

Filter a dictionary based on a typed dictionary.

PARAMETER DESCRIPTION typed_dict

The typed dictionary to filter by.

TYPE: Type[TypedDictCls]

data

The dictionary to filter.

TYPE: AnyDict

RETURNS DESCRIPTION TypedDictCls

A new instance of the typed dictionary with only the keys present in the data dictionary.

Source code in faststream/utils/data.py
def filter_by_dict(typed_dict: Type[TypedDictCls], data: AnyDict) -> TypedDictCls:\n    \"\"\"Filter a dictionary based on a typed dictionary.\n\n    Args:\n        typed_dict: The typed dictionary to filter by.\n        data: The dictionary to filter.\n\n    Returns:\n        A new instance of the typed dictionary with only the keys present in the data dictionary.\n    \"\"\"\n    annotations = typed_dict.__annotations__\n    return typed_dict(  # type: ignore\n        {k: v for k, v in data.items() if k in annotations}\n    )\n
","boost":0.5},{"location":"api/faststream/utils/functions/call_or_await/","title":"call_or_await","text":"","boost":0.5},{"location":"api/faststream/utils/functions/call_or_await/#fast_depends.utils.run_async","title":"fast_depends.utils.run_async async","text":"
run_async(\n    func: Union[Callable[P, T], Callable[P, Awaitable[T]]],\n    *args: P.args,\n    **kwargs: P.kwargs\n) -> T\n
Source code in fast_depends/utils.py
async def run_async(\n    func: Union[\n        Callable[P, T],\n        Callable[P, Awaitable[T]],\n    ],\n    *args: P.args,\n    **kwargs: P.kwargs,\n) -> T:\n    if is_coroutine_callable(func):\n        return await cast(Callable[P, Awaitable[T]], func)(*args, **kwargs)\n    else:\n        return await run_in_threadpool(cast(Callable[P, T], func), *args, **kwargs)\n
","boost":0.5},{"location":"api/faststream/utils/functions/drop_response_type/","title":"drop_response_type","text":"","boost":0.5},{"location":"api/faststream/utils/functions/drop_response_type/#faststream.utils.functions.drop_response_type","title":"faststream.utils.functions.drop_response_type","text":"
drop_response_type(\n    model: CallModel[F_Spec, F_Return]\n) -> CallModel[F_Spec, F_Return]\n
Source code in faststream/utils/functions.py
def drop_response_type(\n    model: CallModel[F_Spec, F_Return]\n) -> CallModel[F_Spec, F_Return]:\n    model.response_model = None\n    return model\n
","boost":0.5},{"location":"api/faststream/utils/functions/fake_context/","title":"fake_context","text":"","boost":0.5},{"location":"api/faststream/utils/functions/fake_context/#faststream.utils.functions.fake_context","title":"faststream.utils.functions.fake_context async","text":"
fake_context(\n    *args: Any, **kwargs: Any\n) -> AsyncIterator[None]\n
Source code in faststream/utils/functions.py
@asynccontextmanager\nasync def fake_context(*args: Any, **kwargs: Any) -> AsyncIterator[None]:\n    yield None\n
","boost":0.5},{"location":"api/faststream/utils/functions/get_function_positional_arguments/","title":"get_function_positional_arguments","text":"","boost":0.5},{"location":"api/faststream/utils/functions/get_function_positional_arguments/#faststream.utils.functions.get_function_positional_arguments","title":"faststream.utils.functions.get_function_positional_arguments","text":"
get_function_positional_arguments(\n    func: AnyCallable,\n) -> List[str]\n

Get the positional arguments of a function.

PARAMETER DESCRIPTION func

The function to get the positional arguments from.

TYPE: AnyCallable

RETURNS DESCRIPTION List[str]

A list of strings representing the names of the positional arguments.

Source code in faststream/utils/functions.py
def get_function_positional_arguments(func: AnyCallable) -> List[str]:\n    \"\"\"Get the positional arguments of a function.\n\n    Args:\n        func: The function to get the positional arguments from.\n\n    Returns:\n        A list of strings representing the names of the positional arguments.\n    \"\"\"\n    signature = inspect.signature(func)\n\n    arg_kinds = (\n        inspect.Parameter.POSITIONAL_ONLY,\n        inspect.Parameter.POSITIONAL_OR_KEYWORD,\n    )\n\n    return [\n        param.name for param in signature.parameters.values() if param.kind in arg_kinds\n    ]\n
","boost":0.5},{"location":"api/faststream/utils/functions/timeout_scope/","title":"timeout_scope","text":"","boost":0.5},{"location":"api/faststream/utils/functions/timeout_scope/#faststream.utils.functions.timeout_scope","title":"faststream.utils.functions.timeout_scope","text":"
timeout_scope(\n    timeout: Optional[float] = 30,\n    raise_timeout: bool = False,\n) -> ContextManager[anyio.CancelScope]\n
Source code in faststream/utils/functions.py
def timeout_scope(\n    timeout: Optional[float] = 30,\n    raise_timeout: bool = False,\n) -> ContextManager[anyio.CancelScope]:\n    scope: Callable[[Optional[float]], ContextManager[anyio.CancelScope]]\n    if raise_timeout:\n        scope = anyio.fail_after\n    else:\n        scope = anyio.move_on_after\n\n    return scope(timeout)\n
","boost":0.5},{"location":"api/faststream/utils/functions/to_async/","title":"to_async","text":"","boost":0.5},{"location":"api/faststream/utils/functions/to_async/#faststream.utils.functions.to_async","title":"faststream.utils.functions.to_async","text":"
to_async(\n    func: Union[\n        Callable[F_Spec, F_Return],\n        Callable[F_Spec, Awaitable[F_Return]],\n    ]\n) -> Callable[F_Spec, Awaitable[F_Return]]\n

Converts a synchronous function to an asynchronous function.

PARAMETER DESCRIPTION func

The synchronous function to be converted.

TYPE: Union[Callable[F_Spec, F_Return], Callable[F_Spec, Awaitable[F_Return]]]

RETURNS DESCRIPTION Callable[F_Spec, Awaitable[F_Return]]

The asynchronous version of the input function.

Source code in faststream/utils/functions.py
def to_async(\n    func: Union[\n        Callable[F_Spec, F_Return],\n        Callable[F_Spec, Awaitable[F_Return]],\n    ]\n) -> Callable[F_Spec, Awaitable[F_Return]]:\n    \"\"\"Converts a synchronous function to an asynchronous function.\n\n    Args:\n        func: The synchronous function to be converted.\n\n    Returns:\n        The asynchronous version of the input function.\n    \"\"\"\n\n    @wraps(func)\n    async def to_async_wrapper(*args: F_Spec.args, **kwargs: F_Spec.kwargs) -> F_Return:\n        \"\"\"Wraps a function to make it asynchronous.\n\n        Args:\n            func: The function to be wrapped\n            args: Positional arguments to be passed to the function\n            kwargs: Keyword arguments to be passed to the function\n\n        Returns:\n            The result of the wrapped function\n\n        Raises:\n            Any exceptions raised by the wrapped function\n        \"\"\"\n        return await call_or_await(func, *args, **kwargs)\n\n    return to_async_wrapper\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/","title":"NoCast","text":"","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast","title":"faststream.utils.no_cast.NoCast","text":"
NoCast()\n

Bases: CustomField

A class that represents a custom field without casting.

METHOD DESCRIPTION __init__

Initializes the NoCast object.

use

Returns the provided keyword arguments as a dictionary.

Source code in faststream/utils/no_cast.py
def __init__(self) -> None:\n    super().__init__(cast=False)\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast.cast","title":"cast instance-attribute","text":"
cast: bool = cast\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast.param_name","title":"param_name instance-attribute","text":"
param_name: Optional[str] = None\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast.required","title":"required instance-attribute","text":"
required: bool = required\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast.set_param_name","title":"set_param_name","text":"
set_param_name(name: str) -> Cls\n
Source code in fast_depends/library/model.py
def set_param_name(self: Cls, name: str) -> Cls:\n    self.param_name = name\n    return self\n
","boost":0.5},{"location":"api/faststream/utils/no_cast/NoCast/#faststream.utils.no_cast.NoCast.use","title":"use","text":"
use(**kwargs: Any) -> AnyDict\n

Return a dictionary containing the keyword arguments passed to the function.

PARAMETER DESCRIPTION **kwargs

Keyword arguments

TYPE: Any DEFAULT: {}

RETURNS DESCRIPTION AnyDict

Dictionary containing the keyword arguments

Source code in faststream/utils/no_cast.py
def use(self, **kwargs: Any) -> AnyDict:\n    \"\"\"Return a dictionary containing the keyword arguments passed to the function.\n\n    Args:\n        **kwargs: Keyword arguments\n\n    Returns:\n        Dictionary containing the keyword arguments\n    \"\"\"\n    return kwargs\n
","boost":0.5},{"location":"getting-started/","title":"QUICK START","text":"

Install using pip:

KafkaRabbitMQNATSRedis
pip install \"faststream[kafka]\"\n

Tip

To start a new project, we need a test broker container

docker run -d --rm -p 9092:9092 --name test-mq \\\n-e KAFKA_ENABLE_KRAFT=yes \\\n-e KAFKA_CFG_NODE_ID=1 \\\n-e KAFKA_CFG_PROCESS_ROLES=broker,controller \\\n-e KAFKA_CFG_CONTROLLER_LISTENER_NAMES=CONTROLLER \\\n-e KAFKA_CFG_LISTENERS=PLAINTEXT://:9092,CONTROLLER://:9093 \\\n-e KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP=CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT \\\n-e KAFKA_CFG_ADVERTISED_LISTENERS=PLAINTEXT://127.0.0.1:9092 \\\n-e KAFKA_BROKER_ID=1 \\\n-e KAFKA_CFG_CONTROLLER_QUORUM_VOTERS=1@kafka:9093 \\\n-e ALLOW_PLAINTEXT_LISTENER=yes \\\nbitnami/kafka:3.5.0\n

pip install \"faststream[rabbit]\"\n

Tip

To start a new project, we need a test broker container

docker run -d --rm -p 5672:5672 --name test-mq rabbitmq:alpine\n

pip install \"faststream[nats]\"\n

Tip

To start a new project, we need a test broker container

bash docker run -d --rm -p 4222:4222 --name test-mq nats -js\n

pip install \"faststream[redis]\"\n

Tip

To start a new project, we need a test broker container

bash docker run -d --rm -p 6379:6379 --name test-mq redis\n

","boost":10},{"location":"getting-started/#basic-usage","title":"Basic Usage","text":"

To create a basic application, add the following code to a new file (e.g. serve.py):

KafkaRabbitMQNATSRedis serve.py
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n
serve.py
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\n\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n
serve.py
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\n\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n
serve.py
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\n\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n

And just run this command:

faststream run serve:app\n

After running the command, you should see the following output:

Enjoy your new development experience!

Don't forget to stop the test broker container
docker container stop test-mq\n
","boost":10},{"location":"getting-started/logging/","title":"Application and Access Logging","text":"

FastStream uses two already configured loggers:

","boost":10},{"location":"getting-started/logging/#logging-requests","title":"Logging Requests","text":"

To log requests, it is strongly recommended to use the access_logger of your broker, as it is available from the Context of your application.

from faststream import Logger\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker()\n\n@broker.subscriber(\"test\")\nasync def func(logger: Logger):\n    logger.info(\"message received\")\n

This approach offers several advantages:

","boost":10},{"location":"getting-started/logging/#logging-levels","title":"Logging Levels","text":"

If you use the FastStream CLI, you can change the current logging level of the entire application directly from the command line.

The --log-level flag sets the current logging level for both the broker and the FastStream app. This allows you to configure the levels of not only the default loggers but also your custom loggers, if you use them inside FastStream.

faststream run serve:app --log-level debug\n

If you want to completely disable the default logging of FastStream, you can set logger=None

from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(logger=None)     # Disables broker logs\napp = FastStream(broker, logger=None)  # Disables application logs\n

Warning

Be careful: the logger that you get from the context will also have the value None if you turn off broker logging.

If you don't want to lose access to the `logger' inside your context but want to disable the default logs of FastStream, you can lower the level of logs that the broker publishes itself.

import logging\nfrom faststream.rabbit import RabbitBroker\n\n# Sets the broker logs to the DEBUG level\nbroker = RabbitBroker(log_level=logging.DEBUG)\n
","boost":10},{"location":"getting-started/logging/#formatting-logs","title":"Formatting Logs","text":"

If you are not satisfied with the current format of your application logs, you can change it directly in your broker's constructor.

from faststream.rabbit import RabbitBroker\nbroker = RabbitBroker(log_fmt=\"%(asctime)s %(levelname)s - %(message)s\")\n
","boost":10},{"location":"getting-started/logging/#logger-access","title":"Logger Access","text":"

If you want to override default logger's behavior, you can access them directly via logging.

import logging\nlogger = logging.getLogger(\"faststream\")\naccess_logger = logging.getLogger(\"faststream.access\")\n

Or you can import them from FastStream.

from faststream.log import access_logger, logger\n
","boost":10},{"location":"getting-started/logging/#using-your-own-loggers","title":"Using Your Own Loggers","text":"

Since FastStream works with the standard logging.Logger object, you can initiate an application and a broker using your own logger.

import logging\nfrom faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nlogger = logging.getLogger(\"my_logger\")\n\nbroker = RabbitBroker(logger=logger)\napp = FastStream(broker, logger=logger)\n

Note

Doing this, you doesn't change the CLI logs behavior (multiprocessing and hot reload logs). This was done to keep your log storage clear of unnecessary stuff.

This logger will be used only for FastStream and StreamBroker service messages and will be passed to your function through the Context.

By doing this, you will lose information about the context of the current request. However, you can retrieve it directly from the context anywhere in your code.

from faststream import context\nlog_context: dict[str, str] = context.get_local(\"log_context\")\n

This way, all broker handlers can get access to your broker logger right from the context:

from faststream import Logger\n\n@broker.subscriber(...)\nasync def handler(\n    msg,\n    logger: Logger,  # <-- YOUR logger here\n):\n    logger.info(msg)\n
","boost":10},{"location":"getting-started/logging/#structlog-example","title":"Structlog Example","text":"

Structlog is a production-ready logging solution for Python. It can be easely integrated with any log storage system, making it suitable for use in production projects.

Here is a quick tutorial on integrating Structlog with FastStream:

Start with the Structlog guide example:

import sys\nimport structlog\n\nshared_processors = [\n    structlog.processors.add_log_level,\n    structlog.processors.StackInfoRenderer(),\n    structlog.dev.set_exc_info,\n    structlog.processors.TimeStamper(fmt=\"iso\"),\n]\n\nif sys.stderr.isatty():\n    # terminal session\n    processors = shared_processors + [\n        structlog.dev.ConsoleRenderer()\n    ]\nelse:\n    # Docker container session\n    processors = shared_processors + [\n        structlog.processors.dict_tracebacks,\n        structlog.processors.JSONRenderer(),\n    ]\n\nstructlog.configure(\n    processors=processors,\n    logger_factory=structlog.PrintLoggerFactory(),\n    cache_logger_on_first_use=False,\n)\n\nlogger = structlog.get_logger()\n

We created a logger that prints messages to the console in a user-friendly format during development and uses JSON-formatted logs in production.

To integrate this logger with our FastStream application, we just need to access it through context information and pass it to our objects:

import logging\n\nimport structlog\n\nfrom faststream import FastStream, context\nfrom faststream.kafka import KafkaBroker\n\ndef merge_contextvars(\n    logger: structlog.types.WrappedLogger,\n    method_name: str,\n    event_dict: structlog.types.EventDict,\n) -> structlog.types.EventDict:\n    event_dict[\"extra\"] = event_dict.get(\n        \"extra\",\n        context.get(\"log_context\", {}),\n    )\n    return event_dict\n\nshared_processors = [\n    merge_contextvars,\n    ...\n]\n\n...\n\nbroker = KafkaBroker(logger=logger, log_level=logging.DEBUG)\napp = FastStream(broker, logger=logger)\n

And the job is done! Now you have a perfectly structured logs using Structlog.

","boost":10},{"location":"getting-started/asyncapi/custom/","title":"Customizing AsyncAPI Documentation for FastStream","text":"

In this guide, we will explore how to customize AsyncAPI documentation for your FastStream application. Whether you want to add custom app info, broker information, handlers, or fine-tune payload details, we'll walk you through each step.

","boost":10},{"location":"getting-started/asyncapi/custom/#prerequisites","title":"Prerequisites","text":"

Before we dive into customization, ensure you have a basic FastStream application up and running. If you haven't done that yet, let's setup a simple appication right now.

Copy the following code in your basic.py file:

from faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaMessage\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n@broker.publisher(\"output_data\")\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg):\n    # your processing logic\n    pass\n

Now, when you run

faststream docs serve basic:app\n
you should see the following documentation:

","boost":10},{"location":"getting-started/asyncapi/custom/#setup-custom-faststream-app-info","title":"Setup Custom FastStream App Info","text":"

Let's start by customizing the app information that appears in your AsyncAPI documentation. This is a great way to give your documentation a personal touch. Here's how:

  1. Locate the app configuration in your FastStream application.
  2. Update the title, version, and description fields to reflect your application's details.
  3. Save the changes.
  4. Serve your FastStream app documentation.

Copy the following code in your basic.py file, we have highligted the additional info passed to FastStream app:

from faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaMessage\nfrom faststream.asyncapi.schema import Contact, ExternalDocs, License, Tag\n\nbroker = KafkaBroker(\"localhost:9092\")\ndescription=\"\"\"# Title of the description\nThis description supports **Markdown** syntax\"\"\"\napp = FastStream(\n    broker,\n    title=\"My App\",\n    version=\"1.0.0\",\n    description=description,\n    license=License(name=\"MIT\", url=\"https://opensource.org/license/mit/\"),\n    terms_of_service=\"https://my-terms.com/\",\n    contact=Contact(name=\"support\", url=\"https://help.com/\"),\n)\n\n@broker.publisher(\"output_data\")\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg):\n    # your processing logic\n    pass\n

Now, when you run

faststream docs serve basic:app\n
you should see the following in your general app documentation:

Now, your documentation reflects your application's identity and purpose.

Note

The description field in the above example supports Markdown text.

","boost":10},{"location":"getting-started/asyncapi/custom/#setup-custom-broker-information","title":"Setup Custom Broker Information","text":"

The next step is to customize broker information. This helps users understand the messaging system your application uses. Follow these steps:

  1. Locate the broker configuration in your FastStream application.
  2. Update the description field.
  3. Update the asyncapi_url field with a non-sensitive URL if you want to conceal your broker's actual bootstrap server URL.
  4. Save the changes.
  5. Serve your FastStream app.

Copy the following code in your basic.py file, we have highligted the additional info passed to the FastStream app broker:

from faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaMessage\nfrom faststream.asyncapi.schema import Tag\n\nbroker = KafkaBroker(\n    \"localhost:9092\",\n    description=\"Kafka broker running locally\",\n    asyncapi_url=\"non-sensitive-url:9092\",\n)\napp = FastStream(broker)\n\n\n@broker.publisher(\"output_data\")\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg):\n    # your processing logic\n    pass\n

Now, when you run

faststream docs serve basic:app\n
you should see the description in your broker documentation:

Your AsyncAPI documentation now provides clear insights into the messaging infrastructure you're using.

","boost":10},{"location":"getting-started/asyncapi/custom/#setup-custom-handler-information","title":"Setup Custom Handler Information","text":"

Customizing handler information helps users comprehend the purpose and behavior of each message handler. Here's how to do it:

  1. Navigate to your handler definitions in your FastStream application.
  2. Add descriptions to each handler using description field.
  3. For subscriber, consumer function's docstring can be used as description.
  4. Add titles to each handler using title field adhering to URI format.
  5. Add publishing schema to publisher handler using schema field.
  6. Save the changes.
  7. Serve your FastStream app.

Copy the following code in your basic.py file, we have highligted the additional info passed to the FastStream app handlers:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaMessage\n\n\nclass DataBasic(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.publisher(\n    \"output_data\",\n    description=\"My publisher description\",\n    title=\"output_data:Produce\",\n    schema=DataBasic,\n)\n@broker.subscriber(\n    \"input_data\", title=\"input_data:Consume\"\n)\nasync def on_input_data(msg):\n    \"\"\"Consumer function\n\n    Args:\n        msg: input msg\n    \"\"\"\n    # your processing logic\n    pass\n

Now, when you run

faststream docs serve basic:app\n
you should see the descriptions in your handlers:

Now, your documentation is enriched with meaningful details about each message handler.

","boost":10},{"location":"getting-started/asyncapi/custom/#setup-payload-information-via-pydantic-model","title":"Setup Payload Information via Pydantic Model","text":"

To describe your message payload effectively, you can use Pydantic models. Here's how:

  1. Define Pydantic models for your message payloads.
  2. Annotate these models with descriptions and examples.
  3. Use these models as argument types or return types in your handlers.
  4. Save the changes.
  5. Serve your FastStream app.

Copy the following code in your basic.py file, we have highligted the creation of payload info and you can see it being passed to the return type and the msg argument type in the on_input_data function:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\n\nclass DataBasic(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.publisher(\"output_data\")\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: DataBasic) -> DataBasic:\n    # your processing logic\n    pass\n

Now, when you run

faststream docs serve basic:app\n
you should see the payload schema described in your documentation:

Your AsyncAPI documentation now showcases well-structured payload information.

","boost":10},{"location":"getting-started/asyncapi/custom/#generate-schemajson-customize-and-serve-it","title":"Generate Schema.json, customize and serve it","text":"

To take customization to the next level, you can manually modify the schema.json file. Follow these steps:

  1. Generate the initial schema.json by running
    faststream docs gen basic:app\n
  2. Manually edit the asyncapi.json file to add custom fields, descriptions, and details.
  3. Save your changes.
  4. Serve your FastStream app with the updated asyncapi.json by running
    faststream docs serve asyncapi.json\n

Now, you have fine-tuned control over your AsyncAPI documentation.

","boost":10},{"location":"getting-started/asyncapi/custom/#conclusion","title":"Conclusion","text":"

Customizing AsyncAPI documentation for your FastStream application not only enhances its appearance but also provides valuable insights to users. With these steps, you can create documentation that's not only informative but also uniquely yours.

Happy coding with your customized FastStream AsyncAPI documentation!

","boost":10},{"location":"getting-started/asyncapi/export/","title":"How to Generate and Serve AsyncAPI Documentation","text":"

In this guide, let's explore how to generate and serve AsyncAPI documentation for our FastStream application.

","boost":10},{"location":"getting-started/asyncapi/export/#writing-the-faststream-application","title":"Writing the FastStream Application","text":"

Here's an example Python application using FastStream that consumes data from a topic, increments the value, and outputs the data to another topic. Save it in a file called basic.py.

basic.py
from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n\n\nclass DataBasic(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.publisher(\"output_data\")\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: DataBasic, logger: Logger) -> DataBasic:\n    logger.info(msg)\n    return DataBasic(data=msg.data + 1.0)\n
","boost":10},{"location":"getting-started/asyncapi/export/#generating-the-asyncapi-specification","title":"Generating the AsyncAPI Specification","text":"

Now that we have a FastStream application, we can proceed with generating the AsyncAPI specification using a CLI command.

faststream docs gen basic:app\n

The above command will generate the AsyncAPI specification and save it in a file called asyncapi.json.

If you prefer yaml instead of json, please run the following command to generate asyncapi.yaml.

faststream docs gen --yaml basic:app\n

Tip

To generate the documentation in yaml format, please install the necessary dependency to work with YAML file format at first.

pip install PyYAML\n
","boost":10},{"location":"getting-started/asyncapi/hosting/","title":"Serving the AsyncAPI Documentation","text":"

FastStream provides a command to serve the AsyncAPI documentation.

Note

This feature requires an Internet connection to obtain the AsyncAPI HTML via CDN.

faststream docs serve basic:app\n

In the above command, we are providing the path in the format of python_module:FastStream. Alternatively, you can also specify asyncapi.json or asyncapi.yaml to serve the AsyncAPI documentation.

JSONYAML
faststream docs serve asyncapi.json\n
faststream docs serve asyncapi.yaml\n

After running the command, it should serve the AsyncAPI documentation on port 8000 and display the following logs in the terminal.

And you should be able to see the following page in your browser:

ShortExpand

Tip

The command also offers options to serve the documentation on a different host and port.

","boost":10},{"location":"getting-started/asyncapi/hosting/#customizing-asyncapi-documentation","title":"Customizing AsyncAPI Documentation","text":"

FastStream also provides query parameters to show and hide specific sections of AsyncAPI documentation.

You can use the following parameters control the visibility of relevant sections:

  1. sidebar: Whether to include the sidebar. Default is true.
  2. info: Whether to include the info section. Default is true.
  3. servers: Whether to include the servers section. Default is true.
  4. operations: Whether to include the operations section. Default is true.
  5. messages: Whether to include the messages section. Default is true.
  6. schemas: Whether to include the schemas section. Default is true.
  7. errors: Whether to include the errors section. Default is true.
  8. expandMessageExamples: Whether to expand message examples. Default is true.

For example, to hide the entire Servers section of the documentation, simply add servers=false as a query parameter, i.e., http://localhost:8000?servers=false. The resulting page would look like the image below:

Please use the above-listed query parameters to show and hide sections of the AsyncAPI documentation.

","boost":10},{"location":"getting-started/cli/","title":"CLI","text":"

FastStream has its own built-in CLI tool for your maximum comfort as a developer.

Thanks to typer and watchfiles. Their work is the basis of this tool.

faststream --help\n
","boost":10},{"location":"getting-started/cli/#running-the-project","title":"Running the Project","text":"","boost":10},{"location":"getting-started/cli/#multiprocessing-scaling","title":"Multiprocessing Scaling","text":"

FastStream allows you to scale application right from the command line by running you application in the Process pool.

Just set the --worker option to scale your application:

faststream run serve:app --workers 2\n
","boost":10},{"location":"getting-started/cli/#hot-reload","title":"Hot Reload","text":"

Thanks to watchfiles, written in Rust, you can work with your project easily. Edit the code as much as you like - the new version has already been launched and is waiting for your requests!

faststream run serve:app --reload\n

Tip

Please, install watchfiles if you want to use --reload feature

pip install watchfiles\n

By default FastStream watches for .py file changes, but you can specify an extra file extensions to watch by (your config files as an example)

faststream run serve:app --reload  --reload-ext .yml --realod-ext .yaml\n
","boost":10},{"location":"getting-started/cli/#environment-management","title":"Environment Management","text":"

You can pass any custom flags and launch options to the FastStream CLI even without first registering them. Just use them when launching the application - and they will be right in your environment.

Use this option to select environment files, configure logging, or at your discretion.

For example, we will pass the .env file to the context of our application:

faststream run serve:app --env=.env.dev\n
KafkaRabbitMQNATSRedis
from faststream import FastStream, ContextRepo\nfrom faststream.kafka import KafkaBroker\nfrom pydantic_settings import BaseSettings\n\nbroker = KafkaBroker()\n\napp = FastStream(broker)\n\nclass Settings(BaseSettings):\n    host: str = \"localhost:9092\"\n\n@app.on_startup\nasync def setup(env: str, context: ContextRepo):\n    settings = Settings(_env_file=env)\n    await broker.connect(settings.host)\n    context.set_global(\"settings\", settings)\n
from faststream import FastStream, ContextRepo\nfrom faststream.rabbit import RabbitBroker\nfrom pydantic_settings import BaseSettings\n\nbroker = RabbitBroker()\n\napp = FastStream(broker)\n\nclass Settings(BaseSettings):\n    host: str = \"amqp://guest:guest@localhost:5672/\" \n\n@app.on_startup\nasync def setup(env: str, context: ContextRepo):\n    settings = Settings(_env_file=env)\n    await broker.connect(settings.host)\n    context.set_global(\"settings\", settings)\n
from faststream import FastStream, ContextRepo\nfrom faststream.nats import NatsBroker\nfrom pydantic_settings import BaseSettings\n\nbroker = NatsBroker()\n\napp = FastStream(broker)\n\nclass Settings(BaseSettings):\n    host: str = \"nats://localhost:4222\"\n\n@app.on_startup\nasync def setup(env: str, context: ContextRepo):\n    settings = Settings(_env_file=env)\n    await broker.connect(settings.host)\n    context.set_global(\"settings\", settings)\n
from faststream import FastStream, ContextRepo\nfrom faststream.redis import RedisBroker\nfrom pydantic_settings import BaseSettings\n\nbroker = RedisBroker()\n\napp = FastStream(broker)\n\nclass Settings(BaseSettings):\n    host: str = \"redis://localhost:6379\"\n\n@app.on_startup\nasync def setup(env: str, context: ContextRepo):\n    settings = Settings(_env_file=env)\n    await broker.connect(settings.host)\n    context.set_global(\"settings\", settings)\n

Note

Note that the env parameter was passed to the setup function directly from the command line

All passed values can be of type bool, str or list[str].

In this case, the flags will be interpreted as follows:

You can use them both individually and together in unlimited quantities.

","boost":10},{"location":"getting-started/cli/#asyncapi-schema","title":"AsyncAPI Schema","text":"

Also, the FastStream CLI allows you to work with the AsyncAPI schema in a simple way.

You are able to generate .json or .yaml files by your application code or host HTML representation directly:

faststream docs --help\n

To learn more about the commands above, please visit AsyncAPI export and AsyncAPI hosting.

","boost":10},{"location":"getting-started/config/","title":"Settings and Environment Variables","text":"

In many cases, your application may require external settings or configurations, such as a broker connection or database credentials.

To manage these settings effectively, it's common to provide them through environment variables that can be read by the application.

","boost":10},{"location":"getting-started/config/#pydantic-settings","title":"Pydantic Settings","text":"

Fortunately, Pydantic provides a useful utility for handling settings coming from environment variables with Pydantic: Settings management.

","boost":10},{"location":"getting-started/config/#install-pydantic-settings","title":"Install pydantic-settings","text":"

First, install the pydantic-settings package:

pip install pydantic-settings\n

Info

In Pydantic v1, this functionality was included with the main package. Now it is distributed as an independent package so that you can choose not to install it if you don't need that functionality.

","boost":10},{"location":"getting-started/config/#create-the-settings-object","title":"Create the Settings Object","text":"

Import BaseSettings from Pydantic and create a subclass, similar to what you would do with a Pydantic model.

Just like with Pydantic models, you declare class attributes with type annotations and can use all the same validation features and tools, including different data types and additional validations with Field().

Pydantic v2Pydantic v1 config.py
from pydantic_settings import BaseSettings\n\n\nclass Settings(BaseSettings):\n    url: str = \"\"\n    queue: str = \"test-queue\"\n\n\nsettings = Settings()\n

Info

In Pydantic v1 you would import BaseSettings directly from pydantic instead of from pydantic_settings.

config.py
from pydantic import BaseSettings\n\n\nclass Settings(BaseSettings):\n    url: str = \"\"\n    queue: str = \"test-queue\"\n\n\nsettings = Settings()\n

When you create an instance of that Settings class (in this case, in the settings object), Pydantic will read the environment variables in a case-insensitive way. For example, an upper-case variable APP_NAME will still be read for the attribute app_name.

It will also convert and validate the data, so when you use that settings object, you will have data of the type you declared (e.g. items_per_user will be an int).

","boost":10},{"location":"getting-started/config/#using-the-settings","title":"Using the settings","text":"

Now you can use the new settings object in your application:

serve.py
import os\n\nfrom pydantic_settings import BaseSettings\n\nfrom faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\n\nclass Settings(BaseSettings):\n    url: str\n    queue: str = \"test-queue\"\n\n\nsettings = Settings(_env_file=os.getenv(\"ENV\", \".env\"))\n\nbroker = RabbitBroker(settings.url)\napp = FastStream(broker)\n\n\n@broker.subscriber(settings.queue)\nasync def handler(msg):\n    ...\n
","boost":10},{"location":"getting-started/config/#running-the-application","title":"Running the Application","text":"

You can run the application while passing the configuration parameters as environment variables. For example, you could set an URL:

URL=\"amqp://guest:guest@localhost:5672\" faststream run serve:app\n

Tip

To set multiple environment variables for a single command, separate them with spaces and put them all before the command.

","boost":10},{"location":"getting-started/config/#reading-a-env-file","title":"Reading a .env File","text":"

If you have many settings that may change frequently, especially in different environments, it might be useful to store them in a file and then read them as if they were environment variables.

This practice is common enough that it has a name; these environment variables are typically placed in a file named .env, commonly referred to as a \"dotenv\" file.

Tip

In Unix-like systems like Linux and macOS, a file starting with a dot (.) is considered a hidden file.

But a dotenv file doesn't really have to have that exact filename.

Pydantic supports reading from these types of files using an external library. You can learn more at Pydantic Settings: Dotenv (.env) support.

Tip

To use this feature, you need to install the python-dotenv library.

","boost":10},{"location":"getting-started/config/#the-env-file","title":"The .env File","text":"

You can create a .env file with contents like this:

URL=\"amqp://guest:guest@localhost:5672\"\nQUEUE=\"test-queue\"\n
","boost":10},{"location":"getting-started/config/#reading-settings-from-env","title":"Reading Settings from .env","text":"

Then update your config.py as follows:

import os\n\nfrom pydantic_settings import BaseSettings\n\n\nclass Settings(BaseSettings):\n    url: str\n    queue: str = \"test-queue\"\n\n\nsettings = Settings(_env_file=os.getenv(\"ENV\", \".env\"))\n

This way, you can specify different .env files directly from your terminal, which can be extremely helpful for various testing and production scenarios.

Note

By default, Pydantic will attempt to find a .env file. If it's not present, Pydantic will use the default field values.

","boost":10},{"location":"getting-started/config/#choosing-the-env-file-at-startup","title":"Choosing the .env File at Startup","text":"

Now you can run the apllication with different .env files like so:

ENV=.local.env faststream run serve:app\n

Or, for a production environment:

ENV=.production.env faststream run serve:app\n

Or even for a test environment:

ENV=.test.env pytest\n
","boost":10},{"location":"getting-started/context/","title":"Application Context","text":"

FastStreams has its own Dependency Injection container - Context, used to store application runtime objects and variables.

With this container, you can access both application scope and message processing scope objects. This functionality is similar to Depends usage.

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message=Context(),  # get access to raw message\n):\n    ...\n
from faststream import Context, FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message=Context(),  # get access to raw message\n):\n    ...\n
from faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message=Context(),  # get access to raw message\n):\n    ...\n
from faststream import Context, FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message=Context(),  # get access to raw message\n):\n    ...\n

But, with the Annotated Python feature usage, it is much closer to @pytest.fixture.

KafkaRabbitMQNATSRedis
from typing import Annotated\n\nfrom faststream import Context, FastStream\nfrom faststream.kafka import KafkaBroker\nfrom faststream.kafka.message import KafkaMessage\n\nMessage = Annotated[KafkaMessage, Context()]\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message: Message,  # get access to raw message\n):\n    ...\n
from typing import Annotated\n\nfrom faststream import Context, FastStream\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.rabbit.message import RabbitMessage\n\nMessage = Annotated[RabbitMessage, Context()]\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message: Message,  # get access to raw message\n):\n    ...\n
from typing import Annotated\n\nfrom faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.message import NatsMessage\n\nMessage = Annotated[NatsMessage, Context()]\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message: Message,  # get access to raw message\n):\n    ...\n
from typing import Annotated\n\nfrom faststream import Context, FastStream\nfrom faststream.redis import RedisBroker\nfrom faststream.redis.message import RedisMessage\n\nMessage = Annotated[RedisMessage, Context()]\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    message: Message,  # get access to raw message\n):\n    ...\n
","boost":10},{"location":"getting-started/context/#usages","title":"Usages","text":"

By default, the context is available in the same place as Depends:

Tip

Fields obtained from the Context are editable, so editing them in a function means editing them everywhere.

","boost":10},{"location":"getting-started/context/#compatibility-with-regular-functions","title":"Compatibility with Regular Functions","text":"

To use context in other functions, use the @apply_types decorator. In this case, the context of the called function will correspond to the context of the event handler from which it was called.

from faststream import Context, apply_types\n\n@broker.subscriber(\"test\")\nasync def handler(body):\n    nested_func(body)\n\n@apply_types\ndef nested_func(body, logger=Context()):\n    logger.info(body)\n

In the example above, we did not pass the logger function at calling it; it was placed from context.

","boost":10},{"location":"getting-started/context/custom/","title":"Context Fields Declaration","text":"

You can also store your own objects in the Context.

","boost":10},{"location":"getting-started/context/custom/#global","title":"Global","text":"

To declare an application-level context field, you need to call the context.set_global method with with a key to indicate where the object will be placed in the context.

KafkaRabbitMQNATSRedis
from faststream import FastStream, ContextRepo, Context\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n@app.on_startup\nasync def set_global(context: ContextRepo):\n    context.set_global(\"secret_str\", \"my-perfect-secret\")\n
from faststream import FastStream, ContextRepo, Context\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n@app.on_startup\nasync def set_global(context: ContextRepo):\n    context.set_global(\"secret_str\", \"my-perfect-secret\")\n
from faststream import FastStream, ContextRepo, Context\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n@app.on_startup\nasync def set_global(context: ContextRepo):\n    context.set_global(\"secret_str\", \"my-perfect-secret\")\n
from faststream import FastStream, ContextRepo, Context\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n@app.on_startup\nasync def set_global(context: ContextRepo):\n    context.set_global(\"secret_str\", \"my-perfect-secret\")\n

Afterward, you can access your secret field in the usual way:

KafkaRabbitMQNATSRedis
@broker.subscriber(\"test-topic\")\nasync def handle(\n    msg: str,\n    secret_str: str=Context(),\n):\n    assert secret_str == \"my-perfect-secret\"\n
@broker.subscriber(\"test-queue\")\nasync def handle(\n    msg: str,\n    secret_str: str=Context(),\n):\n    assert secret_str == \"my-perfect-secret\"\n
@broker.subscriber(\"test-subject\")\nasync def handle(\n    msg: str,\n    secret_str: str=Context(),\n):\n    assert secret_str == \"my-perfect-secret\"\n
@broker.subscriber(\"test-channel\")\nasync def handle(\n    msg: str,\n    secret_str: str=Context(),\n):\n    assert secret_str == \"my-perfect-secret\"\n

In this case, the field becomes a global context field: it does not depend on the current message handler (unlike message)

To remove a field from the context use the reset_global method:

context.reset_global(\"my_key\")\n
","boost":10},{"location":"getting-started/context/custom/#local","title":"Local","text":"

To set a local context (available only within the message processing scope), use the context manager scope

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream, apply_types\nfrom faststream.kafka import KafkaBroker\nfrom faststream.kafka.annotations import ContextRepo, KafkaMessage\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    msg: str,\n    message: KafkaMessage,\n    context: ContextRepo,\n):\n    with context.scope(\"correlation_id\", message.correlation_id):\n        call()\n\n\n@apply_types\ndef call(\n    message: KafkaMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n
from faststream import Context, FastStream, apply_types\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.rabbit.annotations import ContextRepo, RabbitMessage\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    msg: str,\n    message: RabbitMessage,\n    context: ContextRepo,\n):\n    with context.scope(\"correlation_id\", message.correlation_id):\n        call()\n\n\n@apply_types\ndef call(\n    message: RabbitMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n
from faststream import Context, FastStream, apply_types\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import ContextRepo, NatsMessage\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    msg: str,\n    message: NatsMessage,\n    context: ContextRepo,\n):\n    with context.scope(\"correlation_id\", message.correlation_id):\n        call()\n\n\n@apply_types\ndef call(\n    message: NatsMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n
from faststream import Context, FastStream, apply_types\nfrom faststream.redis import RedisBroker\nfrom faststream.redis.annotations import ContextRepo, RedisMessage\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    msg: str,\n    message: RedisMessage,\n    context: ContextRepo,\n):\n    with context.scope(\"correlation_id\", message.correlation_id):\n        call()\n\n\n@apply_types\ndef call(\n    message: RedisMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n

You can also set the context by yourself, and it will remain within the current call stack until you clear it.

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream, apply_types, context\nfrom faststream.kafka import KafkaBroker\nfrom faststream.kafka.annotations import KafkaMessage\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    msg: str,\n    message: KafkaMessage,\n):\n    tag = context.set_local(\"correlation_id\", message.correlation_id)\n    call(tag)\n\n\n@apply_types\ndef call(\n    tag,\n    message: KafkaMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n    context.reset_local(\"correlation_id\", tag)\n
from faststream import Context, FastStream, apply_types, context\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.rabbit.annotations import RabbitMessage\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    msg: str,\n    message: RabbitMessage,\n):\n    tag = context.set_local(\"correlation_id\", message.correlation_id)\n    call(tag)\n\n\n@apply_types\ndef call(\n    tag,\n    message: RabbitMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n    context.reset_local(\"correlation_id\", tag)\n
from faststream import Context, FastStream, apply_types, context\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import NatsMessage\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    msg: str,\n    message: NatsMessage,\n):\n    tag = context.set_local(\"correlation_id\", message.correlation_id)\n    call(tag)\n\n\n@apply_types\ndef call(\n    tag,\n    message: NatsMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n    context.reset_local(\"correlation_id\", tag)\n
from faststream import Context, FastStream, apply_types, context\nfrom faststream.redis import RedisBroker\nfrom faststream.redis.annotations import RedisMessage\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    msg: str,\n    message: RedisMessage,\n):\n    tag = context.set_local(\"correlation_id\", message.correlation_id)\n    call(tag)\n\n\n@apply_types\ndef call(\n    tag,\n    message: RedisMessage,\n    correlation_id=Context(),\n):\n    assert correlation_id == message.correlation_id\n    context.reset_local(\"correlation_id\", tag)\n
","boost":10},{"location":"getting-started/context/existed/","title":"Existing Fields","text":"

Context already contains some global objects that you can always access:

At the same time, thanks to contextlib.ContextVar, message is local for you current consumer scope.

","boost":10},{"location":"getting-started/context/existed/#access-to-context-fields","title":"Access to Context Fields","text":"

By default, the context searches for an object based on the argument name.

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker_object = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"test-topic\")\nasync def handle(\n    msg: str,\n    logger=Context(),\n    message=Context(),\n    broker=Context(),\n    context=Context(),\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream import Context, FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker_object = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"test-queue\")\nasync def handle(\n    msg: str,\n    logger=Context(),\n    message=Context(),\n    broker=Context(),\n    context=Context(),\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\n\nbroker_object = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"test-subject\")\nasync def handle(\n    msg: str,\n    logger=Context(),\n    message=Context(),\n    broker=Context(),\n    context=Context(),\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream import Context, FastStream\nfrom faststream.redis import RedisBroker\n\nbroker_object = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"test-channel\")\nasync def handle(\n    msg: str,\n    logger=Context(),\n    message=Context(),\n    broker=Context(),\n    context=Context(),\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
","boost":10},{"location":"getting-started/context/existed/#annotated-aliases","title":"Annotated Aliases","text":"

Also, FastStream has already created Annotated aliases to provide you with comfortable access to existing objects. You can import them directly from faststream or your broker-specific modules:

from faststream import Logger, ContextRepo\n
KafkaRabbitMQNATSRedis
from faststream.kafka.annotations import (\n    Logger, ContextRepo, KafkaMessage,\n    KafkaBroker, KafkaProducer, NoCast,\n)\n

faststream.kafka.KafkaMessage is an alias to faststream.kafka.annotations.KafkaMessage

from faststream.kafka import KafkaMessage\n

To use them, simply import and use them as subscriber argument annotations.

from faststream import Context, FastStream\nfrom faststream.kafka import KafkaBroker\nfrom faststream.kafka.annotations import (\n    ContextRepo,\n    KafkaMessage,\n    Logger,\n    KafkaBroker as BrokerAnnotation,\n)\n\nbroker_object = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"response-topic\")\nasync def handle_response(\n    msg: str,\n    logger: Logger,\n    message: KafkaMessage,\n    context: ContextRepo,\n    broker: BrokerAnnotation,\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream.rabbit.annotations import (\n    Logger, ContextRepo, RabbitMessage,\n    RabbitBroker, RabbitProducer, NoCast,\n)\n

faststream.rabbit.RabbitMessage is an alias to faststream.rabbit.annotations.RabbitMessage

from faststream.rabbit import RabbitMessage\n

To use them, simply import and use them as subscriber argument annotations.

from faststream import Context, FastStream\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.rabbit.annotations import (\n    ContextRepo,\n    RabbitMessage,\n    Logger,\n    RabbitBroker as BrokerAnnotation,\n)\n\nbroker_object = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"response-queue\")\nasync def handle_response(\n    msg: str,\n    logger: Logger,\n    message: RabbitMessage,\n    context: ContextRepo,\n    broker: BrokerAnnotation,\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream.nats.annotations import (\n    Logger, ContextRepo, NatsMessage,\n    NatsBroker, NatsProducer, NatsJsProducer,\n    Client, JsClient, NoCast,\n)\n

faststream.nats.NatsMessage is an alias to faststream.nats.annotations.NatsMessage

from faststream.nats import NatsMessage\n

To use them, simply import and use them as subscriber argument annotations.

from faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import (\n    ContextRepo,\n    NatsMessage,\n    Logger,\n    NatsBroker as BrokerAnnotation,\n)\n\nbroker_object = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"response-subject\")\nasync def handle_response(\n    msg: str,\n    logger: Logger,\n    message: NatsMessage,\n    context: ContextRepo,\n    broker: BrokerAnnotation,\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
from faststream.redis.annotations import (\n    Logger, ContextRepo, RedisMessage,\n    RedisBroker, Redis, NoCast,\n)\n

faststream.redis.RedisMessage is an alias to faststream.redis.annotations.RedisMessage

from faststream.redis import RedisMessage\n

To use them, simply import and use them as subscriber argument annotations.

from faststream import Context, FastStream\nfrom faststream.redis import RedisBroker\nfrom faststream.redis.annotations import (\n    ContextRepo,\n    RedisMessage,\n    Logger,\n    RedisBroker as BrokerAnnotation,\n)\n\nbroker_object = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker_object)\n\n@broker_object.subscriber(\"response-channel\")\nasync def handle_response(\n    msg: str,\n    logger: Logger,\n    message: RedisMessage,\n    context: ContextRepo,\n    broker: BrokerAnnotation,\n):\n    logger.info(message)\n    await broker.publish(\"test\", \"response\")\n
","boost":10},{"location":"getting-started/context/extra/","title":"Context Extra Options","text":"

Additionally, Context provides you with some extra capabilities for working with containing objects.

","boost":10},{"location":"getting-started/context/extra/#default-values","title":"Default Values","text":"

For instance, if you attempt to access a field that doesn't exist in the global context, you will receive a pydantic.ValidationError exception.

However, you can set default values if needed.

KafkaRabbitMQNATSRedis
@broker.subscriber(\"test-topic\")\nasync def handle(\n    not_existed: None = Context(\"not_existed\", default=None),\n):\n    assert not_existed is None\n
@broker.subscriber(\"test-queue\")\nasync def handle(\n    not_existed: None = Context(\"not_existed\", default=None),\n):\n    assert not_existed is None\n
@broker.subscriber(\"test-subject\")\nasync def handle(\n    not_existed: None = Context(\"not_existed\", default=None),\n):\n    assert not_existed is None\n
@broker.subscriber(\"test-channel\")\nasync def handle(\n    not_existed: None = Context(\"not_existed\", default=None),\n):\n    assert not_existed is None\n
","boost":10},{"location":"getting-started/context/extra/#cast-context-types","title":"Cast Context Types","text":"

By default, context fields are NOT CAST to the type specified in their annotation.

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream, context\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\ncontext.set_global(\"secret\", \"1\")\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    secret: int = Context(),\n):\n    assert secret == \"1\"\n
from faststream import Context, FastStream, context\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\ncontext.set_global(\"secret\", \"1\")\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    secret: int = Context(),\n):\n    assert secret == \"1\"\n
from faststream import Context, FastStream, context\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\ncontext.set_global(\"secret\", \"1\")\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    secret: int = Context(),\n):\n    assert secret == \"1\"\n
from faststream import Context, FastStream, context\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\ncontext.set_global(\"secret\", \"1\")\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    secret: int = Context(),\n):\n    assert secret == \"1\"\n

If you require this functionality, you can enable the appropriate flag.

KafkaRabbitMQNATSRedis
@broker.subscriber(\"test-topic2\")\nasync def handle_int(\n    secret: int = Context(cast=True),\n):\n    assert secret == 1\n
@broker.subscriber(\"test-queue2\")\nasync def handle_int(\n    secret: int = Context(cast=True),\n):\n    assert secret == 1\n
@broker.subscriber(\"test-subject2\")\nasync def handle_int(\n    secret: int = Context(cast=True),\n):\n    assert secret == 1\n
@broker.subscriber(\"test-channel2\")\nasync def handle_int(\n    secret: int = Context(cast=True),\n):\n    assert secret == 1\n
","boost":10},{"location":"getting-started/context/fields/","title":"Access by Name","text":"

Sometimes, you may need to use a different name for the argument (not the one under which it is stored in the context) or get access to specific parts of the object. To do this, simply specify the name of what you want to access, and the context will provide you with the object.

KafkaRabbitMQNATSRedis
from faststream import Context, FastStream\nfrom faststream.kafka import KafkaBroker\nfrom faststream.kafka.message import KafkaMessage\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    msg: KafkaMessage = Context(\"message\"),\n    correlation_id: str = Context(\"message.correlation_id\"),\n    user_header: str = Context(\"message.headers.user\"),\n):\n    assert msg.correlation_id == correlation_id\n    assert msg.headers[\"user\"] == user_header\n

This way you can get access to context object by its name

msg: KafkaMessage = Context(\"message\"),\n
from faststream import Context, FastStream\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.rabbit.message import RabbitMessage\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    msg: RabbitMessage = Context(\"message\"),\n    correlation_id: str = Context(\"message.correlation_id\"),\n    user_header: str = Context(\"message.headers.user\"),\n):\n    assert msg.correlation_id == correlation_id\n    assert msg.headers[\"user\"] == user_header\n

This way you can get access to context object by its name

msg: RabbitMessage = Context(\"message\"),\n
from faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.message import NatsMessage\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    msg: NatsMessage = Context(\"message\"),\n    correlation_id: str = Context(\"message.correlation_id\"),\n    user_header: str = Context(\"message.headers.user\"),\n):\n    assert msg.correlation_id == correlation_id\n    assert msg.headers[\"user\"] == user_header\n

This way you can get access to context object by its name

msg: NatsMessage = Context(\"message\"),\n
from faststream import Context, FastStream\nfrom faststream.redis import RedisBroker\nfrom faststream.redis.message import RedisMessage\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    msg: RedisMessage = Context(\"message\"),\n    correlation_id: str = Context(\"message.correlation_id\"),\n    user_header: str = Context(\"message.headers.user\"),\n):\n    assert msg.correlation_id == correlation_id\n    assert msg.headers[\"user\"] == user_header\n

This way you can get access to context object by its name

msg: RedisMessage = Context(\"message\"),\n

This way you can get access to context object specific field

correlation_id: str = Context(\"message.correlation_id\"),\n

Or even to a dict key

user_header: str = Context(\"message.headers.user\"),\n
","boost":10},{"location":"getting-started/contributing/CONTRIBUTING/","title":"Development","text":"

After cloning the project, you'll need to set up the development environment. Here are the guidelines on how to do this.

","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#virtual-environment-with-venv","title":"Virtual Environment with venv","text":"

Create a virtual environment in a directory using Python's venv module:

python -m venv venv\n

That will create a ./venv/ directory with Python binaries, allowing you to install packages in an isolated environment.

","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#activate-the-environment","title":"Activate the Environment","text":"

Activate the new environment with:

source ./venv/bin/activate\n

Ensure you have the latest pip version in your virtual environment:

python -m pip install --upgrade pip\n
","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#installing-dependencies","title":"Installing Dependencies","text":"

After activating the virtual environment as described above, run:

pip install -e \".[dev]\"\n

This will install all the dependencies and your local FastStream in your virtual environment.

","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#using-your-local-faststream","title":"Using Your local FastStream","text":"

If you create a Python file that imports and uses FastStream, and run it with the Python from your local environment, it will use your local FastStream source code.

Whenever you update your local FastStream source code, it will automatically use the latest version when you run your Python file again. This is because it is installed with -e.

This way, you don't have to \"install\" your local version to be able to test every change.

To use your local FastStream CLI, type:

python -m faststream ...\n
","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#running-tests","title":"Running Tests","text":"","boost":3},{"location":"getting-started/contributing/CONTRIBUTING/#pytest","title":"Pytest","text":"

To run tests with your current FastStream application and Python environment, use:

pytest tests\n# or\n./scripts/test.sh\n# with coverage output\n./scripts/test-cov.sh\n

In your project, you'll find some pytest marks:

By default, running pytest will execute \"not slow\" tests.

To run all tests use:

pytest -m 'all'\n

If you don't have a local broker instance running, you can run tests without those dependencies:

pytest -m 'not rabbit and not kafka and not nats and not redis'\n

To run tests based on RabbitMQ, Kafka, or other dependencies, the following dependencies are needed to be started as docker containers:

version: \"3\"\nservices:\n  # nosemgrep: yaml.docker-compose.security.writable-filesystem-service.writable-filesystem-service\n  rabbitmq:\n    image: rabbitmq:alpine\n    ports:\n      - \"5672:5672\"\n    # https://semgrep.dev/r?q=yaml.docker-compose.security.no-new-privileges.no-new-privileges\n    security_opt:\n      - no-new-privileges:true\n  # nosemgrep: yaml.docker-compose.security.writable-filesystem-service.writable-filesystem-service\n  kafka:\n    image: bitnami/kafka:3.5.0\n    ports:\n      - \"9092:9092\"\n    environment:\n      KAFKA_ENABLE_KRAFT: \"true\"\n      KAFKA_CFG_NODE_ID: \"1\"\n      KAFKA_CFG_PROCESS_ROLES: \"broker,controller\"\n      KAFKA_CFG_CONTROLLER_LISTENER_NAMES: \"CONTROLLER\"\n      KAFKA_CFG_LISTENERS: \"PLAINTEXT://:9092,CONTROLLER://:9093\"\n      KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP: \"CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT\"\n      KAFKA_CFG_ADVERTISED_LISTENERS: \"PLAINTEXT://127.0.0.1:9092\"\n      KAFKA_BROKER_ID: \"1\"\n      KAFKA_CFG_CONTROLLER_QUORUM_VOTERS: \"1@kafka:9093\"\n      ALLOW_PLAINTEXT_LISTENER: \"true\"\n    # https://semgrep.dev/r?q=yaml.docker-compose.security.no-new-privileges.no-new-privileges\n    security_opt:\n      - no-new-privileges:true\n  # nosemgrep: yaml.docker-compose.security.writable-filesystem-service.writable-filesystem-service\n  nats:\n    image: nats\n    command: -js\n    ports:\n      - 4222:4222\n      - 8222:8222  # management\n    # https://semgrep.dev/r?q=yaml.docker-compose.security.no-new-privileges.no-new-privileges\n    security_opt:\n      - no-new-privileges:true\n  # nosemgrep: yaml.docker-compose.security.writable-filesystem-service.writable-filesystem-service\n  redis:\n    image: redis:alpine\n    ports:\n      - 6379:6379\n    # https://semgrep.dev/r?q=yaml.docker-compose.security.no-new-privileges.no-new-privileges\n    security_opt:\n      - no-new-privileges:true\n

You can start the dependencies easily using provided script by running:

./scripts/start_test_env.sh\n

Once you are done with development and running tests, you can stop the dependencies' docker containers by running:

./scripts/stop_test_env.sh\n
","boost":3},{"location":"getting-started/contributing/docs/","title":"Documentation","text":"","boost":3},{"location":"getting-started/contributing/docs/#how-to-help","title":"How to help","text":"

You will be of invaluable help if you contribute to the documentation.

Such a contribution can be:

You can report all this in discussions on GitHub, start issue, or write about it in our discord group.

Note

Special thanks to those who are ready to offer help with the case and help in developing documentation, as well as translating it into other languages.

","boost":3},{"location":"getting-started/contributing/docs/#how-to-get-started","title":"How to get started","text":"

To develop the documentation, you don't even need to install the entire FastStream project as a whole.

Enough:

  1. Clone the project repository
  2. Create a virtual environment
    python -m venv venv\n
  3. Activate it
    source venv/bin/activate\n
  4. Install documentation dependencies
    pip install \".[devdocs]\"\n
  5. Go to the docs/ directory
  6. Start the local documentation server
    mkdocs serve\n

Now all changes in the documentation files will be reflected on your local version of the site. After making all the changes, you can issue a PR with them - and we will gladly accept it!

","boost":3},{"location":"getting-started/dependencies/","title":"Dependencies","text":"

FastStream uses the secondary library FastDepends for dependency management. This dependency system is literally borrowed from FastAPI, so if you know how to work with that framework, you'll be comfortable with dependencies in FastStream.

You can visit the FastDepends documentation for more details, but the key points and additions are covered here.

","boost":10},{"location":"getting-started/dependencies/#type-casting","title":"Type Casting","text":"

The key function in the dependency management and type conversion system in FastStream is the decorator @apply_types (also known as @inject in FastDepends).

By default, it applies to all event handlers, unless you disabled the same option when creating the broker.

KafkaRabbitMQNATSRedis
from faststream.kafka import KafkaBroker\nbroker = KafkaBroker(..., apply_types=False)\n
from faststream.rabbit import RabbitBroker\nbroker = RabbitBroker(..., apply_types=False)\n
from faststream.nats import NatsBroker\nbroker = NatsBroker(..., apply_types=False)\n
from faststream.redis import RedisBroker\nbroker = RedisBroker(..., apply_types=False)\n

Warning

Setting the apply_types=False flag not only disables type casting but also Depends and Context. If you want to disable only type casting, use validate=False instead.

This flag can be useful if you are using FastStream within another framework and you need to use its native dependency system.

","boost":10},{"location":"getting-started/dependencies/#dependency-injection","title":"Dependency Injection","text":"

To implement dependencies in FastStream, a special class called Depends is used

KafkaRabbitMQNATSRedis
from faststream import FastStream, Depends\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\ndef simple_dependency():\n    return 1\n\n@broker.subscriber(\"test\")\nasync def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
from faststream import FastStream, Depends\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\ndef simple_dependency():\n    return 1\n\n@broker.subscriber(\"test\")\nasync def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
from faststream import FastStream, Depends\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\ndef simple_dependency():\n    return 1\n\n@broker.subscriber(\"test\")\nasync def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
from faststream import FastStream, Depends\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\ndef simple_dependency():\n    return 1\n\n@broker.subscriber(\"test\")\nasync def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n

The first step: You need to declare a dependency, which can be any Callable object.

Callable

A \"Callable\" is an object that can be \"called\". It can be a function, a class, or a class method.

In other words, if you can write code like my_object() - my_object is Callable

KafkaRabbitMQNATSRedis
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n

Second step: Declare which dependencies you need using Depends

KafkaRabbitMQNATSRedis
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n
async def handler(body: dict, d: int = Depends(simple_dependency)):\n    assert d == 1\n

The last step: Just use the result of executing your dependency!

It's easy, isn't it?

Auto @apply_types

In the code above, we didn't use this decorator for our dependencies. However, it still applies to all functions used as dependencies. Please keep this in your mind.

","boost":10},{"location":"getting-started/dependencies/#top-level-dependencies","title":"Top-level Dependencies","text":"

If you don't need a dependency result, you can use the following code:

@broker.subscriber(\"test\")\ndef method(_ = Depends(...)): ...\n

But, using a special subscriber parameter is much more suitable:

@broker.subscriber(\"test\", dependencies=[Depends(...)])\ndef method(): ...\n

You can also declare broker-level dependencies, which will be applied to all broker's handlers:

broker = RabbitBroker(dependencies=[Depends(...)])\n
","boost":10},{"location":"getting-started/dependencies/#nested-dependencies","title":"Nested Dependencies","text":"

Dependencies can also contain other dependencies. This works in a very predictable way: just declare Depends in the dependent function.

KafkaRabbitMQNATSRedis
from faststream import FastStream, Depends\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\ndef another_dependency():\n    return 1\n\ndef simple_dependency(b: int = Depends(another_dependency)): # (1)\n    return b * 2\n\n@broker.subscriber(\"test\")\nasync def handler(\n    body: dict,\n    a: int = Depends(another_dependency),\n    b: int = Depends(simple_dependency)):\n    assert (a + b) == 3\n
  1. A nested dependency is called here
from faststream import FastStream, Depends\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\ndef another_dependency():\n    return 1\n\ndef simple_dependency(b: int = Depends(another_dependency)): # (1)\n    return b * 2\n\n@broker.subscriber(\"test\")\nasync def handler(\n    body: dict,\n    a: int = Depends(another_dependency),\n    b: int = Depends(simple_dependency)):\n    assert (a + b) == 3\n
  1. A nested dependency is called here
from faststream import FastStream, Depends\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\ndef another_dependency():\n    return 1\n\ndef simple_dependency(b: int = Depends(another_dependency)): # (1)\n    return b * 2\n\n@broker.subscriber(\"test\")\nasync def handler(\n    body: dict,\n    a: int = Depends(another_dependency),\n    b: int = Depends(simple_dependency)):\n    assert (a + b) == 3\n
  1. A nested dependency is called here
from faststream import FastStream, Depends\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\ndef another_dependency():\n    return 1\n\ndef simple_dependency(b: int = Depends(another_dependency)): # (1)\n    return b * 2\n\n@broker.subscriber(\"test\")\nasync def handler(\n    body: dict,\n    a: int = Depends(another_dependency),\n    b: int = Depends(simple_dependency)):\n    assert (a + b) == 3\n
  1. A nested dependency is called here

Caching

In the example above, the another_dependency function will be called at ONCE! FastDepends caches all dependency execution results within ONE @apply_types call stack. This means that all nested dependencies will receive the cached result of dependency execution. But, between different calls of the main function, these results will be different.

To prevent this behavior, just use Depends(..., cache=False). In this case, the dependency will be used for each function in the call stack where it is used.

","boost":10},{"location":"getting-started/dependencies/#use-with-regular-functions","title":"Use with Regular Functions","text":"

You can use the decorator @apply_types not only with @broker.subscriber(...), but also with regular functions, both synchronous and asynchronous.

SyncAsync
from faststream import Depends, apply_types\n\ndef simple_dependency(a: int, b: int = 3):\n    return a + b\n\n@apply_types\ndef method(a: int, d: int = Depends(simple_dependency)):\n    return a + d\n\ndef test_sync_dependency():\n    assert method(\"1\") == 5\n
import asyncio\nimport pytest\nfrom faststream import Depends, apply_types\n\nasync def simple_dependency(a: int, b: int = 3):\n    return a + b\n\ndef another_dependency(a: int):\n    return a\n\n@apply_types\nasync def method(\n    a: int,\n    b: int = Depends(simple_dependency),\n    c: int = Depends(another_dependency),\n):\n    return a + b + c\n\n@pytest.mark.asyncio\nasync def test_async_dependency():\n    assert 6 == await method(\"1\")\n

Be careful

In asynchronous code, you can use both synchronous and asynchronous dependencies. But in synchronous code, only synchronous dependencies are available to you.

","boost":10},{"location":"getting-started/dependencies/#casting-dependency-types","title":"Casting Dependency Types","text":"

FastDepends, used by FastStream, also gives the type return. This means that the value returned by the dependency will be be cast to the type twice: as return for dependencies and as the input argument of the main function. This does not incur additional costs if these types have the same annotation. Just keep it in mind. Or not... Anyway, I've warned you.

from faststream import Depends, apply_types\n\ndef simple_dependency(a: int, b: int = 3) -> str:\n    return a + b  # 'return' is cast to `str` for the first time\n\n@apply_types\ndef method(a: int, d: int = Depends(simple_dependency)):\n    # 'd' is cast to `int` for the second time\n    return a + d\n\nassert method(\"1\") == 5\n

Also, the result of executing the dependency is cached. If you use this dependency in N functions, this cached result will be converted to type N times (at the input to the function being used).

To avoid problems with this, use mypy or just be careful with the annotation of types in your project.

","boost":10},{"location":"getting-started/dependencies/global/","title":"Global","text":""},{"location":"getting-started/dependencies/testing/","title":"Testing","text":"

https://lancetnik.github.io/FastDepends/tutorial/overrides/

"},{"location":"getting-started/integrations/django/","title":"Using FastStream with Django","text":"

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel. It\u2019s free and open source.

In this tutorial, let's see how to use the FastStream app alongside a Django app.

","boost":10},{"location":"getting-started/integrations/django/#asgi","title":"ASGI","text":"

ASGI protocol supports lifespan events, and Django can be served as an ASGI application. So, the best way to integrate FastStream with the Django is by using ASGI lifespan. You can write it by yourself (it is really easy) or use something like this, but the prefered way for us is using Starlette Router.

Starlette Router allows you to serve any ASGI application you want, and it also supports lifespans. So, you can use it in your project to serve your regular Django ASGI and start up your FastStream broker too. Additionally, Starlette has much better static files support, providing an extra zero-cost feature.

","boost":10},{"location":"getting-started/integrations/django/#default-django-application","title":"Default Django Application","text":"

Well, lets take a look at a default Django asgi.py

asgi.py
import os\n\nfrom django.core.asgi import get_asgi_application\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\")\n\napplication = get_asgi_application()\n

You can already serve it using any ASGI server

For example, using uvicorn:

uvicorn asgi:app --workers 4\n

Or you can use Gunicorn with uvicorn workers

gunicorn asgi:app --workers 4 --worker-class uvicorn.workers.UvicornWorker\n

Your Django views, models and other stuff has no any changes if you serving it through ASGI, so you need no worry about it.

","boost":10},{"location":"getting-started/integrations/django/#faststream-integration","title":"FastStream Integration","text":"","boost":10},{"location":"getting-started/integrations/django/#serving-django-via-starlette","title":"Serving Django via Starlette","text":"

Now, we need to modify our asgi.py to serve it using Starlette

asgi.py
# regular Djano stuff\nimport os\n\nfrom django.core.asgi import get_asgi_application\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\")\n\ndjango_asgi = get_asgi_application()\n\n# Starlette serving\nfrom starlette.applications import Starlette\nfrom starlette.routing import Mount\n\napp = Starlette(\n    routes=(\n        Mount(\"/\", django_asgi()),  # redirect all requests to Django\n    ),\n)\n
","boost":10},{"location":"getting-started/integrations/django/#serving-static-files-with-starlette","title":"Serving static files with Starlette","text":"

Also, Starlette has a better static files provider than original Django one, so we can reuse it too.

Just add this line to your settings.py

settings.py
STATIC_ROOT = \"static/\"\n

And collect all static files by default Django command

python manage.py collectstatic\n

It creates a static/ directory in the root of your project, so you can serve it using Starlette

asgi.py
# Code above omitted \ud83d\udc46\n\nfrom starlette.staticfiles import StaticFiles\n\napp = Starlette(\n    routes=(\n        # /static is your STATIC_URL setting\n        Mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\"),\n        Mount(\"/\", get_asgi_application()),  # regular Django ASGI\n    ),\n)\n
","boost":10},{"location":"getting-started/integrations/django/#faststream-lifespan","title":"FastStream lifespan","text":"

Finally, we can add our FastStream integration like a regular lifespan

asgi.py
# Code above omitted \ud83d\udc46\n\nfrom contextlib import asynccontextmanager\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker()\n\n@asynccontextmanager\nasync def broker_lifespan(app):\n    await broker.start()\n    try:\n        yield\n    finally:\n        await broker.close()\n\napp = Starlette(\n    ...,\n    lifespan=broker_lifespan,\n)\n

Note

The code imports KafkaBroker as our application is going to connect with Kafka. Depending on your requirements, import the necessary service's broker from the options provided by FastStream, such as RabbitBroker, NatsBroker or KafkaBroker.

Full Example asgi.py
import os\nfrom contextlib import asynccontextmanager\n\nfrom django.core.asgi import get_asgi_application\nfrom starlette.applications import Starlette\nfrom starlette.routing import Mount\nfrom starlette.staticfiles import StaticFiles\nfrom faststream.kafka import KafkaBroker\n\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"app.settings\")\n\nbroker = KafkaBroker()\n\n@asynccontextmanager\nasync def broker_lifespan(app):\n    await broker.start()\n    try:\n        yield\n    finally:\n        await broker.close()\n\napp = Starlette(\n    routes=(\n        Mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\"),\n        Mount(\"/\", get_asgi_application()),\n    ),\n    lifespan=broker_lifespan,\n)\n

This way we can easely integrate our FastStream apllication with the Django!

","boost":10},{"location":"getting-started/integrations/fastapi/","title":"FastAPI Plugin","text":"","boost":10},{"location":"getting-started/integrations/fastapi/#handling-messages","title":"Handling messages","text":"

FastStream can be used as a part of FastAPI.

Just import a StreamRouter you need and declare the message handler in the same way as with a regular FastStream application.

Tip

When used in this way, FastStream does not use its own dependency system but integrates into FastAPI. That is, you can use Depends, BackgroundTasks and other original FastAPI features as if it were a regular HTTP endpoint, but you can't use faststream.Context and faststream.Depends.

Note that the code below uses fastapi.Depends, not faststream.Depends.

Also, instead original faststream.Context you should use faststream.[broker].fastapi.Context (the same with already created annotations)

KafkaRabbitMQNATSRedis
from fastapi import Depends, FastAPI\nfrom pydantic import BaseModel\n\nfrom faststream.kafka.fastapi import KafkaRouter, Logger\n\nrouter = KafkaRouter(\"localhost:9092\")\n\nclass Incoming(BaseModel):\n    m: dict\n\ndef call():\n    return True\n\n@router.subscriber(\"test\")\n@router.publisher(\"response\")\nasync def hello(m: Incoming, logger: Logger, d=Depends(call)):\n    logger.info(m)\n    return {\"response\": \"Hello, Kafka!\"}\n\n@router.get(\"/\")\nasync def hello_http():\n    return \"Hello, HTTP!\"\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom pydantic import BaseModel\n\nfrom faststream.rabbit.fastapi import RabbitRouter, Logger\n\nrouter = RabbitRouter(\"amqp://guest:guest@localhost:5672/\")\n\nclass Incoming(BaseModel):\n    m: dict\n\ndef call():\n    return True\n\n@router.subscriber(\"test\")\n@router.publisher(\"response\")\nasync def hello(m: Incoming, logger: Logger, d=Depends(call)):\n    logger.info(m)\n    return {\"response\": \"Hello, Rabbit!\"}\n\n@router.get(\"/\")\nasync def hello_http():\n    return \"Hello, HTTP!\"\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom pydantic import BaseModel\n\nfrom faststream.nats.fastapi import NatsRouter, Logger\n\nrouter = NatsRouter(\"nats://localhost:4222\")\n\nclass Incoming(BaseModel):\n    m: dict\n\ndef call():\n    return True\n\n@router.subscriber(\"test\")\n@router.publisher(\"response\")\nasync def hello(m: Incoming, logger: Logger, d=Depends(call)):\n    logger.info(m)\n    return {\"response\": \"Hello, NATS!\"}\n\n@router.get(\"/\")\nasync def hello_http():\n    return \"Hello, HTTP!\"\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom pydantic import BaseModel\n\nfrom faststream.redis.fastapi import RedisRouter, Logger\n\nrouter = RedisRouter(\"redis://localhost:6379\")\n\nclass Incoming(BaseModel):\n    m: dict\n\ndef call():\n    return True\n\n@router.subscriber(\"test\")\n@router.publisher(\"response\")\nasync def hello(m: Incoming, logger: Logger, d=Depends(call)):\n    logger.info(m)\n    return {\"response\": \"Hello, Redis!\"}\n\n@router.get(\"/\")\nasync def hello_http():\n    return \"Hello, HTTP!\"\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n

When processing a message from a broker, the entire message body is placed simultaneously in both the body and path request parameters. You can access them in any way convenient for you. The message header is placed in headers.

Also, this router can be fully used as an HttpRouter (of which it is the inheritor). So, you can use it to declare any get, post, put and other HTTP methods. For example, this is done at line 20.

Warning

If your ASGI server does not support installing state inside lifespan, you can disable this behavior as follows:

router = StreamRouter(..., setup_state=False)\n

However, after that, you will not be able to access the broker from your application's state (but it is still available as the router.broker).

","boost":10},{"location":"getting-started/integrations/fastapi/#accessing-the-broker-object","title":"Accessing the Broker Object","text":"

Inside each router, there is a broker. You can easily access it if you need to send a message to MQ:

KafkaRabbitMQNATSRedis
from fastapi import FastAPI\n\nfrom faststream.kafka.fastapi import KafkaRouter\n\nrouter = KafkaRouter(\"localhost:9092\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\n@router.get(\"/\")\nasync def hello_http():\n    await router.broker.publish(\"Hello, Kafka!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.rabbit.fastapi import RabbitRouter\n\nrouter = RabbitRouter(\"amqp://guest:guest@localhost:5672/\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\n@router.get(\"/\")\nasync def hello_http():\n    await router.broker.publish(\"Hello, Rabbit!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.nats.fastapi import NatsRouter\n\nrouter = NatsRouter(\"nats://localhost:4222\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\n@router.get(\"/\")\nasync def hello_http():\n    await router.broker.publish(\"Hello, NATS!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.redis.fastapi import RedisRouter\n\nrouter = RedisRouter(\"redis://localhost:6379\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\n@router.get(\"/\")\nasync def hello_http():\n    await router.broker.publish(\"Hello, Redis!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n

Also, you can use the following Depends to access the broker if you want to use it at different parts of your program:

KafkaRabbitMQNATSRedis
from fastapi import Depends, FastAPI\nfrom typing_extensions import Annotated\n\nfrom faststream.kafka import KafkaBroker, fastapi\n\nrouter = fastapi.KafkaRouter(\"localhost:9092\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\ndef broker():\n    return router.broker\n\n\n@router.get(\"/\")\nasync def hello_http(broker: Annotated[KafkaBroker, Depends(broker)]):\n    await broker.publish(\"Hello, Kafka!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom typing_extensions import Annotated\n\nfrom faststream.rabbit import RabbitBroker, fastapi\n\nrouter = fastapi.RabbitRouter(\"amqp://guest:guest@localhost:5672/\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\ndef broker():\n    return router.broker\n\n\n@router.get(\"/\")\nasync def hello_http(broker: Annotated[RabbitBroker, Depends(broker)]):\n    await broker.publish(\"Hello, Rabbit!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom typing_extensions import Annotated\n\nfrom faststream.nats import NatsBroker, fastapi\n\nrouter = fastapi.NatsRouter(\"nats://localhost:4222\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\ndef broker():\n    return router.broker\n\n\n@router.get(\"/\")\nasync def hello_http(broker: Annotated[NatsBroker, Depends(broker)]):\n    await broker.publish(\"Hello, NATS!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n
from fastapi import Depends, FastAPI\nfrom typing_extensions import Annotated\n\nfrom faststream.redis import RedisBroker, fastapi\n\nrouter = fastapi.RedisRouter(\"redis://localhost:6379\")\n\napp = FastAPI(lifespan=router.lifespan_context)\n\n\ndef broker():\n    return router.broker\n\n\n@router.get(\"/\")\nasync def hello_http(broker: Annotated[RedisBroker, Depends(broker)]):\n    await broker.publish(\"Hello, Redis!\", \"test\")\n    return \"Hello, HTTP!\"\n\n\napp.include_router(router)\n

Or you can access the broker from a FastAPI application state (if you don't disable it with setup_state=False):

from fastapi import Request\n\n@app.get(\"/\")\ndef main(request: Request):\n    broker = request.state.broker\n
","boost":10},{"location":"getting-started/integrations/fastapi/#after_startup","title":"@after_startup","text":"

The FastStream application has the @after_startup hook, which allows you to perform operations with your message broker after the connection is established. This can be extremely convenient for managing your brokers' objects and/or sending messages. This hook is also available for your FastAPI StreamRouter

KafkaRabbitMQNATSRedis
from fastapi import FastAPI\n\nfrom faststream.kafka.fastapi import KafkaRouter\n\nrouter = KafkaRouter(\"localhost:9092\")\n\n\n@router.subscriber(\"test\")\nasync def hello(msg: str):\n    return {\"response\": \"Hello, Kafka!\"}\n\n\n@router.after_startup\nasync def test(app: FastAPI):\n    await router.broker.publish(\"Hello!\", \"test\")\n\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.rabbit.fastapi import RabbitRouter\n\nrouter = RabbitRouter(\"amqp://guest:guest@localhost:5672/\")\n\n\n@router.subscriber(\"test\")\nasync def hello(msg: str):\n    return {\"response\": \"Hello, Rabbit!\"}\n\n\n@router.after_startup\nasync def test(app: FastAPI):\n    await router.broker.publish(\"Hello!\", \"test\")\n\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.nats.fastapi import NatsRouter\n\nrouter = NatsRouter(\"nats://localhost:4222\")\n\n\n@router.subscriber(\"test\")\nasync def hello(msg: str):\n    return {\"response\": \"Hello, NATS!\"}\n\n\n@router.after_startup\nasync def test(app: FastAPI):\n    await router.broker.publish(\"Hello!\", \"test\")\n\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
from fastapi import FastAPI\n\nfrom faststream.redis.fastapi import RedisRouter\n\nrouter = RedisRouter(\"redis://localhost:6379\")\n\n\n@router.subscriber(\"test\")\nasync def hello(msg: str):\n    return {\"response\": \"Hello, Redis!\"}\n\n\n@router.after_startup\nasync def test(app: FastAPI):\n    await router.broker.publish(\"Hello!\", \"test\")\n\n\napp = FastAPI(lifespan=router.lifespan_context)\napp.include_router(router)\n
","boost":10},{"location":"getting-started/integrations/fastapi/#documentation","title":"Documentation","text":"

When using FastStream as a router for FastAPI, the framework automatically registers endpoints for hosting AsyncAPI documentation into your application with the following default values:

KafkaRabbitMQNATSRedis
from faststream.kafka.fastapi import KafkaRouter\n\nrouter = KafkaRouter(\n    ...,\n    schema_url=\"/asyncapi\",\n    include_in_schema=True,\n)\n
from faststream.rabbit.fastapi import RabbitRouter\n\nrouter = RabbitRouter(\n    ...,\n    schema_url=\"/asyncapi\",\n    include_in_schema=True,\n)\n
from faststream.nats.fastapi import NatsRouter\n\nrouter = NatsRouter(\n    ...,\n    schema_url=\"/asyncapi\",\n    include_in_schema=True,\n)\n
from faststream.redis.fastapi import RedisRouter\n\nrouter = RedisRouter(\n    ...,\n    schema_url=\"/asyncapi\",\n    include_in_schema=True,\n)\n

This way, you will have three routes to interact with your application's AsyncAPI schema:

","boost":10},{"location":"getting-started/integrations/fastapi/#testing","title":"Testing","text":"

To test your FastAPI StreamRouter, you can still use it with the TestClient:

KafkaRabbitMQNATSRedis
import pytest\n\nfrom faststream.kafka import TestKafkaBroker, fastapi\n\nrouter = fastapi.KafkaRouter()\n\n\n@router.subscriber(\"test\")\nasync def handler(msg: str):\n    ...\n\n\n@pytest.mark.asyncio\nasync def test_router():\n    async with TestKafkaBroker(router.broker) as br:\n        await br.publish(\"Hi!\", \"test\")\n\n        handler.mock.assert_called_once_with(\"Hi!\")\n
import pytest\n\nfrom faststream.rabbit import TestRabbitBroker, fastapi\n\nrouter = fastapi.RabbitRouter()\n\n\n@router.subscriber(\"test\")\nasync def handler(msg: str):\n    ...\n\n\n@pytest.mark.asyncio\nasync def test_router():\n    async with TestRabbitBroker(router.broker) as br:\n        await br.publish(\"Hi!\", \"test\")\n\n        handler.mock.assert_called_once_with(\"Hi!\")\n
import pytest\n\nfrom faststream.nats import TestNatsBroker, fastapi\n\nrouter = fastapi.NatsRouter()\n\n\n@router.subscriber(\"test\")\nasync def handler(msg: str):\n    ...\n\n\n@pytest.mark.asyncio\nasync def test_router():\n    async with TestNatsBroker(router.broker) as br:\n        await br.publish(\"Hi!\", \"test\")\n\n        handler.mock.assert_called_once_with(\"Hi!\")\n
import pytest\n\nfrom faststream.redis import TestRedisBroker, fastapi\n\nrouter = fastapi.RedisRouter()\n\n\n@router.subscriber(\"test\")\nasync def handler(msg: str):\n    ...\n\n\n@pytest.mark.asyncio\nasync def test_router():\n    async with TestRedisBroker(router.broker) as br:\n        await br.publish(\"Hi!\", \"test\")\n\n        handler.mock.assert_called_once_with(\"Hi!\")\n
","boost":10},{"location":"getting-started/integrations/fastapi/#miltiple-routers","title":"Miltiple Routers","text":"

Using FastStream as a FastAPI plugin you are still able to separate messages processing logic between different routers (like with a regular HTTPRouter). But it can be confusing - how you should include multiple routers, if we have to setup router.lifespan_context as a FastAPI object lifespan.

You can make it in a two ways, depends on you reminds.

","boost":10},{"location":"getting-started/integrations/fastapi/#routers-nesting","title":"Routers nesting","text":"

If you want to use the SAME CONNECTION for all of you routers you should nest them each other and finally use only the core router to include it into FastAPI object.

KafkaRabbitMQNATSRedis
from fastapi import FastAPI\nfrom faststream.kafka.fastapi import KafkaRouter\n\ncore_router = KafkaRouter()\nnested_router = KafkaRouter()\n\n@core_router.subscriber(\"core-topic\")\nasync def handler():\n    ...\n\n@nested_router.subscriber(\"nested-topic\")\nasync def nested_handler():\n    ...\n\ncore_router.include_router(nested_router)\n\napp = FastAPI(lifespan=core_router.lifespan_context)\napp.include_router(core_router)\n
from fastapi import FastAPI\nfrom faststream.rabbit.fastapi import RabbitRouter\n\ncore_router = RabbitRouter()\nnested_router = RabbitRouter()\n\n@core_router.subscriber(\"core-queue\")\nasync def handler():\n    ...\n\n@nested_router.subscriber(\"nested-queue\")\nasync def nested_handler():\n    ...\n\ncore_router.include_router(nested_router)\n\napp = FastAPI(lifespan=core_router.lifespan_context)\napp.include_router(core_router)\n
from fastapi import FastAPI\nfrom faststream.nats.fastapi import NatsRouter\n\ncore_router = NatsRouter()\nnested_router = NatsRouter()\n\n@core_router.subscriber(\"core-subject\")\nasync def handler():\n    ...\n\n@nested_router.subscriber(\"nested-subject\")\nasync def nested_handler():\n    ...\n\ncore_router.include_router(nested_router)\n\napp = FastAPI(lifespan=core_router.lifespan_context)\napp.include_router(core_router)\n
from fastapi import FastAPI\nfrom faststream.redis.fastapi import RedisRouter\n\ncore_router = RedisRouter()\nnested_router = RedisRouter()\n\n@core_router.subscriber(\"core-channel\")\nasync def handler():\n    ...\n\n@nested_router.subscriber(\"nested-channel\")\nasync def nested_handler():\n    ...\n\ncore_router.include_router(nested_router)\n\napp = FastAPI(lifespan=core_router.lifespan_context)\napp.include_router(core_router)\n

This way the core router collects all nested routers publishers and subscribers and stores it like its own.

","boost":10},{"location":"getting-started/integrations/fastapi/#custom-lifespan","title":"Custom lifespan","text":"

Overwise, if you want to has multiple connections to different broker instances, you should start routers independently in your custom lifespan

KafkaRabbitMQNATSRedis
from contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom faststream.kafka.fastapi import KafkaRouter\n\ncore_router = KafkaRouter()\nnested_router = KafkaRouter()\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    async with (\n        core_router.lifespan_context(app),\n        nested_router.lifespan_context(app),\n    ):\n        yield\n\napp = FastAPI(lifespan=lifespan)\napp.include_router(core_router)\napp.include_router(nested_router)\n
from contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom faststream.rabbit.fastapi import RabbitRouter\n\ncore_router = RabbitRouter()\nnested_router = RabbitRouter()\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    async with (\n        core_router.lifespan_context(app),\n        nested_router.lifespan_context(app),\n    ):\n        yield\n\napp = FastAPI(lifespan=lifespan)\napp.include_router(core_router)\napp.include_router(nested_router)\n
from contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom faststream.nats.fastapi import NatsRouter\n\ncore_router = NatsRouter()\nnested_router = NatsRouter()\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    async with (\n        core_router.lifespan_context(app),\n        nested_router.lifespan_context(app),\n    ):\n        yield\n\napp = FastAPI(lifespan=lifespan)\napp.include_router(core_router)\napp.include_router(nested_router)\n
from contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom faststream.redis.fastapi import RedisRouter\n\ncore_router = RedisRouter()\nnested_router = RedisRouter()\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    async with (\n        core_router.lifespan_context(app),\n        nested_router.lifespan_context(app),\n    ):\n        yield\n\napp = FastAPI(lifespan=lifespan)\napp.include_router(core_router)\napp.include_router(nested_router)\n

Warning

This way you lose AsyncAPI schema, but we are working on it.

","boost":10},{"location":"getting-started/integrations/frameworks/","title":"INTEGRATIONS","text":"

FastStream brokers are very easy to integrate with any of your applications: it is enough to initialize the broker at startup and close it correctly at the end of your application.

Most HTTP frameworks have built-in lifecycle hooks for this.

FastAPILitestarAiohttpBlacksheepFalconQuartSanic

Tip

If you want to use FastStream in conjunction with FastAPI, perhaps you should use a special plugin

from contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    await broker.start()\n    yield\n    await broker.close()\n\napp = FastAPI(lifespan=lifespan)\n\n@app.get(\"/\")\ndef read_root():\n    return {\"Hello\": \"World\"}\n
from litestar import Litestar, get\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\n\n@broker.subscriber(\"queue\")\nasync def handle(msg):\n    print(msg)\n\n@get(\"/\")\nasync def index() -> str:\n    return \"Hello, world!\"\n\napp = Litestar(\n    [index],\n    on_startup=(broker.start,),\n    on_shutdown=(broker.close,),\n)\n
from aiohttp import web\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\nasync def start_broker(app):\n    await broker.start()\n\n\nasync def stop_broker(app):\n    await broker.close()\n\n\nasync def hello(request):\n    return web.Response(text=\"Hello, world\")\n\n\napp = web.Application()\napp.add_routes([web.get(\"/\", hello)])\napp.on_startup.append(start_broker)\napp.on_cleanup.append(stop_broker)\n\n\nif __name__ == \"__main__\":\n    web.run_app(app)\n
from blacksheep import Application\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\napp = Application()\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\n@app.on_start\nasync def start_broker(application: Application) -> None:\n    await broker.start()\n\n\n@app.on_stop\nasync def stop_broker(application: Application) -> None:\n    await broker.close()\n\n\n@app.route(\"/\")\nasync def home():\n    return \"Hello, World!\"\n
import falcon\nimport falcon.asgi\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\nclass ThingsResource:\n    async def on_get(self, req, resp):\n        resp.status = falcon.HTTP_200\n        resp.content_type = falcon.MEDIA_TEXT\n        resp.text = (\n            \"\\nTwo things awe me most, the starry sky \"\n            \"above me and the moral law within me.\\n\"\n            \"\\n\"\n            \"    ~ Immanuel Kant\\n\\n\"\n        )\n\n\nclass StreamMiddleware:\n    async def process_startup(self, scope, event):\n        await broker.start()\n\n    async def process_shutdown(self, scope, event):\n        await broker.close()\n\n\napp = falcon.asgi.App()\napp.add_middleware(StreamMiddleware())\napp.add_route(\"/things\", ThingsResource())\n
from quart import Quart\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\napp = Quart(__name__)\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\n@app.before_serving\nasync def start_broker():\n    await broker.start()\n\n\n@app.after_serving\nasync def stop_broker():\n    await broker.close()\n\n\n@app.route(\"/\")\nasync def json():\n    return {\"hello\": \"world\"}\n
from sanic import Sanic\nfrom sanic.response import text\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\napp = Sanic(\"MyHelloWorldApp\")\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\n@app.after_server_start\nasync def start_broker(app, loop):\n    await broker.start()\n\n\n@app.after_server_stop\nasync def stop_broker(app, loop):\n    await broker.close()\n\n\n@app.get(\"/\")\nasync def hello_world(request):\n    return text(\"Hello, world.\")\n

However, even if such a hook is not provided, you can do it yourself.

Tornado
import asyncio\n\nimport tornado.web\n\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n\n@broker.subscriber(\"test\")\nasync def base_handler(body):\n    print(body)\n\n\nclass MainHandler(tornado.web.RequestHandler):\n    def get(self):\n        self.write(\"Hello, world\")\n\n\ndef make_app():\n    return tornado.web.Application(\n        [\n            (r\"/\", MainHandler),\n        ]\n    )\n\n\nasync def main():\n    app = make_app()\n    app.listen(8888)\n\n    await broker.start()\n    try:\n        await asyncio.Event().wait()\n    finally:\n        await broker.close()\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n
","boost":10},{"location":"getting-started/lifespan/","title":"Lifespan Events","text":"

Sometimes you need to define the logic that should be executed before launching the application. This means that the code will be executed once - even before your application starts receiving messages.

Also, you may need to terminate some processes after stopping the application. In this case, your code will also be executed exactly once: but after the completion of the main application.

Since this code is executed before the application starts and after it stops, it covers the entire lifecycle (lifespan) of the application.

This can be very useful for initializing your application settings at startup, raising a pool of connections to a database, or running machine learning models.

","boost":10},{"location":"getting-started/lifespan/context/","title":"Lifespan Context Manager","text":"

Also, you can define startup and shutdown logic using the lifespan parameter of the FastSTream app, and a \"context manager\" (I'll show you what that is in a second).

Let's start with an example from hooks page and refactor it using \"context manager\".

We create an async function lifespan() with yield like this:

KafkaRabbitMQNATSRedis
from contextlib import asynccontextmanager\n\nfrom faststream import Context, ContextRepo, FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\n\n\ndef fake_ml_model_answer(x: float):\n    return x * 42\n\n\n@asynccontextmanager\nasync def lifespan(context: ContextRepo):\n    # load fake ML model\n    ml_models = { \"answer_to_everything\": fake_ml_model_answer }\n    context.set_global(\"model\", ml_models)\n\n    yield\n\n    # Clean up the ML models and release the resources\n    ml_models.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n\n\napp = FastStream(broker, lifespan=lifespan)\n
from contextlib import asynccontextmanager\n\nfrom faststream import Context, ContextRepo, FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\n\n\ndef fake_ml_model_answer(x: float):\n    return x * 42\n\n\n@asynccontextmanager\nasync def lifespan(context: ContextRepo):\n    # load fake ML model\n    ml_models = { \"answer_to_everything\": fake_ml_model_answer }\n    context.set_global(\"model\", ml_models)\n\n    yield\n\n    # Clean up the ML models and release the resources\n    ml_models.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n\n\napp = FastStream(broker, lifespan=lifespan)\n
from contextlib import asynccontextmanager\n\nfrom faststream import Context, ContextRepo, FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\n\n\ndef fake_ml_model_answer(x: float):\n    return x * 42\n\n\n@asynccontextmanager\nasync def lifespan(context: ContextRepo):\n    # load fake ML model\n    ml_models = { \"answer_to_everything\": fake_ml_model_answer }\n    context.set_global(\"model\", ml_models)\n\n    yield\n\n    # Clean up the ML models and release the resources\n    ml_models.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n\n\napp = FastStream(broker, lifespan=lifespan)\n
from contextlib import asynccontextmanager\n\nfrom faststream import Context, ContextRepo, FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\n\n\ndef fake_ml_model_answer(x: float):\n    return x * 42\n\n\n@asynccontextmanager\nasync def lifespan(context: ContextRepo):\n    # load fake ML model\n    ml_models = { \"answer_to_everything\": fake_ml_model_answer }\n    context.set_global(\"model\", ml_models)\n\n    yield\n\n    # Clean up the ML models and release the resources\n    ml_models.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n\n\napp = FastStream(broker, lifespan=lifespan)\n

As you can see, lifespan parameter is much suitable for case (than @app.on_startup and @app.after_shutdown separated calls) if you have object needs to process at application startup and shutdown both.

Tip

lifespan starts BEFORE your broken started (@app.on_startup hook) and AFTER broker was shutdown (@app.after_shutdown), so you can't publish any messages here.

If you want to make some actions will already/still running broker, please use @app.after_startup and @app.on_shutdown hooks.

Also, lifespan supports all FastStream hooks features:

","boost":10},{"location":"getting-started/lifespan/hooks/","title":"Lifespan Hooks","text":"","boost":10},{"location":"getting-started/lifespan/hooks/#usage-example","title":"Usage example","text":"

Let's imagine that your application uses pydantic as your settings manager.

I highly recommend using pydantic for these purposes, because this dependency is already used at FastStream and you don't have to install an additional package

Also, let's imagine that you have several .env, .env.development, .env.test, .env.production files with your application settings, and you want to switch them at startup without any code changes.

By passing optional arguments with the command line to your code FastStream allows you to do this easily.

","boost":10},{"location":"getting-started/lifespan/hooks/#lifespan","title":"Lifespan","text":"

Let's write some code for our example

KafkaRabbitMQNATSRedis
from pydantic_settings import BaseSettings\n\nfrom faststream import ContextRepo, FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker()\napp = FastStream(broker)\n\n\nclass Settings(BaseSettings):\n    host: str = \"localhost:9092\"\n\n\n@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
from pydantic_settings import BaseSettings\n\nfrom faststream import ContextRepo, FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\n\nclass Settings(BaseSettings):\n    host: str = \"amqp://guest:guest@localhost:5672/\" \n\n\n@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
from pydantic_settings import BaseSettings\n\nfrom faststream import ContextRepo, FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n\nclass Settings(BaseSettings):\n    host: str = \"nats://localhost:4222\"\n\n\n@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
from pydantic_settings import BaseSettings\n\nfrom faststream import ContextRepo, FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\nclass Settings(BaseSettings):\n    host: str = \"redis://localhost:6379\"\n\n\n@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n

Now this application can be run using the following command to manage the environment:

faststream run serve:app --env .env.test\n
","boost":10},{"location":"getting-started/lifespan/hooks/#details","title":"Details","text":"

Now let's look into a little more detail

To begin with, we used a decorator

@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n

to declare a function that should run when our application starts

The next step is to declare the arguments that our function will receive

@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n

In this case, the env field will be passed to the setup function from the arguments with the command line

Tip

The default lifecycle functions are used with the decorator @apply_types, therefore, all context fields and dependencies are available in them

Then, we initialized the settings of our application using the file passed to us from the command line

@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n

And put these settings in a global context

KafkaRabbitMQNATSRedis
@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
Note

Now we can access our settings anywhere in the application right from the context

from faststream import Context, apply_types\n@apply_types\nasync def func(settings = Context()): ...\n

The last step we initialized our broker: now, when the application starts, it will be ready to receive messages

@app.on_startup\nasync def setup(context: ContextRepo, env: str = \".env\"):\n    settings = Settings(_env_file=env)\n    context.set_global(\"settings\", settings)\n    await broker.connect(settings.host)\n
","boost":10},{"location":"getting-started/lifespan/hooks/#another-example","title":"Another example","text":"

Now let's imagine that we have a machine learning model that needs to process messages from some broker.

Initialization of such models usually takes a long time. It would be wise to do this at the start of the application, and not when processing each message.

You can initialize your model somewhere at the top of your module/file. However, in this case, this code will be run even just in case of importing this module, for example, during testing. It is unlikely that you want to run your model on every test run...

Therefore, it is worth initializing the model in the @app.on_startup hook.

Also, we don't want the model to finish its work incorrectly when the application is stopped. To avoid this, we need the hook @app.on_shutdown

KafkaRabbitMQNATSRedis
from faststream import Context, ContextRepo, FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\nml_models = {}  # fake ML model\n\n\ndef fake_answer_to_everything_ml_model(x: float):\n    return x * 42\n\n\n@app.on_startup\nasync def setup_model(context: ContextRepo):\n    # Load the ML model\n    ml_models[\"answer_to_everything\"] = fake_answer_to_everything_ml_model\n    context.set_global(\"model\", ml_models)\n\n\n@app.on_shutdown\nasync def shutdown_model(model: dict = Context()):\n    # Clean up the ML models and release the resources\n    model.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n
from faststream import Context, ContextRepo, FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\nml_models = {}  # fake ML model\n\n\ndef fake_answer_to_everything_ml_model(x: float):\n    return x * 42\n\n\n@app.on_startup\nasync def setup_model(context: ContextRepo):\n    # Load the ML model\n    ml_models[\"answer_to_everything\"] = fake_answer_to_everything_ml_model\n    context.set_global(\"model\", ml_models)\n\n\n@app.on_shutdown\nasync def shutdown_model(model: dict = Context()):\n    # Clean up the ML models and release the resources\n    model.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n
from faststream import Context, ContextRepo, FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\nml_models = {}  # fake ML model\n\n\ndef fake_answer_to_everything_ml_model(x: float):\n    return x * 42\n\n\n@app.on_startup\nasync def setup_model(context: ContextRepo):\n    # Load the ML model\n    ml_models[\"answer_to_everything\"] = fake_answer_to_everything_ml_model\n    context.set_global(\"model\", ml_models)\n\n\n@app.on_shutdown\nasync def shutdown_model(model: dict = Context()):\n    # Clean up the ML models and release the resources\n    model.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n
from faststream import Context, ContextRepo, FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\nml_models = {}  # fake ML model\n\n\ndef fake_answer_to_everything_ml_model(x: float):\n    return x * 42\n\n\n@app.on_startup\nasync def setup_model(context: ContextRepo):\n    # Load the ML model\n    ml_models[\"answer_to_everything\"] = fake_answer_to_everything_ml_model\n    context.set_global(\"model\", ml_models)\n\n\n@app.on_shutdown\nasync def shutdown_model(model: dict = Context()):\n    # Clean up the ML models and release the resources\n    model.clear()\n\n\n@broker.subscriber(\"test\")\nasync def predict(x: float, model=Context()):\n    result = model[\"answer_to_everything\"](x)\n    return {\"result\": result}\n
","boost":10},{"location":"getting-started/lifespan/hooks/#multiple-hooks","title":"Multiple hooks","text":"

If you want to declare multiple lifecycle hooks, they will be used in the order they are registered:

from faststream import Context, ContextRepo, FastStream\n\napp = FastStream()\n\n\n@app.on_startup\nasync def setup(context: ContextRepo):\n    context.set_global(\"field\", 1)\n\n\n@app.on_startup\nasync def setup_later(field: int = Context()):\n    assert field == 1\n
","boost":10},{"location":"getting-started/lifespan/hooks/#some-more-details","title":"Some more details","text":"","boost":10},{"location":"getting-started/lifespan/hooks/#async-or-not-async","title":"Async or not async","text":"

In the asynchronous version of the application, both asynchronous and synchronous methods can be used as hooks. In the synchronous version, only synchronous methods are available.

","boost":10},{"location":"getting-started/lifespan/hooks/#command-line-arguments","title":"Command line arguments","text":"

Command line arguments are available in all @app.on_startup hooks. To use them in other parts of the application, put them in the ContextRepo.

","boost":10},{"location":"getting-started/lifespan/hooks/#broker-initialization","title":"Broker initialization","text":"

The @app.on_startup hooks are called BEFORE the broker is launched by the application. The @app.after_shutdown hooks are triggered AFTER stopping the broker.

If you want to perform some actions AFTER initializing the broker: send messages, initialize objects, etc., you should use the @app.after_startup hook.

","boost":10},{"location":"getting-started/lifespan/test/","title":"Events Testing","text":"

In the most cases you are testing your subsriber/publisher functions, but sometimes you need to trigger some lifespan hooks in your tests too.

For this reason, FastStream has a special TestApp patcher working as a regular async context manager.

KafkaRabbitMQNATSRedis
import pytest\n\nfrom faststream import FastStream, TestApp\nfrom faststream.kafka import KafkaBroker, TestKafkaBroker\n\napp = FastStream(KafkaBroker())\n\n\n@app.after_startup\nasync def handle():\n    print(\"Calls in tests too!\")\n\n\n@pytest.mark.asyncio\nasync def test_lifespan():\n    async with (\n        TestKafkaBroker(app.broker, connect_only=True),\n        TestApp(app),\n    ):\n        # test something\n        pass\n
import pytest\n\nfrom faststream import FastStream, TestApp\nfrom faststream.rabbit import RabbitBroker, TestRabbitBroker\n\napp = FastStream(RabbitBroker())\n\n\n@app.after_startup\nasync def handle():\n    print(\"Calls in tests too!\")\n\n\n@pytest.mark.asyncio\nasync def test_lifespan():\n    async with (\n        TestRabbitBroker(app.broker, connect_only=True),\n        TestApp(app),\n    ):\n        # test something\n        pass\n
import pytest\n\nfrom faststream import FastStream, TestApp\nfrom faststream.nats import NatsBroker, TestNatsBroker\n\napp = FastStream(NatsBroker())\n\n\n@app.after_startup\nasync def handle():\n    print(\"Calls in tests too!\")\n\n\n@pytest.mark.asyncio\nasync def test_lifespan():\n    async with (\n        TestNatsBroker(app.broker, connect_only=True),\n        TestApp(app),\n    ):\n        # test something\n        pass\n
import pytest\n\nfrom faststream import FastStream, TestApp\nfrom faststream.redis import RedisBroker, TestRedisBroker\n\napp = FastStream(RedisBroker())\n\n\n@app.after_startup\nasync def handle():\n    print(\"Calls in tests too!\")\n\n\n@pytest.mark.asyncio\nasync def test_lifespan():\n    async with (\n        TestRedisBroker(app.broker, connect_only=True),\n        TestApp(app),\n    ):\n        # test something\n        pass\n
","boost":10},{"location":"getting-started/lifespan/test/#using-with-testbroker","title":"Using with TestBroker","text":"

If you want to use In-Memory patched broker in your tests, it's advisable to patch the broker first (before applying the application patch).

Also, TestApp and TestBroker are calling broker.start() both. According to the original logic, broker should be started in the FastStream application, but TestBroker applied first breaks this behavior. This reason TestApp prevents TestBroker broker.start() call if it placed incide TestBroker context.

This behavior is ruled by connect_only TestBroker argument. By default it has None value, but TestApp can set it to True/False by inner logic. To prevent this \"magic\", just setup connect_only argument manually.

Warning

With connect_only=False, all FastStream hooks will be called after broker was started, what can breaks some @app.on_startup logic.

","boost":10},{"location":"getting-started/middlewares/","title":"Middlewares","text":"

Middlewares are a powerful mechanism that allows you to add additional logic to any stage of the message processing pipeline.

This way, you can greatly extend your FastStream application with features such as:

Middlewares have several methods to override. You can implement some or all of them and use middlewares at the broker, router, or subscriber level. Thus, middlewares are the most flexible FastStream feature.

","boost":10},{"location":"getting-started/middlewares/#message-receive-wrapper","title":"Message Receive Wrapper","text":"

Unfortunately, this powerful feature has a somewhat complex signature too.

Using middlewares, you can wrap the entire message processing pipeline. In this case, you need to specify on_receive and after_processed methods:

from faststream import BaseMiddleware\n\nclass MyMiddleware(BaseMiddleware):\n    async def on_receive(self):\n        print(f\"Received: {self.message}\")\n        return await super().on_receive()\n\n    async def after_processed(self, exc_type, exc_val, exec_tb):\n        return await super().after_processed(exc_type, exc_val, exec_tb)\n

These methods should be overwritten only in a broker-level middlewares.

Broker(middlewares=[MyMiddleware])\n

In other cases, on_receive will be called at every subscriber filter function call.

Tip

Please always call super() methods at the end of your function; this is important for correct error processing.

","boost":10},{"location":"getting-started/middlewares/#message-consuming-wrapper","title":"Message Consuming Wrapper","text":"

Also, using middlewares, you are able to wrap consumer function calls directly.

In this case, you need to specify on_receive and after_processed methods:

from typing import Optional\n\nfrom faststream import BaseMiddleware:\nfrom faststream.types import DecodedMessage\n\nclass MyMiddleware(BaseMiddleware):\n    async def on_consume(self, msg: DecodedMessage) -> DecodedMessage:\n        return await super().on_consume(msg)\n\n    async def after_consume(self, err: Optional[Exception]) -> None:\n        return await super().after_consume(err)\n

This way, you can patch the incoming message body right before passing it to your consumer subscriber.

Also, if you have multiple filters for one subscriber, these methods will be called at once when the filtering is completed successfully.

","boost":10},{"location":"getting-started/middlewares/#message-publishing-wrapper","title":"Message Publishing Wrapper","text":"

Finally, using middlewares, you are able to patch outgoing messages too. For example, you can compress/encode outgoing messages at the application level.

In this, case you need to specify on_publish and after_publish methods:

from typing import Optional\n\nfrom faststream import BaseMiddleware:\nfrom faststream.types import SendableMessage\n\nclass MyMiddleware(BaseMiddleware):\n    async def on_publish(self, msg: SendableMessage) -> SendableMessage:\n        return await super().on_publish(msg)\n\n    async def after_publish(self, err: Optional[Exception]) -> None:\n        return await super().after_publish(err)\n
","boost":10},{"location":"getting-started/publishing/","title":"Publishing Basics","text":"

FastStream is broker-agnostic and easy to use, even as a client in non-FastStream applications.

It offers several use cases for publishing messages:

All of these variants have their own advantages and limitations, so you can choose what you want based on your requirements. Please visit the following pages for details.

","boost":10},{"location":"getting-started/publishing/#serialization","title":"Serialization","text":"

FastStream allows you to publish any JSON-serializable messages (Python types, Pydantic models, etc.) or raw bytes.

It automatically sets up all required headers, especially the correlation_id, which is used to trace message processing pipelines across all services.

The content-type is a meaningfull header for FastStream services. It helps the framework serialize messages faster, selecting the right serializer based on the header. This header is automatically set by FastStream too, but you should set it up manually using other libraries to interact with FastStream applications.

Content-Type can be:

By the way, you can use application/json for all of your messages if they are not raw bytes. You can even omit using any header at all, but it makes serialization slightly slower.

","boost":10},{"location":"getting-started/publishing/#publishing","title":"Publishing","text":"

FastStream can also be used as a Broker client to send messages in other applications. It is quite straightforward and similar to aiohttp or requests.

You just need to connect your broker, and you are ready to send a message. Additionally, you can use Broker as an async context manager to establish a connection and disconnect when leaving the scope.

To publish a message, simply set up the message content and a routing key:

KafkaRabbitMQNATSRedis
async with KafkaBroker() as br:\n    await br.publish(\"message\", \"topic\")\n
async with RabbitBroker() as br:\n    await br.publish(\"message\", \"queue\")\n
async with NatsBroker() as br:\n    await br.publish(\"message\", \"subject\")\n
async with RedisBroker() as br:\n    await br.publish(\"message\", \"channel\")\n
","boost":10},{"location":"getting-started/publishing/broker/","title":"Broker Publishing","text":"

The easiest way to publish a message is to use a Broker, which allows you to use it as a publisher client in any applications.

In the FastStream project, this call is not represented in the AsyncAPI scheme. You can use it to send rarely-publishing messages, such as startup or shutdown events.

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle():\n    await broker.publish(\"Hi!\", topic=\"another-topic\")\n\n\n@broker.subscriber(\"another-topic\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", topic=\"test-topic\")\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle():\n    await broker.publish(\"Hi!\", queue=\"another-queue\")\n\n\n@broker.subscriber(\"another-queue\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", queue=\"test-queue\")\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle():\n    await broker.publish(\"Hi!\", subject=\"another-subject\")\n\n\n@broker.subscriber(\"another-subject\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", subject=\"test-subject\")\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle():\n    await broker.publish(\"Hi!\", channel=\"another-channel\")\n\n\n@broker.subscriber(\"another-channel\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", channel=\"test-channel\")\n
","boost":10},{"location":"getting-started/publishing/decorator/","title":"Publisher Decorator","text":"

The second easiest way to publish messages is by using the Publisher Decorator. This method has an AsyncAPI representation and is suitable for quickly creating applications. However, it doesn't provide all testing features.

It creates a structured DataPipeline unit with an input and output. The order of Subscriber and Publisher decorators doesn't matter, but @broker.publisher(...) can be used only with functions already decorated by a @broker.subscriber(...).

Note

It uses the handler function's return type annotation to cast the function's return value before sending, so be accurate with it.

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\n@broker.publisher(\"another-topic\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-topic\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", topic=\"test-topic\")\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\n@broker.publisher(\"another-queue\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-queue\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", queue=\"test-queue\")\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\n@broker.publisher(\"another-subject\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-subject\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", subject=\"test-subject\")\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\n@broker.publisher(\"another-channel\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-channel\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", channel=\"test-channel\")\n
","boost":10},{"location":"getting-started/publishing/decorator/#message-broadcasting","title":"Message Broadcasting","text":"

The decorator can be used multiple times with one function to broadcast the function's return:

@broker.subscriber(\"in\")\n@broker.publisher(\"first-out\")\n@broker.publisher(\"second-out\")\nasync def handle(msg) -> str:\n    return \"Response\"\n

This way you will send a copy of your return to the all output topics.

Note

Also, if this subscriber consumes a message with RPC mode, it sends a reply not only to the RPC channel but also to all publishers as well.

","boost":10},{"location":"getting-started/publishing/decorator/#details","title":"Details","text":"

Additionally, @broker.publisher(...) automatically sends a message with the same correlation_id as the incoming message. This way, you get the same correlation_id for the entire message pipeline process across all services, allowing you to collect a trace.

","boost":10},{"location":"getting-started/publishing/direct/","title":"Publisher Direct Usage","text":"

The Publisher Object provides a full-featured way to publish messages. It has an AsyncAPI representation and includes testability features.

This method creates a reusable Publisher object that can be used directly to publish a message:

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-topic\")\n\n@broker.subscriber(\"test-topic\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n\n\n@broker.subscriber(\"another-topic\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-queue\")\n\n@broker.subscriber(\"test-queue\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n\n\n@broker.subscriber(\"another-queue\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-subject\")\n\n@broker.subscriber(\"test-subject\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n\n\n@broker.subscriber(\"another-subject\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-channel\")\n\n@broker.subscriber(\"test-channel\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n\n\n@broker.subscriber(\"another-channel\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n

It is something in the middle between broker publish and object decorator. It has an AsyncAPI representation and testability features (like the object decorator), but allows you to send different messages to different outputs (like the broker publish).

@broker.subscriber(\"in\")\nasync def handle(msg) -> str:\n    await publisher1.publish(\"Response-1\")\n    await publisher2.publish(\"Response-2\")\n

Note

When using this method, FastStream doesn't reuse the incoming correlation_id to mark outgoing messages with it. You should set it manually if it is required.

","boost":10},{"location":"getting-started/publishing/object/","title":"Publisher Object","text":"

The Publisher Object provides a full-featured way to publish messages. It has an AsyncAPI representation and includes testability features. This method creates a reusable Publisher object.

Additionally, this object can be used as a decorator. The order of Subscriber and Publisher decorators doesn't matter, but @publisher can be used only with functions already decorated by a @broker.subscriber(...).

Note

It uses the handler function's return type annotation to cast the function's return value before sending, so be accurate with it.

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-topic\")\n\n@publisher\n@broker.subscriber(\"test-topic\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-topic\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-queue\")\n\n@publisher\n@broker.subscriber(\"test-queue\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-queue\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-subject\")\n\n@publisher\n@broker.subscriber(\"test-subject\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-subject\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\npublisher = broker.publisher(\"another-channel\")\n\n@publisher\n@broker.subscriber(\"test-channel\")\nasync def handle() -> str:\n    return \"Hi!\"\n\n\n@broker.subscriber(\"another-channel\")\nasync def handle_next(msg: str):\n    assert msg == \"Hi!\"\n
","boost":10},{"location":"getting-started/publishing/object/#message-broadcasting","title":"Message Broadcasting","text":"

The decorator can be used multiple times with one function to broadcast the function's return:

@publisher1\n@publisher2\n@broker.subscriber(\"in\")\nasync def handle(msg) -> str:\n    return \"Response\"\n

This way, you will send a copy of your return to all output topics.

Note

Also, if this subscriber consumes a message with RPC mode, it sends a reply not only to the RPC channel but also to all publishers as well.

","boost":10},{"location":"getting-started/publishing/object/#details","title":"Details","text":"

Additionally, @publisher automatically sends a message with the same correlation_id as the incoming message. This way, you get the same correlation_id for the entire message pipeline process across all services, allowing you to collect a trace.

","boost":10},{"location":"getting-started/publishing/test/","title":"Publisher Testing","text":"

If you are working with a Publisher object (either as a decorator or directly), you have several testing features available:

","boost":10},{"location":"getting-started/publishing/test/#base-application","title":"Base Application","text":"

Let's take a look at a simple application example with a publisher as a decorator or as a direct call:

DecoratorDirect KafkaRabbitMQNATSRedis
publisher = broker.publisher(\"another-topic\")\n\n@publisher\n@broker.subscriber(\"test-topic\")\nasync def handle() -> str:\n    return \"Hi!\"\n
publisher = broker.publisher(\"another-queue\")\n\n@publisher\n@broker.subscriber(\"test-queue\")\nasync def handle() -> str:\n    return \"Hi!\"\n
publisher = broker.publisher(\"another-subject\")\n\n@publisher\n@broker.subscriber(\"test-subject\")\nasync def handle() -> str:\n    return \"Hi!\"\n
publisher = broker.publisher(\"another-channel\")\n\n@publisher\n@broker.subscriber(\"test-channel\")\nasync def handle() -> str:\n    return \"Hi!\"\n
KafkaRabbitMQNATSRedis
publisher = broker.publisher(\"another-topic\")\n\n@broker.subscriber(\"test-topic\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n
publisher = broker.publisher(\"another-queue\")\n\n@broker.subscriber(\"test-queue\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n
publisher = broker.publisher(\"another-subject\")\n\n@broker.subscriber(\"test-subject\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n
publisher = broker.publisher(\"another-channel\")\n\n@broker.subscriber(\"test-channel\")\nasync def handle():\n    await publisher.publish(\"Hi!\")\n
","boost":10},{"location":"getting-started/publishing/test/#testing","title":"Testing","text":"

To test it, you just need to patch your broker with a special TestBroker.

KafkaRabbitMQNATSRedis
import pytest\n\nfrom faststream.kafka import TestKafkaBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestKafkaBroker(broker) as br:\n        await br.publish(\"\", topic=\"test-topic\")\n
import pytest\n\nfrom faststream.rabbit import TestRabbitBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRabbitBroker(broker) as br:\n        await br.publish(\"\", queue=\"test-queue\")\n
import pytest\n\nfrom faststream.nats import TestNatsBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestNatsBroker(broker) as br:\n        await br.publish(\"\", subject=\"test-subject\")\n
import pytest\n\nfrom faststream.redis import TestRedisBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRedisBroker(broker) as br:\n        await br.publish(\"\", channel=\"test-channel\")\n

By default, it patches you broker to run In-Memory, so you can use it without any external broker. It should be extremely usefull in your CI or local development environment.

Also, it allows you to check the outgoing message body in the same way as with a subscriber.

publisher.mock.assert_called_once_with(\"Hi!\")\n

Note

The Publisher mock contains not just a publish method input value. It sets up a virtual consumer for an outgoing topic, consumes a message, and stores this consumed one.

Additionally, TestBroker can be used with a real external broker to make your tests end-to-end suitable. For more information, please visit the subscriber testing page.

","boost":10},{"location":"getting-started/routers/","title":"Broker Router","text":"

Sometimes you want to:

For these reasons, FastStream has a special Broker Router.

","boost":10},{"location":"getting-started/routers/#router-usage","title":"Router Usage","text":"

First, you need to import the Broker Router from the same module from where you imported the broker.

When creating a Broker Router, you can specify a prefix that will be automatically applied to all subscribers and publishers of this router.

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaRouter\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\nrouter = KafkaRouter(prefix=\"prefix_\")\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker, RabbitRouter\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\nrouter = RabbitRouter(prefix=\"prefix_\")\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker, NatsRouter\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\nrouter = NatsRouter(prefix=\"prefix_\")\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker, RedisRouter\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\nrouter = RedisRouter(prefix=\"prefix_\")\n

Now you can use the created router to register handlers and publishers as if it were a regular broker

KafkaRabbitMQNATSRedis
@router.subscriber(\"test-topic\")\n@router.publisher(\"another-topic\")\nasync def handle(name: str, user_id: int) -> str:\n    assert name == \"John\"\n    assert user_id == 1\n    return \"Hi!\"\n\n\n@router.subscriber(\"another-topic\")\nasync def handle_response(msg: str):\n    assert msg == \"Hi!\"\n
@router.subscriber(\"test-queue\")\n@router.publisher(\"another-queue\")\nasync def handle(name: str, user_id: int) -> str:\n    assert name == \"John\"\n    assert user_id == 1\n    return \"Hi!\"\n\n\n@router.subscriber(\"another-queue\")\nasync def handle_response(msg: str):\n    assert msg == \"Hi!\"\n
@router.subscriber(\"test-subject\")\n@router.publisher(\"another-subject\")\nasync def handle(name: str, user_id: int) -> str:\n    assert name == \"John\"\n    assert user_id == 1\n    return \"Hi!\"\n\n\n@router.subscriber(\"another-subject\")\nasync def handle_response(msg: str):\n    assert msg == \"Hi!\"\n
@router.subscriber(\"test-channel\")\n@router.publisher(\"another-channel\")\nasync def handle(name: str, user_id: int) -> str:\n    assert name == \"John\"\n    assert user_id == 1\n    return \"Hi!\"\n\n\n@router.subscriber(\"another-channel\")\nasync def handle_response(msg: str):\n    assert msg == \"Hi!\"\n

Then you can simply include all the handlers declared using the router in your broker

broker.include_router(router)\n

Please note that when publishing a message, you now need to specify the same prefix that you used when creating the router

KafkaRabbitMQNATSRedis
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    topic=\"prefix_test-topic\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    queue=\"prefix_test-queue\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    subject=\"prefix_test-subject\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    channel=\"prefix_test-channel\",\n)\n

Tip

Also, when creating a Broker Router, you can specify middleware, dependencies, parser and decoder to apply them to all subscribers declared via this router.

","boost":10},{"location":"getting-started/routers/#delay-handler-registration","title":"Delay Handler Registration","text":"

If you want to separate your application's core logic from FastStream's routing logic, you can write some core functions and use them as Broker Router handlers later:

KafkaRabbitMQNATSRedis
from faststream.kafka import KafkaRoute, KafkaRouter\n\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\nrouter = KafkaRouter(\n    handlers=(\n        KafkaRoute(handle, \"test-topic\"),\n    )\n)\n
from faststream.rabbit import RabbitRoute, RabbitRouter\n\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\nrouter = RabbitRouter(\n    handlers=(\n        RabbitRoute(handle, \"test-queue\"),\n    )\n)\n
from faststream.nats import NatsRoute, NatsRouter\n\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\nrouter = NatsRouter(\n    handlers=(\n        NatsRoute(handle, \"test-subject\"),\n    )\n)\n
from faststream.redis import RedisRouter, RedisRoute\n\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\nrouter = RedisRouter(\n    handlers=(\n        RedisRoute(handle, \"test-channel\"),\n    )\n)\n

Warning

Be careful, this way you won't be able to test your handlers with a mock object.

","boost":10},{"location":"getting-started/serialization/","title":"Custom Serialization","text":"

By default, FastStream uses the JSON format to send and receive messages. However, if you need to handle messages in other formats or with additional serialization steps, such as gzip, lz4, Avro, Protobuf or Msgpack, you can easily modify the serialization logic.

","boost":10},{"location":"getting-started/serialization/#serialization-steps","title":"Serialization Steps","text":"

Before the message reaches your subscriber, FastStream applies two functions to it sequentially: parse_message and decode_message. You can modify one or both stages depending on your needs.

","boost":10},{"location":"getting-started/serialization/#message-parsing","title":"Message Parsing","text":"

At this stage, FastStream serializes an incoming message from the broker's framework into a general format called - StreamMessage. During this stage, the message body remains in the form of raw bytes.

This stage is closely related to the features of the broker used, and in most cases, redefining it is not necessary.

The parser declared at the broker level will be applied to all subscribers. The parser declared at the subscriber level is applied only to that specific subscriber and overrides the `broker' parser if specified.

","boost":10},{"location":"getting-started/serialization/#message-decoding","title":"Message Decoding","text":"

At this stage, the body of the StreamMessage is transformed into a format suitable for processing within your subscriber function. This is the stage you may need to redefine more often.

","boost":10},{"location":"getting-started/serialization/decoder/","title":"Custom Decoder","text":"

At this stage, the body of a StreamMessage is transformed into the format that it will take when it enters your handler function. This stage is the one you will need to redefine more often.

","boost":10},{"location":"getting-started/serialization/decoder/#signature","title":"Signature","text":"

The original decoder function has a relatively simple signature (this is a simplified version):

KafkaRabbitMQNATSRedis
from faststream.types import DecodedMessage\nfrom faststream.kafka import KafkaMessage\n\ndef decoder(msg: KafkaMessage) -> DecodedMessage:\n    ...\n
from faststream.types import DecodedMessage\nfrom faststream.rabbit import RabbitMessage\n\ndef decoder(msg: RabbitMessage) -> DecodedMessage:\n    ...\n
from faststream.types import DecodedMessage\nfrom faststream.nats import NatsMessage\n\ndef decoder(msg: NatsMessage) -> DecodedMessage:\n    ...\n
from faststream.types import DecodedMessage\nfrom faststream.redis import RedisMessage\n\ndef decoder(msg: RedisMessage) -> DecodedMessage:\n    ...\n

Alternatively, you can reuse the original decoder function with the following signature:

KafkaRabbitMQNATSRedis
from types import Callable, Awaitable\nfrom faststream.types import DecodedMessage\nfrom faststream.kafka import KafkaMessage\n\nasync def decoder(\n    msg: KafkaMessage,\n    original_decoder: Callable[[KafkaMessage], Awaitable[DecodedMessage]],\n) -> DecodedMessage:\n    return await original_decoder(msg)\n
from types import Callable, Awaitable\nfrom faststream.types import DecodedMessage\nfrom faststream.rabbit import RabbitMessage\n\nasync def decoder(\n    msg: RabbitMessage,\n    original_decoder: Callable[[RabbitMessage], Awaitable[DecodedMessage]],\n) -> DecodedMessage:\n    return await original_decoder(msg)\n
from types import Callable, Awaitable\nfrom faststream.types import DecodedMessage\nfrom faststream.nats import NatsMessage\n\nasync def decoder(\n    msg: NatsMessage,\n    original_decoder: Callable[[NatsMessage], Awaitable[DecodedMessage]],\n) -> DecodedMessage:\n    return await original_decoder(msg)\n
from types import Callable, Awaitable\nfrom faststream.types import DecodedMessage\nfrom faststream.redis import RedisMessage\n\nasync def decoder(\n    msg: RedisMessage,\n    original_decoder: Callable[[RedisMessage], Awaitable[DecodedMessage]],\n) -> DecodedMessage:\n    return await original_decoder(msg)\n

Note

The original decoder is always an asynchronous function, so your custom decoder should also be asynchronous.

Afterward, you can set this custom decoder at the broker or subscriber level.

","boost":10},{"location":"getting-started/serialization/decoder/#example","title":"Example","text":"

You can find examples of Protobuf, Msgpack and Avro serialization in the next article.

","boost":10},{"location":"getting-started/serialization/examples/","title":"Serialization examples","text":"","boost":10},{"location":"getting-started/serialization/examples/#protobuf","title":"Protobuf","text":"

In this section, we will explore an example using Protobuf. However, this approach is also applicable to other serialization methods.

Protobuf

Protobuf is an alternative message serialization method commonly used in GRPC. Its main advantage is that it results in much smaller message sizes1 compared to JSON, but it requires a message schema (.proto files) on both the client and server sides.

To begin, install the necessary dependencies:

pip install grpcio-tools\n

Next, let's define the schema for our message:

message.proto
syntax = \"proto3\";\n\nmessage Person {\n    string name = 1;\n    float age = 2;\n}\n

Now, generate a Python class to work with messages in Protobuf format:

python -m grpc_tools.protoc --python_out=. --pyi_out=. -I . message.proto\n

This generates two files: message_pb2.py and message_pb2.pyi. We can use the generated class to serialize our messages:

from message_pb2 import Person\n\nfrom faststream import FastStream, Logger, NoCast\nfrom faststream.rabbit import RabbitBroker, RabbitMessage\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\n\nasync def decode_message(msg: RabbitMessage) -> Person:\n    decoded = Person()\n    decoded.ParseFromString(msg.body)\n    return decoded\n\n\n@broker.subscriber(\"test\", decoder=decode_message)\nasync def consume(body: NoCast[Person], logger: Logger):\n    logger.info(body)\n\n\n@app.after_startup\nasync def publish():\n    body = Person(name=\"John\", age=25).SerializeToString()\n    await broker.publish(body, \"test\")\n

Note that we used the NoCast annotation to exclude the message from the pydantic representation of our handler.

async def consume(body: NoCast[Person], logger: Logger):\n
","boost":10},{"location":"getting-started/serialization/examples/#msgpack","title":"Msgpack","text":"

Msgpack is another alternative binary data format. Its main advantage is that it results in smaller message sizes2 compared to JSON, although slightly larger than Protobuf. The key advantage is that it doesn't require a message schema, making it easy to use in most cases.

To get started, install the necessary dependencies:

pip install msgpack\n

Since there is no need for a schema, you can easily write a Msgpack decoder:

import msgpack\n\nfrom faststream import FastStream, Logger\nfrom faststream.rabbit import RabbitBroker, RabbitMessage\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\n\nasync def decode_message(msg: RabbitMessage):\n    return msgpack.loads(msg.body)\n\n\n@broker.subscriber(\"test\", decoder=decode_message)\nasync def consume(name: str, age: int, logger: Logger):\n    logger.info(f\"{name}: {age}\")\n\n\n@app.after_startup\nasync def publish():\n    body = msgpack.dumps({\"name\": \"John\", \"age\": 25}, use_bin_type=True)\n    await broker.publish(body, \"test\")\n

Using Msgpack is much simpler than using Protobuf schemas. Therefore, if you don't have strict message size limitations, you can use Msgpack serialization in most cases.

","boost":10},{"location":"getting-started/serialization/examples/#avro","title":"Avro","text":"

In this section, let's explore how to use Avro encoding and decoding to encode/decode our messages as part of FastStream.

Avro

Apache Avro uses JSON to define data types and protocols and serializes data in a compact binary format. Avro utilizes a schema to structure the data that is being encoded. Schemas are composed of primitive types (null, boolean, int, long, float, double, bytes, and string) and complex types (record, enum, array, map, union, and fixed).

To get started, install the necessary dependencies:

pip install fastavro\n

Next, let's define the schema for our message. You can either define it in the Python file itself as:

person_schema = {\n    \"type\": \"record\",\n    \"namespace\": \"Person\",\n    \"name\": \"Person\",\n    \"fields\": [\n        {\"doc\": \"Name\", \"type\": \"string\", \"name\": \"name\"},\n        {\"doc\": \"Age\", \"type\": \"int\", \"name\": \"age\"},\n    ],\n}\n

Or you can load the schema from an avsc file as:

person_schema = fastavro.schema.load_schema(\"person.avsc\")\n

The contents of the person.avsc file are:

person.avsc
{\n    \"type\": \"record\",\n    \"namespace\": \"Person\",\n    \"name\": \"Person\",\n    \"fields\": [\n        {\"doc\": \"Name\", \"type\": \"string\", \"name\": \"name\"},\n        {\"doc\": \"Age\", \"type\": \"int\", \"name\": \"age\"}\n    ]\n}\n

Finally, let's use Avro's schemaless_reader and schemaless_writer to decode and encode messages in the FastStream app.

import io\n\nimport fastavro\n\nfrom faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker, KafkaMessage\n\nbroker = KafkaBroker()\napp = FastStream(broker)\n\n\n# person_schema = ...\nschema = fastavro.schema.parse_schema(person_schema)\n\nasync def decode_message(msg: KafkaMessage):\n    bytes_reader = io.BytesIO(msg.body)\n    msg_dict = fastavro.schemaless_reader(bytes_reader, schema)\n    return msg_dict\n\n\n@broker.subscriber(\"test\", decoder=decode_message)\nasync def consume(name: str, age: int, logger: Logger):\n    logger.info(f\"{name}: {age}\")\n\n\n@app.after_startup\nasync def publish():\n    msg = {\"name\": \"John\", \"age\": 25}\n\n    bytes_writer = io.BytesIO()\n    fastavro.schemaless_writer(bytes_writer, schema, msg)\n    raw_bytes = bytes_writer.getvalue()\n\n    await broker.publish(raw_bytes, \"test\")\n
","boost":10},{"location":"getting-started/serialization/examples/#tips","title":"Tips","text":"","boost":10},{"location":"getting-started/serialization/examples/#data-compression","title":"Data Compression","text":"

If you are dealing with very large messages, consider compressing them as well. You can explore libraries such as lz4 or zstd for compression algorithms.

Compression can significantly reduce message size, especially if there are repeated blocks. However, in the case of small message bodies, data compression may increase the message size. Therefore, you should assess the compression impact based on your specific application requirements.

","boost":10},{"location":"getting-started/serialization/examples/#broker-level-serialization","title":"Broker-Level Serialization","text":"

You can still set a custom decoder at the Broker or Router level. However, if you want to automatically encode publishing messages as well, you should explore Middleware for serialization implimentation.

  1. For example, a message like { \"name\": \"John\", \"age\": 25 } in JSON takes 27 bytes, while in Protobuf, it takes only 11 bytes. With lists and more complex structures, the savings can be even more significant (up to 20x times).\u00a0\u21a9

  2. A message with Msgpack serialization, such as { \"name\": \"John\", \"age\": 25 }, takes 16 bytes.\u00a0\u21a9

","boost":10},{"location":"getting-started/serialization/parser/","title":"Custom Parser","text":"

At this stage, FastStream serializes an incoming message from the broker's framework into a general format called StreamMessage. During this stage, the message body remains in the form of raw bytes.

StreamMessage is a general representation of a message within FastStream. It contains all the information required for message processing within FastStreams. It is even used to represent message batches, so the primary reason to customize it is to redefine the metadata associated with FastStream messages.

For example, you can specify your own header with the message_id semantic. This allows you to inform FastStream about this custom header through parser customization.

","boost":10},{"location":"getting-started/serialization/parser/#signature","title":"Signature","text":"

To create a custom message parser, you should write a regular Python function (synchronous or asynchronous) with the following signature:

KafkaRabbitMQNATSRedis
from aiokafka import ConsumerRecord\nfrom faststream.kafka import KafkaMessage\n\ndef parser(msg: ConsumerRecord) -> KafkaMessage:\n    ...\n
from aio_pika import IncomingMessage\nfrom faststream.rabbit import RabbitMessage\n\ndef parser(msg: IncomingMessage) -> RabbitMessage:\n    ...\n
from nats.aio.msg import Msg\nfrom faststream.nats import NatsMessage\n\ndef parser(msg: Msg) -> NatsMessage:\n    ...\n
from faststream.redis import RedisMessage\nfrom faststream.redis.message import PubSubMessage\n\ndef parser(msg: PubSubMessage) -> RedisMessage:\n    ...\n

Alternatively, you can reuse the original parser function with the following signature:

KafkaRabbitMQNATSRedis
from types import Callable, Awaitable\nfrom aiokafka import ConsumerRecord\nfrom faststream.kafka import KafkaMessage\n\nasync def parser(\n    msg: ConsumerRecord,\n    original_parser: Callable[[ConsumerRecord], Awaitable[KafkaMessage]],\n) -> KafkaMessage:\n    return await original_parser(msg)\n
from types import Callable, Awaitable\nfrom aio_pika import IncomingMessage\nfrom faststream.rabbit import RabbitMessage\n\nasync def parser(\n    msg: IncomingMessage,\n    original_parser: Callable[[IncomingMessage], Awaitable[RabbitMessage]],\n) -> RabbitMessage:\n    return await original_parser(msg)\n
from types import Callable, Awaitable\nfrom nats.aio.msg import Msg\nfrom faststream.nats import NatsMessage\n\nasync def parser(\n    msg: Msg,\n    original_parser: Callable[[Msg], Awaitable[NatsMessage]],\n) -> NatsMessage:\n    return await original_parser(msg)\n
from types import Callable, Awaitable\nfrom faststream.redis import RedisMessage\nfrom faststream.redis.message import PubSubMessage\n\nasync def parser(\n    msg: PubSubMessage,\n    original_parser: Callable[[PubSubMessage], Awaitable[RedisMessage]],\n) -> RedisMessage:\n    return await original_parser(msg)\n

The argument naming doesn't matter; the parser will always be placed as the second argument.

Note

The original parser is always an asynchronous function, so your custom parser should also be asynchronous.

Afterward, you can set this custom parser at the broker or subscriber level.

","boost":10},{"location":"getting-started/serialization/parser/#example","title":"Example","text":"

As an example, let's redefine message_id to a custom header:

KafkaRabbitMQNATSRedis
from typing import Awaitable, Callable\n\nfrom aiokafka import ConsumerRecord\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker, KafkaMessage\n\n\nasync def custom_parser(\n    msg: ConsumerRecord,\n    original_parser: Callable[[ConsumerRecord], Awaitable[KafkaMessage]],\n) -> KafkaMessage:\n    parsed_msg = await original_parser(msg)\n    parsed_msg.message_id = parsed_msg.headers[\"custom_message_id\"]\n    return parsed_msg\n\n\nbroker = KafkaBroker(parser=custom_parser)\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def handle():\n    ...\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", \"test\", headers={\"custom_message_id\": \"1\"})\n
from typing import Awaitable, Callable\n\nfrom aio_pika import IncomingMessage\n\nfrom faststream import FastStream\nfrom faststream.rabbit import RabbitBroker, RabbitMessage\n\n\nasync def custom_parser(\n    msg: IncomingMessage,\n    original_parser: Callable[[IncomingMessage], Awaitable[RabbitMessage]],\n) -> RabbitMessage:\n    parsed_msg = await original_parser(msg)\n    parsed_msg.message_id = parsed_msg.headers[\"custom_message_id\"]\n    return parsed_msg\n\n\nbroker = RabbitBroker(parser=custom_parser)\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def handle():\n    ...\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", \"test\", headers={\"custom_message_id\": \"1\"})\n
from typing import Awaitable, Callable\n\nfrom nats.aio.msg import Msg\n\nfrom faststream import FastStream\nfrom faststream.nats import NatsBroker, NatsMessage\n\n\nasync def custom_parser(\n    msg: Msg,\n    original_parser: Callable[[Msg], Awaitable[NatsMessage]],\n) -> NatsMessage:\n    parsed_msg = await original_parser(msg)\n    parsed_msg.message_id = parsed_msg.headers[\"custom_message_id\"]\n    return parsed_msg\n\n\nbroker = NatsBroker(parser=custom_parser)\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def handle():\n    ...\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", \"test\", headers={\"custom_message_id\": \"1\"})\n
from typing import Awaitable, Callable\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker, RedisMessage\nfrom faststream.redis.message import PubSubMessage\n\n\nasync def custom_parser(\n    msg: PubSubMessage,\n    original_parser: Callable[[PubSubMessage], Awaitable[RedisMessage]],\n) -> RedisMessage:\n    parsed_msg = await original_parser(msg)\n    parsed_msg.message_id = parsed_msg.headers[\"custom_message_id\"]\n    return parsed_msg\n\n\nbroker = RedisBroker(parser=custom_parser)\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def handle():\n    ...\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"\", \"test\", headers={\"custom_message_id\": \"1\"})\n
","boost":10},{"location":"getting-started/subscription/","title":"Subscription Basics","text":"

FastStream provides a Message Broker agnostic way to subscribe to event streams.

You need not even know about topics/queues/subjects or any broker inner objects you use. The basic syntax is the same for all brokers:

KafkaRabbitMQNATSRedis
from faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker()\n\n@broker.subscriber(\"test\")  # topic name\nasync def handle_msg(msg_body):\n    ...\n
from faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker()\n\n@broker.subscriber(\"test\")  # queue name\nasync def handle_msg(msg_body):\n    ...\n
from faststream.nats import NatsBroker\n\nbroker = NatsBroker()\n\n@broker.subscriber(\"test\")  # subject name\nasync def handle_msg(msg_body):\n    ...\n
from faststream.redis import RedisBroker\n\nbroker = RedisBroker()\n\n@broker.subscriber(\"test\")  # channel name\nasync def handle_msg(msg_body):\n    ...\n

Tip

If you want to use Message Broker specific features, please visit the corresponding broker documentation section. In the Tutorial section, the general features are described.

Also, synchronous functions are supported as well:

KafkaRabbitMQNATSRedis
from faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker()\n\n@broker.subscriber(\"test\")  # topic name\ndef handle_msg(msg_body):\n    ...\n
from faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker()\n\n@broker.subscriber(\"test\")  # queue name\ndef handle_msg(msg_body):\n    ...\n
from faststream.nats import NatsBroker\n\nbroker = NatsBroker()\n\n@broker.subscriber(\"test\")  # subject name\ndef handle_msg(msg_body):\n    ...\n
from faststream.redis import RedisBroker\n\nbroker = RedisBroker()\n\n@broker.subscriber(\"test\")  # channel name\ndef handle_msg(msg_body):\n    ...\n
","boost":10},{"location":"getting-started/subscription/#message-body-serialization","title":"Message Body Serialization","text":"

Generally, FastStream uses your function type annotation to serialize incoming message body with Pydantic. This is similar to how FastAPI works (if you are familiar with it).

@broker.subscriber(\"test\")\nasync def handle_str(\n    msg_body: str,\n):\n    ...\n

You can also access some extra features through the function arguments, such as Depends and Context if required.

However, you can easily disable Pydantic validation by creating a broker with the following option Broker(apply_types=False) (this also disables Context and Depends features).

This way FastStream still consumes json.loads result, but without pydantic validation and casting.

KafkaRabbitMQNATSRedis
from faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(apply_types=False)\n\n@broker.subscriber(\"test\")\nasync def handle_msg(msg_body: str):  # just an annotation, has no real effect\n    ...\n
from faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(apply_types=False)\n\n@broker.subscriber(\"test\")\nasync def handle_msg(msg_body: str):  # just an annotation, has no real effect\n    ...\n
from faststream.nats import NatsBroker\n\nbroker = NatsBroker(apply_types=False)\n\n@broker.subscriber(\"test\")\nasync def handle_msg(msg_body: str):  # just an annotation, has no real effect\n    ...\n
from faststream.redis import RedisBroker\n\nbroker = RedisBroker(apply_types=False)\n\n@broker.subscriber(\"test\")\nasync def handle_msg(msg_body: str):  # just an annotation, has no real effect\n    ...\n
","boost":10},{"location":"getting-started/subscription/#multiple-subscriptions","title":"Multiple Subscriptions","text":"

You can also subscribe to multiple event streams at the same time with one function. Just wrap it with multiple @broker.subscriber(...) decorators (they have no effect on each other).

@broker.subscriber(\"first_sub\")\n@broker.subscriber(\"second_sub\")\nasync def handler(msg):\n    ...\n
","boost":10},{"location":"getting-started/subscription/annotation/","title":"Annotation Serialization","text":"","boost":10},{"location":"getting-started/subscription/annotation/#basic-usage","title":"Basic usage","text":"

As you already know, FastStream serializes your incoming message body according to the function type annotations using Pydantic.

So, there are some valid usecases:

@broker.subscriber(\"test\")\nasync def handle(\n    msg: str,\n):\n    ...\n\n@broker.subscriber(\"test\")\nasync def handle(\n    msg: bytes,\n):\n    ...\n\n@broker.subscriber(\"test\")\nasync def handle(\n    msg: int,\n):\n    ...\n

As with other Python primitive types as well (float, bool, datetime, etc)

Note

If the incoming message cannot be serialized by the described schema, FastStream raises a pydantic.ValidationError with a correct log message.

Also, thanks to Pydantic (again), FastStream is able to serialize (and validate) more complex types like pydantic.HttpUrl, pydantic.PostitiveInt, etc.

","boost":10},{"location":"getting-started/subscription/annotation/#json-basic-serialization","title":"JSON Basic Serialization","text":"

But how can we serialize more complex message, like { \"name\": \"John\", \"user_id\": 1 } ?

For sure, we can serialize it as a simple dict

from typing import Dict, Any\n\n@broker.subscriber(\"test\")\nasync def handle(\n    msg: dict[str, Any],\n):\n    ...\n

But it doesn't looks like a correct message validation, does it?

For this reason, FastStream supports per-argument message serialization: you can declare multiple arguments with various types and your message will unpack to them:

KafkaRabbitMQNATSRedis
@broker.subscriber(\"test-topic\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
@broker.subscriber(\"test-queue\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
@broker.subscriber(\"test-subject\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
@broker.subscriber(\"test-channel\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
","boost":10},{"location":"getting-started/subscription/filtering/","title":"Application-level Filtering","text":"

FastStream also allows you to specify the message processing way using message headers, body type or something else. The filter feature enables you to consume various messages with different schemas within a single event stream.

Tip

Message must be consumed at ONCE (crossing filters are not allowed)

As an example, let's create a subscriber for both JSON and non-JSON messages:

KafkaRabbitMQNATSRedis
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    \"test-topic\",\n    filter=lambda msg: msg.content_type == \"application/json\",\n)\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\n\n@broker.subscriber(\"test-topic\")\nasync def default_handler(msg: str):\n    assert msg == \"Hello, FastStream!\"\n
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    \"test-queue\",\n    filter=lambda msg: msg.content_type == \"application/json\",\n)\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\n\n@broker.subscriber(\"test-queue\")\nasync def default_handler(msg: str):\n    assert msg == \"Hello, FastStream!\"\n
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    \"test-subject\",\n    filter=lambda msg: msg.content_type == \"application/json\",\n)\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\n\n@broker.subscriber(\"test-subject\")\nasync def default_handler(msg: str):\n    assert msg == \"Hello, FastStream!\"\n
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    \"test-channel\",\n    filter=lambda msg: msg.content_type == \"application/json\",\n)\nasync def handle(name: str, user_id: int):\n    assert name == \"John\"\n    assert user_id == 1\n\n\n@broker.subscriber(\"test-channel\")\nasync def default_handler(msg: str):\n    assert msg == \"Hello, FastStream!\"\n

Note

A subscriber without a filter is a default subscriber. It consumes messages that have not been consumed yet.

For now, the following message will be delivered to the handle function

KafkaRabbitMQNATSRedis
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    topic=\"test-topic\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    queue=\"test-queue\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    subject=\"test-subject\",\n)\n
await broker.publish(\n    {\"name\": \"John\", \"user_id\": 1},\n    channel=\"test-channel\",\n)\n

And this one will be delivered to the default_handler

KafkaRabbitMQNATSRedis
await broker.publish(\n    \"Hello, FastStream!\",\n    topic=\"test-topic\",\n)\n
await broker.publish(\n    \"Hello, FastStream!\",\n    queue=\"test-queue\",\n)\n
await broker.publish(\n    \"Hello, FastStream!\",\n    subject=\"test-subject\",\n)\n
await broker.publish(\n    \"Hello, FastStream!\",\n    channel=\"test-channel\",\n)\n
","boost":10},{"location":"getting-started/subscription/pydantic/","title":"Pydantic Serialization","text":"","boost":10},{"location":"getting-started/subscription/pydantic/#pydanticfield","title":"pydantic.Field","text":"

Besides, FastStream uses your handlers' annotations to collect information about the application schema and generate AsyncAPI schema.

You can access this information with extra details using pydantic.Field (such as title, description and examples). Additionally, Fields usage allows you to add extra validations to your message schema.

Just use pydantic.Field as a function default argument:

KafkaRabbitMQNATSRedis
from pydantic import Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    ),\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    ),\n):\n    assert name == \"John\"\n    assert user_id == 1\n
from pydantic import Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    ),\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    ),\n):\n    assert name == \"John\"\n    assert user_id == 1\n
from pydantic import Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    ),\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    ),\n):\n    assert name == \"John\"\n    assert user_id == 1\n
from pydantic import Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    ),\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    ),\n):\n    assert name == \"John\"\n    assert user_id == 1\n

Tip

Also you can use typing.Annotated (python 3.9+) or typing_extensions.Annotated to declare your handler fields

name: Annotated[\n    str,\n    Field(..., examples=[\"John\"], description=\"Registered user name\")\n],\nuser_id: Annotated[\n    NonNegativeInt,\n    Field(..., examples=[1], description=\"Registered user id\"),\n]\n
","boost":10},{"location":"getting-started/subscription/pydantic/#pydanticbasemodel","title":"pydantic.BaseModel","text":"

To make your message schema reusable between different subscribers and publishers, you can decalre it as a pydantic.BaseModel and use it as a single message annotation:

KafkaRabbitMQNATSRedis
from pydantic import BaseModel, Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\nclass UserInfo(BaseModel):\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    )\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    )\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    user: UserInfo,\n):\n    assert user.name == \"John\"\n    assert user.user_id == 1\n
from pydantic import BaseModel, Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\nclass UserInfo(BaseModel):\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    )\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    )\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    user: UserInfo,\n):\n    assert user.name == \"John\"\n    assert user.user_id == 1\n
from pydantic import BaseModel, Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\nclass UserInfo(BaseModel):\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    )\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    )\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    user: UserInfo,\n):\n    assert user.name == \"John\"\n    assert user.user_id == 1\n
from pydantic import BaseModel, Field, NonNegativeInt\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\nclass UserInfo(BaseModel):\n    name: str = Field(\n        ..., examples=[\"John\"], description=\"Registered user name\"\n    )\n    user_id: NonNegativeInt = Field(\n        ..., examples=[1], description=\"Registered user id\"\n    )\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    user: UserInfo,\n):\n    assert user.name == \"John\"\n    assert user.user_id == 1\n
","boost":10},{"location":"getting-started/subscription/test/","title":"Subscriber Testing","text":"

Testability is a crucial part of any application, and FastStream provides you with the tools to test your code easily.

","boost":10},{"location":"getting-started/subscription/test/#original-application","title":"Original Application","text":"

Let's take a look at the original application to test

KafkaRabbitMQNATSRedis annotation_kafka.py
from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-topic\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
annotation_rabbit.py
from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
annotation_nats.py
from faststream import FastStream\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n
annotation_redis.py
from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-channel\")\nasync def handle(\n    name: str,\n    user_id: int,\n):\n    assert name == \"John\"\n    assert user_id == 1\n

It consumes JSON messages like { \"name\": \"username\", \"user_id\": 1 }

You can test your consume function like a regular one, for sure:

@pytest.mark.asyncio\nasync def test_handler():\n    await handle(\"John\", 1)\n

But if you want to test your function closer to your real runtime, you should use the special FastStream test client.

","boost":10},{"location":"getting-started/subscription/test/#in-memory-testing","title":"In-Memory Testing","text":"

Deploying a whole service with a Message Broker is a bit too much just for testing purposes, especially in your CI environment. Not to mention the possible loss of messages due to network failures when working with real brokers.

For this reason, FastStream has a special TestClient to make your broker work in InMemory mode.

Just use it like a regular async context manager - all published messages will be routed in-memory (without any external dependencies) and consumed by the correct handler.

KafkaRabbitMQNATSRedis
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.kafka import TestKafkaBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestKafkaBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, topic=\"test-topic\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.rabbit import TestRabbitBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRabbitBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, queue=\"test-queue\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.nats import TestNatsBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestNatsBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, subject=\"test-subject\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.redis import TestRedisBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRedisBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, channel=\"test-channel\")\n
","boost":10},{"location":"getting-started/subscription/test/#catching-exceptions","title":"Catching Exceptions","text":"

This way you can catch any exceptions that occur inside your handler:

KafkaRabbitMQNATSRedis
@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestKafkaBroker(broker) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", topic=\"test-topic\")\n
@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestRabbitBroker(broker) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", queue=\"test-queue\")\n
@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestNatsBroker(broker) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", subject=\"test-subject\")\n
@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestRedisBroker(broker) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", channel=\"test-channel\")\n
","boost":10},{"location":"getting-started/subscription/test/#validates-input","title":"Validates Input","text":"

Also, your handler has a mock object to validate your input or call counts.

KafkaRabbitMQNATSRedis
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestKafkaBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, topic=\"test-topic\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRabbitBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, queue=\"test-queue\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestNatsBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, subject=\"test-subject\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRedisBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, channel=\"test-channel\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n

Note

The Handler mock has a not-serialized JSON message body. This way you can validate the incoming message view, not python arguments.

Thus our example checks not mock.assert_called_with(name=\"John\", user_id=1), but mock.assert_called_with({ \"name\": \"John\", \"user_id\": 1 }).

You should be careful with this feature: all mock objects will be cleared when the context manager exits.

KafkaRabbitMQNATSRedis
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestKafkaBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, topic=\"test-topic\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRabbitBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, queue=\"test-queue\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestNatsBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, subject=\"test-subject\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n
@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRedisBroker(broker) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, channel=\"test-channel\")\n\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n
","boost":10},{"location":"getting-started/subscription/test/#real-broker-testing","title":"Real Broker Testing","text":"

If you want to test your application in a real environment, you shouldn't have to rewrite all your tests: just pass with_real optional parameter to your TestClient context manager. This way, TestClient supports all the testing features but uses an unpatched broker to send and consume messages.

KafkaRabbitMQNATSRedis
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.kafka import TestKafkaBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestKafkaBroker(broker, with_real=True) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, topic=\"test-topic\")\n        await handle.wait_call(timeout=3)\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n\n@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestKafkaBroker(broker, with_real=True) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", topic=\"test-topic\")\n            await handle.wait_call(timeout=3)\n\n        handle.mock.assert_called_once_with(\"wrong message\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.rabbit import TestRabbitBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRabbitBroker(broker, with_real=True) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, queue=\"test-queue\")\n        await handle.wait_call(timeout=3)\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n\n@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestRabbitBroker(broker, with_real=True) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", queue=\"test-queue\")\n            await handle.wait_call(timeout=3)\n\n        handle.mock.assert_called_once_with(\"wrong message\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.nats import TestNatsBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestNatsBroker(broker, with_real=True) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, subject=\"test-subject\")\n        await handle.wait_call(timeout=3)\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n\n@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestNatsBroker(broker, with_real=True) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", subject=\"test-subject\")\n            await handle.wait_call(timeout=3)\n\n        handle.mock.assert_called_once_with(\"wrong message\")\n
import pytest\nfrom pydantic import ValidationError\n\nfrom faststream.redis import TestRedisBroker\n\n@pytest.mark.asyncio\nasync def test_handle():\n    async with TestRedisBroker(broker, with_real=True) as br:\n        await br.publish({\"name\": \"John\", \"user_id\": 1}, channel=\"test-channel\")\n        await handle.wait_call(timeout=3)\n        handle.mock.assert_called_once_with({\"name\": \"John\", \"user_id\": 1})\n\n    assert handle.mock is None\n\n@pytest.mark.asyncio\nasync def test_validation_error():\n    async with TestRedisBroker(broker, with_real=True) as br:\n        with pytest.raises(ValidationError):\n            await br.publish(\"wrong message\", channel=\"test-channel\")\n            await handle.wait_call(timeout=3)\n\n        handle.mock.assert_called_once_with(\"wrong message\")\n

Tip

When you're using a patched broker to test your consumers, the publish method is called synchronously with a consumer one, so you need not wait until your message is consumed. But in the real broker's case, it doesn't.

For this reason, you have to wait for message consumption manually with the special handler.wait_call(timeout) method. Also, inner handler exceptions will be raised in this function, not broker.publish(...).

","boost":10},{"location":"getting-started/subscription/test/#a-little-tip","title":"A Little Tip","text":"

It can be very helpful to set the with_real flag using an environment variable. This way, you will be able to choose the testing mode right from the command line:

WITH_REAL=True/False pytest ...\n

To learn more about managing your application configiruation visit this page.

","boost":10},{"location":"getting-started/template/","title":"Using Cookiecutter FastStream Template","text":"

Cookiecutter FastStream is a versatile repository that provides a solid foundation for your Python projects. It comes with a basic application, testing infrastructure, linting scripts, and various development tools to kickstart your development process. Whether you're building a new application from scratch or want to enhance an existing one, this template will save you time and help you maintain high code quality.

","boost":5},{"location":"getting-started/template/#features","title":"Features","text":"","boost":5},{"location":"getting-started/template/#getting-started","title":"Getting Started","text":"

To set up your development environment, follow these steps:

  1. Install the cookiecutter package using the following command:

    pip install cookiecutter\n

  2. Run the provided cookiecutter command and fill out the relevant details to generate a new FastStream project:

    cookiecutter https://github.com/airtai/cookiecutter-faststream.git\n
    The following screenshot illustrates the process of creating a new FastStream app with Kafka using the above command:

  3. Change the working directory to the newly created directory:

    cd <directory-name>\n

    NOTE: Replace <directory-name> with the name of your directory.

  4. Install all development requirements using pip:

    pip install -e \".[dev]\"\n

  5. Create a new repository for our FastStream app on GitHub.

  6. Add all the files, commit and push using the following commands:

    git init\ngit add .\ngit commit -m \"first commit\"\ngit branch -M main\ngit remote add origin git@github.com:<username>/<repo-name>.git\ngit push -u origin main\n

    NOTE: Replace <username> with your GitHub username and <repo-name> with the name of your repository in the above commands.

","boost":5},{"location":"getting-started/template/#development","title":"Development","text":"

The application code is located in the app/ directory. You can add new features or fix bugs in this directory. However, remember that code changes must be accompanied by corresponding updates to the tests located in the tests/ directory.

","boost":5},{"location":"getting-started/template/#running-tests","title":"Running Tests","text":"

Once you have updated tests, you can execute the tests using pytest:

pytest\n
","boost":5},{"location":"getting-started/template/#running-faststream-application-locally","title":"Running FastStream Application Locally","text":"

To run the FastStream application locally, follow these steps:

  1. Start the Kafka Docker container locally using the provided script:

    ./scripts/start_kafka_broker_locally.sh\n

  2. Start the FastStream application with the following command:

    faststream run <directory-name>.application:app --workers 1\n

    NOTE: Replace <directory-name> with the directory that is automatically generated from the project slug name and contains the app.py file.

  3. You can now send messages to the Kafka topic and can test the application. Optionally, if you want to view messages in a topic, you can subscribe to it using the provided script:

    ./scripts/subscribe_to_kafka_broker_locally.sh <topic_name>\n

  4. To stop the FastStream application, press Ctrl+C.

  5. Finally, stop the Kafka Docker container by running the script:

    ./scripts/stop_kafka_broker_locally.sh\n

","boost":5},{"location":"getting-started/template/#building-and-testing-docker-image-locally","title":"Building and Testing Docker Image Locally","text":"

If you'd like to build and test the Docker image locally, follow these steps:

  1. Run the provided script to build the Docker image locally. Use the following command:

    ./scripts/build_docker.sh <username> <repo-name>\n
    This script will build the Docker image locally with the same name as the one built in CI.

  2. Before starting the Docker container, ensure that a Kafka Docker container is running locally. You can start it using the provided script:

    ./scripts/start_kafka_broker_locally.sh\n

  3. Once Kafka is up and running, you can start the local Docker container using the following command:

    docker run --rm --name faststream-app --net=host ghcr.io/<username>/<repo-name>:latest\n
    --rm: This flag removes the container once it stops running, ensuring that it doesn't clutter your system with unused containers. --name faststream-app: Assigns a name to the running container, in this case, \"faststream-app\". --net=host: This flag allows the Docker container to share the host's network namespace.

  4. To stop the local Docker container, simply press Ctrl+C in your terminal.

  5. Finally, stop the Kafka Docker container by running the provided script:

    ./scripts/stop_kafka_broker_locally.sh\n

NOTE: Replace <username> with your GitHub username and <repo-name> with the name of your repository in the above commands.

","boost":5},{"location":"getting-started/template/#code-linting","title":"Code Linting","text":"

After making changes to the code, it's essential to ensure it adheres to coding standards. We provide a script to help you with code formatting and linting. Run the following script to automatically fix linting issues:

./scripts/lint.sh\n
","boost":5},{"location":"getting-started/template/#static-analysis","title":"Static Analysis","text":"

Static analysis tools mypy and bandit can help identify potential issues in your code. To run static analysis, use the following script:

./scripts/static-analysis.sh\n

If there are any static analysis errors, resolve them in your code and rerun the script until it passes successfully.

","boost":5},{"location":"getting-started/template/#viewing-asyncapi-documentation","title":"Viewing AsyncAPI Documentation","text":"

FastStream framework supports AsyncAPI documentation. To ensure that your changes are reflected in the AsyncAPI documentation, follow these steps:

  1. Run the following command to view the AsyncAPI documentation:

    faststream docs serve <directory-name>.application:app\n
    This command builds the AsyncAPI specification file, generates AsyncAPI documentation based on the specification, and serves it at localhost:8000.

    NOTE: Replace <directory-name> with the directory that is automatically generated from the project slug name and contains the app.py file.

  2. Open your web browser and navigate to http://localhost:8000 to view the AsyncAPI documentation reflecting your changes.

  3. To stop the AsyncAPI documentation server, press Ctrl+C.

","boost":5},{"location":"getting-started/template/#contributing","title":"Contributing","text":"

Once you have successfully completed all the above steps, you are ready to contribute your changes:

  1. Add and commit your changes:

    git add .\ngit commit -m \"Your commit message\"\n

  2. Push your changes to GitHub:

    git push origin your-branch\n

  3. Create a merge request on GitHub.

","boost":5},{"location":"getting-started/template/#continuous-integration-ci","title":"Continuous Integration (CI)","text":"

This repository is equipped with GitHub Actions that automate static analysis and pytest in the CI pipeline. Even if you forget to perform any of the required steps, CI will catch any issues before merging your changes.

This repository has three workflows, each triggered when code is pushed:

  1. Tests Workflow: This workflow is named \"Tests\" and consists of two jobs. The first job runs static analysis tools mypy and bandit to identify potential issues in the codebase. The second job runs tests using pytest to ensure the functionality of the application. Both jobs run simultaneously to expedite the CI process.

  2. Build Docker Image Workflow: This workflow is named \"Build Docker Image\" and has one job. In this job, a Docker image is built based on the provided Dockerfile. The built image is then pushed to the GitHub Container Registry, making it available for deployment or other purposes.

  3. Deploy FastStream AsyncAPI Docs Workflow: The final workflow is named \"Deploy FastStream AsyncAPI Docs\" and also consists of a single job. In this job, the AsyncAPI documentation is built from the specification, and the resulting documentation is deployed to GitHub Pages. This allows for easy access and sharing of the AsyncAPI documentation with the project's stakeholders.

","boost":5},{"location":"getting-started/template/#viewing-asyncapi-documentation-hosted-at-github-pages","title":"Viewing AsyncAPI Documentation Hosted at GitHub Pages","text":"

After the Deploy FastStream AsyncAPI Docs workflow in CI has been successfully completed, the AsyncAPI documentation is automatically deployed to GitHub Pages. This provides a convenient way to access and share the documentation with project stakeholders.

To view the deployed AsyncAPI documentation, open your web browser and navigate to the following URL:

https://<username>.github.io/<repo-name>/\n

NOTE: Replace <username> with your GitHub username and <repo-name> with the name of your repository.

You will be directed to the GitHub Pages site where your AsyncAPI documentation is hosted. This hosted documentation allows you to easily share your AsyncAPI specifications with others and provides a centralized location for reviewing the AsyncAPI documentation.

","boost":5},{"location":"getting-started/template/#deploying-docker-container","title":"Deploying Docker Container","text":"

Once the Build Docker Image workflow in CI has successfully completed, the built Docker image is pushed to the GitHub Container Registry. You can then deploy this image on your server by following these steps:

  1. Pull the Docker image from the GitHub Container Registry to your server using the following command:

    docker pull ghcr.io/<username>/<repo-name>:latest\n

    NOTE: Replace <username> with your GitHub username and <repo-name> with the name of your repository.

  2. After successfully pulling the image, start the Docker container using the following command:

    docker run --rm --name faststream-app --env-file /path/to/env-file ghcr.io/<username>/<repo-name>:latest\n
    --rm: This flag removes the container once it stops running, ensuring that it doesn't clutter your system with unused containers. --name faststream-app: Assigns a name to the running container, in this case, \"faststream-app\". --env-file /path/to/env-file: Specifies the path to an environment file (commonly a .env file) that contains environment variables required by your FastStream application. Storing secrets and configuration in an environment file is a secure and best practice for handling sensitive information such as Kafka host, port, and authentication details.

By following these steps, you can easily deploy your FastStream application as a Docker container on your server. Remember to customize the env-file and other environment variables as needed to suit your specific application requirements.

","boost":5},{"location":"kafka/","title":"Kafka Routing","text":"","boost":10},{"location":"kafka/#kafka-overview","title":"Kafka Overview","text":"","boost":10},{"location":"kafka/#what-is-kafka","title":"What is Kafka?","text":"

Kafka is an open-source distributed streaming platform developed by the Apache Software Foundation. It is designed to handle high-throughput, fault-tolerant, real-time data streaming. Kafka is widely used for building real-time data pipelines and streaming applications.

","boost":10},{"location":"kafka/#key-kafka-concepts","title":"Key Kafka Concepts","text":"","boost":10},{"location":"kafka/#1-publish-subscribe-model","title":"1. Publish-Subscribe Model","text":"

Kafka is built around the publish-subscribe messaging model. In this model, data is published to topics, and multiple consumers can subscribe to these topics to receive the data. This decouples the producers of data from the consumers, allowing for flexibility and scalability.

","boost":10},{"location":"kafka/#2-topics","title":"2. Topics","text":"

A topic in Kafka is a logical channel or category to which messages are published by producers and from which messages are consumed by consumers. Topics are used to organize and categorize data streams. Each topic can have multiple partitions, which enable Kafka to distribute data and provide parallelism for both producers and consumers.

","boost":10},{"location":"kafka/#kafka-topics","title":"Kafka Topics","text":"","boost":10},{"location":"kafka/#understanding-kafka-topics","title":"Understanding Kafka Topics","text":"

Topics are fundamental to Kafka and serve as the central point of data distribution. Here are some key points about topics:

","boost":10},{"location":"kafka/#faststream-kafkabroker","title":"FastStream KafkaBroker","text":"

The FastStream KafkaBroker is a key component of the FastStream framework that enables seamless integration with Apache Kafka. With the KafkaBroker, developers can easily connect to Kafka brokers, produce messages to Kafka topics, and consume messages from Kafka topics within their FastStream applications.

","boost":10},{"location":"kafka/#establishing-a-connection","title":"Establishing a Connection","text":"

To connect to Kafka using the FastStream KafkaBroker module, follow these steps:

  1. Initialize the KafkaBroker instance: Start by initializing a KafkaBroker instance with the necessary configuration, including Kafka broker address.

  2. Create your processing logic: Write a function that will consume the incoming messages in the defined format and produce a response to the defined topic

  3. Decorate your processing function: To connect your processing function to the desired Kafka topics you need to decorate it with @broker.subscriber(...) and @broker.publisher(...) decorators. Now, after you start your application, your processing function will be called whenever a new message in the subscribed topic is available and produce the function return value to the topic defined in the publisher decorator.

Here's a simplified code example demonstrating how to establish a connection to Kafka using FastStream's KafkaBroker module:

from faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-topic\")\n@broker.publisher(\"out-topic\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n

This minimal example illustrates how FastStream simplifies the process of connecting to Kafka and performing basic message processing from the in_topic to the out-topic. Depending on your specific use case and requirements, you can further customize your Kafka integration with FastStream to build robust and efficient streaming applications.

For more advanced configuration options and detailed usage instructions, please refer to the FastStream Kafka documentation and the offical Kafka documentation.

","boost":10},{"location":"kafka/ack/","title":"Consuming Acknowledgements","text":"

As you may know, Kafka consumer should commit a topic offset when consuming a message.

The default behaviour, also implemented as such in the FastStream, automatically commits (acks) topic offset on message consumption. This is the at most once consuming strategy.

However, if you wish to use at least once strategy, you should commit offset AFTER the message is processed correctly. To accomplish that, set a consumer group and disable auto_commit option like this:

@broker.subscriber(\n    \"test\", group_id=\"group\", auto_commit=False\n)\nasync def base_handler(body: str):\n    ...\n

This way, upon successful return of the processing function, the message processed will be acknowledged. In the case of an exception being raised, the message will not be acknowledged.

However, there are situations where you might want to use a different acknowledgement logic.

","boost":10},{"location":"kafka/ack/#manual-acknowledgement","title":"Manual Acknowledgement","text":"

If you want to acknowledge a message manually, you can get direct access to the message object via the Context and acknowledge the message by calling the ack method:

from faststream.kafka.annotations import KafkaMessage\n\n\n@broker.subscriber(\n    \"test\", group_id=\"group\", auto_commit=False\n)\nasync def base_handler(body: str, msg: KafkaMessage):\n    await msg.ack()\n    # or\n    await msg.nack()\n

Tip

You can use the nack method to prevent offset commit and the message can be consumed by another consumer within the same group.

FastStream will see that the message was already acknowledged and will do nothing at the end of the process.

","boost":10},{"location":"kafka/ack/#interrupt-process","title":"Interrupt Process","text":"

If you wish to interrupt the processing of a message at any call stack level and acknowledge the message, you can achieve that by raising the faststream.exceptions.AckMessage.

from faststream import FastStream\nfrom faststream.exceptions import AckMessage\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    \"test-topic\", group_id=\"test-group\", auto_commit=False\n)\nasync def handle(body):\n    smth_processing(body)\n\n\ndef smth_processing(body):\n    if True:\n        raise AckMessage()\n\n\n@app.after_startup\nasync def test_publishing():\n    await broker.publish(\"Hello!\", \"test-topic\")\n

This way, FastStream interrupts the current message processing and acknowledges it immediately. Similarly, you can raise NackMessage as well to prevent the message from being committed.

Tip

If you want to disable FastStream Acknowledgement logic at all, you can use @broker.subscriber(..., no_ack=True) option. This way you should always process a message (ack/nack/terminate/etc) by yourself.

","boost":10},{"location":"kafka/message/","title":"Access to Message Information","text":"

As you may know, FastStream serializes a message body and provides you access to it through function arguments. However, there are times when you need to access additional message attributes such as offsets, headers, or other metadata.

","boost":10},{"location":"kafka/message/#message-access","title":"Message Access","text":"

You can easily access this information by referring to the message object in the Context

This object serves as a unified FastStream wrapper around the native broker library message (for example, aiokafka.ConsumerRecord in the case of Kafka). It contains most of the required information, including:

For example, if you would like to access the headers of an incoming message, you would do so like this:

from faststream.kafka import KafkaMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    msg: KafkaMessage,\n):\n    print(msg.headers)\n
","boost":10},{"location":"kafka/message/#message-fields-access","title":"Message Fields Access","text":"

In most cases, you don't need all message fields; you need to know just a part of them. You can use Context Fields access feature for this.

For example, you can get access to the headers like this:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    headers: str = Context(\"message.headers\"),\n):\n    print(headers)\n
","boost":10},{"location":"kafka/message/#headers-access","title":"Headers Access","text":"

Sure, you can get access to a raw message and get the headers dict itself, but more often you just need a single header field. So, you can easily access it using the Context:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Context(\"message.headers.user\"),\n):\n    ...\n

Using the special Header class is more convenient, as it also validates the header value using Pydantic. It works the same way as Context, but it is just a shorcut to Context with a default setup. So, you already know how to use it:

from faststream import Header\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Header(),\n):\n    ...\n
","boost":10},{"location":"kafka/security/","title":"FastStream Kafka Security","text":"

This chapter discusses the security options available in FastStream and how to use them.

","boost":10},{"location":"kafka/security/#security-objects","title":"Security Objects","text":"

FastStream allows you to enhance the security of applications by using security objects when creating brokers. These security objects encapsulate security-related configurations and mechanisms. Security objects supported in FastStream are (More are planned in the future such as SASL OAuth):

","boost":10},{"location":"kafka/security/#1-basesecurity-object","title":"1. BaseSecurity Object","text":"

Purpose: The BaseSecurity object wraps ssl.SSLContext object and is used to enable SSL/TLS encryption for secure communication between FastStream services and external components such as message brokers.

Usage:

import ssl\n\nfrom faststream.kafka import KafkaBroker\nfrom faststream.security import BaseSecurity\n\nssl_context = ssl.create_default_context()\nsecurity = BaseSecurity(ssl_context=ssl_context)\n\nbroker = KafkaBroker(\"localhost:9092\", security=security)\n
","boost":10},{"location":"kafka/security/#2-saslplaintext-object-with-ssltls","title":"2. SASLPlaintext Object with SSL/TLS","text":"

Purpose: The SASLPlaintext object is used for authentication in SASL (Simple Authentication and Security Layer) plaintext mode. It allows you to provide a username and password for authentication.

Usage:

import ssl\n\nfrom faststream.kafka import KafkaBroker\nfrom faststream.security import SASLPlaintext\n\nssl_context = ssl.create_default_context()\nsecurity = SASLPlaintext(\n    ssl_context=ssl_context,\n    username=\"admin\",\n    password=\"password\", \n)\n\nbroker = KafkaBroker(\"localhost:9092\", security=security)\n

Using any SASL authentication without SSL:

The following example will log a RuntimeWarning:

SASLPlaintext(username=\"admin\", password=\"password\")\n

If the user does not want to use SSL encryption without the waringning getting logged, they must explicitly set the use_ssl parameter to False when creating a SASL object.

SASLPlaintext(username=\"admin\", password=\"password\", use_ssl=False) \n
","boost":10},{"location":"kafka/security/#3-saslscram256512-object-with-ssltls","title":"3. SASLScram256/512 Object with SSL/TLS","text":"

Purpose: The SASLScram256 and SASLScram512 objects are used for authentication using the Salted Challenge Response Authentication Mechanism (SCRAM).

Usage:

SCRAM256SCRAM512
import ssl\n\nfrom faststream.kafka import KafkaBroker\nfrom faststream.security import SASLScram256\n\nssl_context = ssl.create_default_context()\nsecurity = SASLScram256(\n    ssl_context=ssl_context,\n    username=\"admin\",\n    password=\"password\", \n)\n\nbroker = KafkaBroker(\"localhost:9092\", security=security)\n
import ssl\n\nfrom faststream.kafka import KafkaBroker\nfrom faststream.security import SASLScram512\n\nssl_context = ssl.create_default_context()\nsecurity = SASLScram512(\n    ssl_context=ssl_context,\n    username=\"admin\",\n    password=\"password\", \n)\n\nbroker = KafkaBroker(\"localhost:9092\", security=security)\n
","boost":10},{"location":"kafka/Publisher/","title":"Publishing","text":"

The FastStream KafkaBroker supports all regular publishing use cases, and you can use them without any changes.

However, if you wish to further customize the publishing logic, you should take a closer look at specific KafkaBroker parameters.

","boost":10},{"location":"kafka/Publisher/#basic-kafka-publishing","title":"Basic Kafka Publishing","text":"

The KafkaBroker uses the unified publish method (from a producer object) to send messages.

In this case, you can use Python primitives and pydantic.BaseModel to define the content of the message you want to publish to the Kafka broker.

You can specify the topic to send by its name.

  1. Create your KafkaBroker instance

    broker = KafkaBroker(\"localhost:9092\")\n
  2. Publish a message using the publish method

    msg = Data(data=0.5)\n\nawait broker.publish(\n    model_to_json(msg),\n    \"input_data\",\n    headers={\"content-type\": \"application/json\"},\n)\n

This is the most basic way of using the KafkaBroker to publish a message.

","boost":10},{"location":"kafka/Publisher/#creating-a-publisher-object","title":"Creating a publisher object","text":"

The simplest way to use a KafkaBroker for publishing has a significant limitation: your publishers won't be documented in the AsyncAPI documentation. This might be acceptable for sending occasional one-off messages. However, if you're building a comprehensive service, it's recommended to create publisher objects. These objects can then be parsed and documented in your service's AsyncAPI documentation. Let's go ahead and create those publisher objects!

  1. Create your KafkaBroker instance

    broker = KafkaBroker(\"localhost:9092\")\n
  2. Create a publisher instance

    prepared_publisher = broker.publisher(\"input_data\")\n
  3. Publish a message using the publish method of the prepared publisher

    msg = Data(data=0.5)\n\nawait prepared_publisher.publish(\n    model_to_json(msg),\n    headers={\"content-type\": \"application/json\"},\n)\n

Now, when you wrap your broker into a FastStream object, the publisher will be exported to the AsyncAPI documentation.

","boost":10},{"location":"kafka/Publisher/#decorating-your-publishing-functions","title":"Decorating your publishing functions","text":"

To publish messages effectively in the Kafka context, consider utilizing the Publisher Decorator. This approach offers an AsyncAPI representation and is ideal for rapidly developing applications.

The Publisher Decorator creates a structured DataPipeline unit with both input and output components. The sequence in which you apply Subscriber and Publisher decorators does not affect their functionality. However, note that these decorators can only be applied to functions decorated by a Subscriber as well.

This method relies on the return type annotation of the handler function to properly interpret the function's return value before sending it. Hence, it's important to ensure accuracy in defining the return type.

Let's start by examining the entire application that utilizes the Publisher Decorator and then proceed to walk through it step by step.

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.kafka import KafkaBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\nto_output_data = broker.publisher(\"output_data\")\n\n\n@to_output_data\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
  1. Initialize the KafkaBroker instance: Start by initializing a KafkaBroker instance with the necessary configuration, including Kafka broker address.

    broker = KafkaBroker(\"localhost:9092\")\n
  2. Prepare your publisher object to use later as a decorator:

    to_output_data = broker.publisher(\"output_data\")\n
  3. Create your processing logic: Write a function that will consume the incoming messages in the defined format and produce a response to the defined topic

    async def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
  4. Decorate your processing function: To connect your processing function to the desired Kafka topics you need to decorate it with @broker.subscriber(...) and @broker.publisher(...) decorators. Now, after you start your application, your processing function will be called whenever a new message in the subscribed topic is available and produce the function return value to the topic defined in the publisher decorator.

    @to_output_data\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
","boost":10},{"location":"kafka/Publisher/batch_publisher/","title":"Publishing in Batches","text":"","boost":10},{"location":"kafka/Publisher/batch_publisher/#general-overview","title":"General Overview","text":"

If you need to send your data in batches, the @broker.publisher(...) decorator offers a convenient way to achieve this. To enable batch production, you need to perform two crucial steps:

  1. When creating your publisher, set the batch argument to True. This configuration tells the publisher that you intend to send messages in batches.

  2. In your producer function, return a tuple containing the messages you want to send as a batch. This action triggers the producer to gather the messages and transmit them as a batch to a Kafka broker.

Let's delve into a detailed example illustrating how to produce messages in batches to the \"output_data\" topic while consuming from the \"input_data_1\" topic.

","boost":10},{"location":"kafka/Publisher/batch_publisher/#code-example","title":"Code Example","text":"

First, let's take a look at the whole app creation and then dive deep into the steps for producing in batches. Here is the application code:

from typing import Tuple\n\nfrom pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\ndecrease_and_increase = broker.publisher(\"output_data\", batch=True)\n\n\n@decrease_and_increase\n@broker.subscriber(\"input_data_1\")\nasync def on_input_data_1(msg: Data, logger: Logger) -> Tuple[Data, Data]:\n    logger.info(msg)\n    return Data(data=(msg.data * 0.5)), Data(data=(msg.data * 2.0))\n\n\n@broker.subscriber(\"input_data_2\")\nasync def on_input_data_2(msg: Data, logger: Logger) -> None:\n    logger.info(msg)\n    await decrease_and_increase.publish(\n        Data(data=(msg.data * 0.5)), Data(data=(msg.data * 2.0))\n    )\n

Below, we have highlighted key lines of code that demonstrate the steps involved in creating and using a batch publisher:

Step 1: Creation of the Publisher

decrease_and_increase = broker.publisher(\"output_data\", batch=True)\n

Step 2: Publishing an Actual Batch of Messages

You can publish a batch by directly calling the publisher with a batch of messages you want to publish, as shown here:

await decrease_and_increase.publish(\n    Data(data=(msg.data * 0.5)), Data(data=(msg.data * 2.0))\n)\n

Or you can decorate your processing function and return a batch of messages, as shown here:

@decrease_and_increase\n@broker.subscriber(\"input_data_1\")\nasync def on_input_data_1(msg: Data, logger: Logger) -> Tuple[Data, Data]:\n    logger.info(msg)\n    return Data(data=(msg.data * 0.5)), Data(data=(msg.data * 2.0))\n

The application in the example imelements both of these ways, so feel free to use whichever option fits your needs better.

Note

Also, you can publishes messages in batches right from a broker object: just call broker.publish_batch(\"msg2\", \"msg2\", topic=\"output_data\")

","boost":10},{"location":"kafka/Publisher/batch_publisher/#why-publish-in-batches","title":"Why Publish in Batches?","text":"

In the above example, we've explored how to leverage the @broker.publisher(...) decorator to efficiently publish messages in batches using FastStream and Kafka. By following the two key steps outlined in the previous sections, you can significantly enhance the performance and reliability of your Kafka-based applications.

Publishing messages in batches offers several advantages when working with Kafka:

  1. Improved Throughput: Batch publishing allows you to send multiple messages in a single transmission, reducing the overhead associated with individual message delivery. This leads to improved throughput and lower latency in your Kafka applications.

  2. Reduced Network and Broker Load: Sending messages in batches reduces the number of network calls and broker interactions. This optimization minimizes the load on the Kafka brokers and network resources, making your Kafka cluster more efficient.

  3. Atomicity: Batches ensure that a group of related messages is processed together or not at all. This atomicity can be crucial in scenarios where message processing needs to maintain data consistency and integrity.

  4. Enhanced Scalability: With batch publishing, you can efficiently scale your Kafka applications to handle high message volumes. By sending messages in larger chunks, you can make the most of Kafka's parallelism and partitioning capabilities.

","boost":10},{"location":"kafka/Publisher/using_a_key/","title":"Using a Partition Key","text":"

Partition keys are a crucial concept in Apache Kafka, enabling you to determine the appropriate partition for a message. This ensures that related messages are kept together in the same partition, which can be invaluable for maintaining order or grouping related messages for efficient processing. Additionally, Kafka utilizes partitioning to distribute load across multiple brokers and scale horizontally, while replicating data across brokers provides fault tolerance.

You can specify your partition keys when utilizing the @KafkaBroker.publisher(...) decorator in FastStream. This guide will walk you through the process of using partition keys effectively.

","boost":10},{"location":"kafka/Publisher/using_a_key/#publishing-with-a-partition-key","title":"Publishing with a Partition Key","text":"

To publish a message to a Kafka topic using a partition key, follow these steps:

","boost":10},{"location":"kafka/Publisher/using_a_key/#step-1-define-the-publisher","title":"Step 1: Define the Publisher","text":"

In your FastStream application, define the publisher using the @KafkaBroker.publisher(...) decorator. This decorator allows you to configure various aspects of message publishing, including the partition key.

to_output_data = broker.publisher(\"output_data\")\n
","boost":10},{"location":"kafka/Publisher/using_a_key/#step-2-pass-the-key","title":"Step 2: Pass the Key","text":"

When you're ready to publish a message with a specific key, simply include the key parameter in the publish function call. This key parameter is used to determine the appropriate partition for the message.

await to_output_data.publish(Data(data=msg.data + 1.0), key=b\"key\")\n
","boost":10},{"location":"kafka/Publisher/using_a_key/#example-application","title":"Example Application","text":"

Let's examine a complete application example that consumes messages from the \"input_data\" topic and publishes them with a specified key to the \"output_data\" topic. This example will illustrate how to incorporate partition keys into your Kafka-based applications:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import Context, FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\nto_output_data = broker.publisher(\"output_data\")\n\n\n@broker.subscriber(\"input_data\")\nasync def on_input_data(\n    msg: Data, logger: Logger, key: bytes = Context(\"message.raw_message.key\")\n) -> None:\n    logger.info(f\"on_input_data({msg=})\")\n    await to_output_data.publish(Data(data=msg.data + 1.0), key=b\"key\")\n

As you can see, the primary difference from standard publishing is the inclusion of the key parameter in the publish call. This key parameter is essential for controlling how Kafka partitions and processes your messages.

In summary, using partition keys in Apache Kafka is a fundamental practice for optimizing message distribution, maintaining order, and achieving efficient processing. It is a key technique for ensuring that your Kafka-based applications scale gracefully and handle large volumes of data effectively.

","boost":10},{"location":"kafka/Subscriber/","title":"Basic Subscriber","text":"

To start consuming from a Kafka topic, simply decorate your consuming function with a @broker.subscriber(...) decorator, passing a string as a topic key.

In the folowing example, we will create a simple FastStream app that will consume HelloWorld messages from a \"hello_world\" topic.

The full app code looks like this:

from pydantic import BaseModel, Field\n\nfrom faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n\n\nclass HelloWorld(BaseModel):\n    msg: str = Field(\n        ...,\n        examples=[\"Hello\"],\n        description=\"Demo hello world message\",\n    )\n\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"hello_world\")\nasync def on_hello_world(msg: HelloWorld, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"kafka/Subscriber/#import-faststream-and-kafkabroker","title":"Import FastStream and KafkaBroker","text":"

To use the @broker.subscriber(...) decorator, first, we need to import the base FastStream app KafkaBroker to create our broker.

from faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n
","boost":10},{"location":"kafka/Subscriber/#define-the-helloworld-message-structure","title":"Define the HelloWorld Message Structure","text":"

Next, you need to define the structure of the messages you want to consume from the topic using Pydantic. For the guide, we\u2019ll stick to something basic, but you are free to define any complex message structure you wish in your project.

class HelloWorld(BaseModel):\n    msg: str = Field(\n        ...,\n        examples=[\"Hello\"],\n        description=\"Demo hello world message\",\n    )\n
","boost":10},{"location":"kafka/Subscriber/#create-a-kafkabroker","title":"Create a KafkaBroker","text":"

Next, we will create a KafkaBroker object and wrap it into the FastStream object so that we can start our app using CLI later.

broker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n
","boost":10},{"location":"kafka/Subscriber/#create-a-function-that-will-consume-messages-from-a-kafka-hello-world-topic","title":"Create a Function that will Consume Messages from a Kafka hello-world Topic","text":"

Let\u2019s create a consumer function that will consume HelloWorld messages from \"hello_world\" topic and log them.

@broker.subscriber(\"hello_world\")\nasync def on_hello_world(msg: HelloWorld, logger: Logger):\n    logger.info(msg)\n

The function decorated with the @broker.subscriber(...) decorator will be called when a message is produced to Kafka.

The message will then be injected into the typed msg argument of the function, and its type will be used to parse the message.

In this example case, when the message is sent to a \"hello_world\" topic, it will be parsed into a HelloWorld class, and the on_hello_world function will be called with the parsed class as the msg argument value.

","boost":10},{"location":"kafka/Subscriber/batch_subscriber/","title":"Batch Subscriber","text":"

If you want to consume data in batches, the @broker.subscriber(...) decorator makes it possible. By defining your consumed msg object as a list of messages and setting the batch parameter to True, the subscriber will call your consuming function with a batch of messages consumed from a single partition. Let's walk through how to achieve this.

","boost":10},{"location":"kafka/Subscriber/batch_subscriber/#using-the-subscriber-with-batching","title":"Using the Subscriber with Batching","text":"

To consume messages in batches, follow these steps:

","boost":10},{"location":"kafka/Subscriber/batch_subscriber/#step-1-define-your-subscriber","title":"Step 1: Define Your Subscriber","text":"

In your FastStream application, define the subscriber using the @broker.subscriber(...) decorator. Ensure that you configure the msg object as a list and set the batch parameter to True. This configuration tells the subscriber to handle message consumption in batches.

@broker.subscriber(\"test_batch\", batch=True)\n
","boost":10},{"location":"kafka/Subscriber/batch_subscriber/#step-2-implement-your-consuming-function","title":"Step 2: Implement Your Consuming Function","text":"

Create a consuming function that accepts the list of messages. The @broker.subscriber(...) decorator will take care of collecting and grouping messages into batches based on the partition.

@broker.subscriber(\"test_batch\", batch=True)\nasync def handle_batch(msg: List[HelloWorld], logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"kafka/Subscriber/batch_subscriber/#example-of-consuming-in-batches","title":"Example of Consuming in Batches","text":"

Let's illustrate how to consume messages in batches from the \"test_batch\" topic with a practical example:

from typing import List\n\nfrom pydantic import BaseModel, Field\n\nfrom faststream import FastStream, Logger\nfrom faststream.kafka import KafkaBroker\n\nbroker = KafkaBroker(\"localhost:9092\")\napp = FastStream(broker)\n\n\nclass HelloWorld(BaseModel):\n    msg: str = Field(\n        ...,\n        examples=[\"Hello\"],\n        description=\"Demo hello world message\",\n    )\n\n\n@broker.subscriber(\"test_batch\", batch=True)\nasync def handle_batch(msg: List[HelloWorld], logger: Logger):\n    logger.info(msg)\n

In this example, the subscriber is configured to process messages in batches, and the consuming function is designed to handle these batches efficiently.

Consuming messages in batches is a valuable technique when you need to optimize the processing of high volumes of data in your Kafka-based applications. It allows for more efficient resource utilization and can enhance the overall performance of your data pipelines.

","boost":10},{"location":"nats/","title":"NATS","text":"

FastStream NATS support is implemented on top of nats-py. You can always get access to objects of it if you need to use some low-level methods not represented in FastStream.

","boost":10},{"location":"nats/#advantages-and-disadvantages","title":"Advantages and Disadvantages","text":"

NATS is an easy-to-use, high-performance message broker written in Golang. If your application does not require complex routing logic, can cope with high loads, scales, and does not require large hardware costs, NATS will be an excellent choice for you.

Also NATS has a zero-cost new entities creation (to be honest, all subjects are just routing fields), so it can be used as a RPC over MQ tool.

Note

More information about NATS can be found on the official website.

However, NATS has disadvantages that you should be aware of:

","boost":10},{"location":"nats/#nats-jetstream","title":"NATS JetStream","text":"

These shortcomings are corrected by using the persistent level - JetStream. If you need strict guarantees for the delivery and processing of messages at the small detriment of speed and resources consumed, you can use NatsJS.

Also, NatsJS supports some high-level features like Key-Value and Object storages (with subscription to changes on it) and provides you with rich abilities to build your logic on top of it.

","boost":10},{"location":"nats/#routing-rules","title":"Routing Rules","text":"

NATS does not have the ability to configure complex routing rules. The only entity in NATS is subject, which can be subscribed to either directly by name or by a regular expression pattern.

Both examples are discussed a little further.

In order to support the ability to scale consumers horizontally, NATS supports the queue group functionality: a message sent to subject will be processed by a random consumer from the queue group subscribed to this subject. This approach allows you to increase the processing speed of subject by N times when starting N consumers with one group.

","boost":10},{"location":"nats/message/","title":"Access to Message Information","text":"

As you know, FastStream serializes a message body and provides you access to it through function arguments. But sometimes you need to access message_id, headers, or other meta-information.

","boost":10},{"location":"nats/message/#message-access","title":"Message Access","text":"

You can get it in a simple way: just acces the message object in the Context.

It contains the required information such as:

It is a FastStream wrapper around a native broker library message (nats.aio.msg.Msg in the NATS' case) that you can access with raw_message.

from faststream.nats import NatsMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    msg: NatsMessage,\n):\n    print(msg.correlation_id)\n

Also, if you can't find the information you require, you can get access directly to the wrapped nats.aio.msg.Msg, which contains complete message information.

from nats.aio.msg import Msg\nfrom faststream.nats import NatsMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(body: str, msg: NatsMessage):\n    raw: Msg = msg.raw_message\n    print(raw)\n
","boost":10},{"location":"nats/message/#message-fields-access","title":"Message Fields Access","text":"

But in most cases, you don't need all message fields; you need to access some of them. You can use Context Fields access feature for this reason.

For example, you can access the correlation_id like this:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: str = Context(\"message.correlation_id\"),\n):\n    print(cor_id)\n

Or even directly from the raw message:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: str = Context(\"message.raw_message.correlation_id\"),\n):\n    print(cor_id)\n

But this code is too long to reuse everywhere. In this case, you can use a Python Annotated feature:

python 3.9+python 3.6+
from types import Annotated\nfrom faststream import Context\n\nCorrelationId = Annotated[str, Context(\"message.correlation_id\")]\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: CorrelationId,\n):\n    print(cor_id)\n
from typing_extensions import Annotated\nfrom faststream import Context\n\nCorrelationId = Annotated[str, Context(\"message.correlation_id\")]\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: CorrelationId,\n):\n    print(cor_id)\n
","boost":10},{"location":"nats/message/#headers-access","title":"Headers Access","text":"

Sure, you can get access to a raw message and get the headers dict itself, but more often you just need a single header field. So, you can easily access it using the Context:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Context(\"message.headers.user\"),\n):\n    ...\n

Using the special Header class is more convenient, as it also validates the header value using Pydantic. It works the same way as Context, but it is just a shorcut to Context with a default setup. So, you already know how to use it:

from faststream import Header\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Header(),\n):\n    ...\n
","boost":10},{"location":"nats/message/#subject-pattern-access","title":"Subject Pattern Access","text":"

As you know, NATS allows you to use a pattern like this \"logs.*\" to subscriber to subjects. Getting access to the real * value is an often-used scenario, and FastStream provide it to you with the Path object (which is a shortcut to Context(\"message.path.*\")).

To use it, you just need to replace your * with {variable-name} and use Path as a regular Context object:

from faststream import Path\n\n@broker.subscriber(\"logs.{level}\")\nasync def base_handler(\n    body: str,\n    level: str = Path(),\n):\n    ...\n
","boost":10},{"location":"nats/rpc/","title":"RPC over NATS","text":"

Because NATS has zero cost for creating new subjects, we can easily set up a new subject consumer just for the one response message. This way, your request message will be published to one topic, and the response message will be consumed from another one (temporary subject), which allows you to use regular FastStream RPC syntax in the NATS case too.

Tip

FastStream RPC over NATS works in both the NATS-Core and NATS-JS cases as well, but in the NATS-JS case, you have to specify the expected stream as a publish argument.

","boost":10},{"location":"nats/rpc/#blocking-request","title":"Blocking Request","text":"

FastStream provides you with the ability to send a blocking RPC request over NATS in a very simple way.

Just send a message like a regular one and get a response synchronously.

It is very close to the common requests syntax:

msg = await broker.publish(\n    \"Hi!\",\n    subject=\"test\",\n    rpc=True,\n)\n

Also, you have two extra options to control this behavior:

","boost":10},{"location":"nats/rpc/#reply-to","title":"Reply-To","text":"

Also, if you want to create a permanent request-reply data flow, probably, you should create a permanent subject to consume responses.

So, if you have such one, you can specify it with the reply_to argument. This way, FastStream will send a response to this subject automatically.

@broker.subscriber(\"response-subject\")\nasync def consume_responses(msg):\n    ...\n\nmsg = await broker.publish(\n    \"Hi!\",\n    subject=\"test\",\n    reply_to=\"response-subject\",\n)\n
","boost":10},{"location":"nats/examples/direct/","title":"Direct","text":"

The Direct Subject is the basic way to route messages in NATS. Its essence is very simple: a subject sends messages to all consumers subscribed to it.

","boost":10},{"location":"nats/examples/direct/#scaling","title":"Scaling","text":"

If one subject is being listened to by several consumers with the same queue group, the message will go to a random consumer each time.

Thus, NATS can independently balance the load on queue consumers. You can increase the processing speed of the message flow from the queue by simply launching additional instances of the consumer service. You don't need to make changes to the current infrastructure configuration: NATS will take care of how to distribute messages between your services.

","boost":10},{"location":"nats/examples/direct/#example","title":"Example","text":"

The Direct Subject is the type used in FastStream by default: you can simply declare it as follows

@broker.handler(\"test_subject\")\nasync def handler():\n...\n

Full example:

from faststream import FastStream, Logger\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n@broker.subscriber(\"test-subj-1\", \"workers\")\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n@broker.subscriber(\"test-subj-1\", \"workers\")\nasync def base_handler2(logger: Logger):  \n    logger.info(\"base_handler2\")\n\n@broker.subscriber(\"test-subj-2\", \"workers\")\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(\"\", \"test-subj-1\")  # handlers: 1 or 2\n    await broker.publish(\"\", \"test-subj-1\")  # handlers: 1 or 2\n    await broker.publish(\"\", \"test-subj-2\")  # handlers: 3\n
","boost":10},{"location":"nats/examples/direct/#consumer-announcement","title":"Consumer Announcement","text":"

To begin with, we have declared several consumers for two subjects: \"test-subj-1\" and \"test-subj-2\":

@broker.subscriber(\"test-subj-1\", \"workers\")\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n@broker.subscriber(\"test-subj-1\", \"workers\")\nasync def base_handler2(logger: Logger):  \n    logger.info(\"base_handler2\")\n\n@broker.subscriber(\"test-subj-2\", \"workers\")\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n

Note

Note that all consumers are subscribed using the same queue_group. Within the same service, this does not make sense, since messages will come to these handlers in turn. Here, we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"nats/examples/direct/#message-distribution","title":"Message Distribution","text":"

Now the distribution of messages between these consumers will look like this:

await broker.publish(\"\", \"test-subj-1\")  # handlers: 1 or 2\n

The message 1 will be sent to handler1 or handler2 because they are listening to one \"test-subj-1\" subject within one queue group.

await broker.publish(\"\", \"test-subj-1\")  # handlers: 1 or 2\n

Message 2 will be sent similarly to message 1.

await broker.publish(\"\", \"test-subj-2\")  # handlers: 3\n

The message 3 will be sent to handler3 because it is the only one listening to \"test-subj-2\".

","boost":10},{"location":"nats/examples/pattern/","title":"Pattern","text":"

Pattern Subject is a powerful NATS routing engine. This type of subject routes messages to consumers based on the pattern specified when they connect to the subject and a message key.

","boost":10},{"location":"nats/examples/pattern/#scaling","title":"Scaling","text":"

If one subject is being listened to by several consumers with the same queue group, the message will go to a random consumer each time.

Thus, NATS can independently balance the load on queue consumers. You can increase the processing speed of the message flow from the queue by simply launching additional instances of the consumer service. You don't need to make changes to the current infrastructure configuration: NATS will take care of how to distribute messages between your services.

","boost":10},{"location":"nats/examples/pattern/#example","title":"Example","text":"
from faststream import FastStream, Logger\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n@broker.subscriber(\"*.info\", \"workers\")\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n@broker.subscriber(\"*.info\", \"workers\")\nasync def base_handler2(logger: Logger):  \n    logger.info(\"base_handler2\")\n\n@broker.subscriber(\"*.error\", \"workers\")\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(\"\", \"logs.info\")  # handlers: 1 or 2\n    await broker.publish(\"\", \"logs.info\")  # handlers: 1 or 2\n    await broker.publish(\"\", \"logs.error\") # handlers: 3\n
","boost":10},{"location":"nats/examples/pattern/#consumer-announcement","title":"Consumer Announcement","text":"

To begin with, we have announced several consumers for two subjects: \"*.info\" and \"*.error\":

@broker.subscriber(\"*.info\", \"workers\")\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n@broker.subscriber(\"*.info\", \"workers\")\nasync def base_handler2(logger: Logger):  \n    logger.info(\"base_handler2\")\n\n@broker.subscriber(\"*.error\", \"workers\")\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n

At the same time, in the subject of our consumers, we specify the pattern that will be processed by these consumers.

Note

Note that all consumers are subscribed using the same queue_group. Within the same service, this does not make sense, since messages will come to these handlers in turn. Here, we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"nats/examples/pattern/#message-distribution","title":"Message Distribution","text":"

Now the distribution of messages between these consumers will look like this:

await broker.publish(\"\", \"logs.info\")  # handlers: 1 or 2\n

The message 1 will be sent to handler1 or handler2 because they listen to the same subject template within the same queue group.

await broker.publish(\"\", \"logs.info\")  # handlers: 1 or 2\n

Message 2 will be sent similarly to message 1.

await broker.publish(\"\", \"logs.error\") # handlers: 3\n

The message 3 will be sent to handler3 because it is the only one listening to the pattern \"*.error\".

","boost":10},{"location":"nats/jetstream/","title":"NATS JetStream","text":"

The default NATS usage is suitable for scenarios where:

If you need stricter restrictions, like:

You should use the NATS JetStream extension.

In fact, the JetStream extension is the same as NATS, with the addition of a persistent layer above the file system. Therefore, all interfaces for publishing and consuming messages are similar to regular NATS usage.

However, the JetStream layer has many possibilities for configuration, from the policy of deleting old messages to the maximum stored messages number limit. You can find out more about all JetStream features in the official documentation.

If you have worked with other message brokers, then you should know that the logic of JS is closer to Kafka than to RabbitMQ: messages, after confirmation, are not deleted from the queue but remain there until the queue is full, and it will start deleting old messages (or in accordance with other logic that you can configure yourself).

When connecting a consumer (and, especially, when reconnecting), you must determine for yourself according to what logic it will consume messages: from the subject beginning, starting with some message, starting from some time, only new ones, etc. Don't be surprised if a connection is restored, and your consumer starts to process all messages received earlier again - you haven't defined the rule.

Also, NATS JetStream has built-in key-value (similar to Redis) and object (similar to Minio) storages, which, in addition to the interface for put/get, have the ability to subscribe to events, which can be extremely useful in various scenarios.

FastStream does not provide access to this functionality directly, but it is covered by the nats-py library used. You can access the JS object from the application context:

from faststream import FastStream, Logger\nfrom faststream.nats import JStream, NatsBroker\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\nstream = JStream(name=\"stream\")\n\n@broker.subscriber(\n    \"js-subject\",\n    stream=stream,\n    deliver_policy=\"new\",\n)\nasync def handler(msg: str, logger: Logger):\n    logger.info(msg)\n\n@app.after_startup\nasync def test_send():\n    await broker.publish(\"Hi!\", \"js-subject\")\n    # publish with stream verification\n    await broker.publish(\"Hi!\", \"js-subject\", stream=\"stream\")\n

Tip

Using JStream object FastStream is trying to create/update stream with the object settings. To prevent this behavior and just get already created stream, please use JStream(..., declare=False) option.

","boost":10},{"location":"nats/jetstream/ack/","title":"Consuming Acknowledgements","text":"

As you may know, Nats employs a rather extensive Acknowledgement policy.

In most cases, FastStream automatically acknowledges (acks) messages on your behalf. When your function executes correctly, including sending all responses, a message will be acknowledged (and rejected in case of an exception).

However, there are situations where you might want to use different acknowledgement logic.

","boost":10},{"location":"nats/jetstream/ack/#retries","title":"Retries","text":"

If you prefer to use a nack instead of a reject when there's an error in message processing, you can specify the retry flag in the @broker.subscriber(...) method, which is responsible for error handling logic.

By default, this flag is set to False, indicating that if an error occurs during message processing, the message can still be retrieved from the queue:

@broker.subscriber(\"test\", retry=False) # don't handle exceptions\nasync def base_handler(body: str):\n    ...\n

If this flag is set to True, the message will be nacked and placed back in the queue each time an error occurs. In this scenario, the message can be processed by another consumer (if there are several of them) or by the same one:

@broker.subscriber(\"test\", retry=True)  # try again indefinitely\nasync def base_handler(body: str):\n    ...\n

Tip

For more complex error handling cases, you can use tenacity

","boost":10},{"location":"nats/jetstream/ack/#manual-acknowledgement","title":"Manual Acknowledgement","text":"

If you want to acknowledge a message manually, you can get access directy to the message object via the Context and call the method.

from faststream.nats.annotations import NatsMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(body: str, msg: NatsMessage):\n    await msg.ack()\n    # or\n    await msg.nack()\n    # or\n    await msg.reject()\n

FastStream will see that the message was already acknowledged and will do nothing at the end of the process.

","boost":10},{"location":"nats/jetstream/ack/#interrupt-process","title":"Interrupt Process","text":"

If you want to interrupt message processing at any call stack, you can raise faststream.exceptions.AckMessage

from faststream import FastStream\nfrom faststream.exceptions import AckMessage\nfrom faststream.nats import NatsBroker\n\nbroker = NatsBroker(\"nats://localhost:4222\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-subject\", stream=\"test-stream\")\nasync def handle(body):\n    smth_processing(body)\n\n\ndef smth_processing(body):\n    if True:\n        raise AckMessage()\n\n\n@app.after_startup\nasync def test_publishing():\n    await broker.publish(\"Hello!\", \"test-subject\")\n

This way, FastStream interrupts the current message proccessing and acknowledges it immediately. Also, you can raise NackMessage and RejectMessage too.

Tip

If you want to disable FastStream Acknowledgement logic at all, you can use @broker.subscriber(..., no_ack=True) option. This way you should always process a message (ack/nack/terminate/etc) by yourself.

","boost":10},{"location":"nats/jetstream/key-value/","title":"Key-Value Storage","text":"","boost":10},{"location":"nats/jetstream/key-value/#overview","title":"Overview","text":"

Key-Value storage is just a high-level interface on top of NatsJS.

It is a regular JetStream, where the KV key is a subject.

Put/Update an object to KV by key - it's like publishing a new message to the corresponding subject in the stream.

Thus, the Get command returns not only the current key value but the latest one with an offset of it. Additionally, you can ask for a specific value based on its offset in the KV stream.

This interface provides you with rich abilities to use it like a regular KV storage (ignoring offset) + subscribe to KV key changes + ask for an old KV value revision. So you can use this feature in your application in a really different way. You can find some examples on the NATS developers' official YouTube channel

","boost":10},{"location":"nats/jetstream/key-value/#faststream-details","title":"FastStream Details","text":"

FastStream has no native interfaces to this NatsJS functionality (yet), but it allows you to get access into the inner JetStream object to create it manually.

First of all, you need to create a Key-Value storage object and pass it into the context:

from faststream import Context, FastStream, Logger\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import ContextRepo\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n@app.on_startup\nasync def setup_broker(context: ContextRepo):\n    await broker.connect()\n\n    kv = await broker.stream.create_key_value(bucket=\"bucket\")\n    context.set_global(\"kv\", kv)\n

Tip

We placed this code in @app.on_startup hook because @app.after_startup will be triggered AFTER your handlers start consuming messages. So, if you need to have access to any custom context objects, you should set them up in the @app.on_startup hook.

Also, we call await broker.connect() method manually to establish the connection to be able to create a storage.

Next, we are ready to use this object right in our handlers.

Let's create an annotated object to shorten context object access:

from nats.js.kv import KeyValue as KV\nfrom typing_extensions import Annotated\n\nKeyValue = Annotated[KV, Context(\"kv\")]\n

And just use it in a handler:

from faststream import Logger\n\n@broker.subscriber(\"subject\")\nasync def handler(msg: str, kv: KeyValue, logger: Logger):\n    logger.info(msg)\n    kv_data = await kv.get(\"key\")\n    assert kv_data.value == b\"Hello!\"\n

Finally, let's test our code behavior by putting something into the KV storage and sending a message:

@app.after_startup\nasync def test_send(kv: KeyValue):\n    await kv.put(\"key\", b\"Hello!\")\n    await broker.publish(\"Hi!\", \"subject\")\n
Full listing
from nats.js.kv import KeyValue as KV\nfrom typing_extensions import Annotated\n\nfrom faststream import Logger\nfrom faststream import Context, FastStream, Logger\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import ContextRepo\n\nKeyValue = Annotated[KV, Context(\"kv\")]\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\"subject\")\nasync def handler(msg: str, kv: KeyValue, logger: Logger):\n    logger.info(msg)\n    kv_data = await kv.get(\"key\")\n    assert kv_data.value == b\"Hello!\"\n\n\n@app.on_startup\nasync def setup_broker(context: ContextRepo):\n    await broker.connect()\n\n    kv = await broker.stream.create_key_value(bucket=\"bucket\")\n    context.set_global(\"kv\", kv)\n\n\n@app.after_startup\nasync def test_send(kv: KeyValue):\n    await kv.put(\"key\", b\"Hello!\")\n    await broker.publish(\"Hi!\", \"subject\")\n
","boost":10},{"location":"nats/jetstream/object/","title":"Object Storage","text":"

Object storage is almost identical to the Key-Value stroge concept, so you can reuse the guide.

","boost":10},{"location":"nats/jetstream/object/#overview","title":"Overview","text":"

Object Storage is just a high-level interface on top of NatsJS.

It is a regular JetStream, where the Object key is a subject.

The main difference between KV and Object storages is that in the Object storage, you can store files greater than 1MB (a limitation of KV). It has no limit on the maximum object size and stores it in chunks (each message is an object chunk), so you can literally stream huge objects through NATS.

","boost":10},{"location":"nats/jetstream/object/#faststream-details","title":"FastStream Details","text":"

FastStream has no native interfaces to this NatsJS functionality (yet), but it allows you to access the inner JetStream object to create in manually.

First of all, you need to create an Object storage object and pass in to the context:

from faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import ContextRepo\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n@app.on_startup\nasync def setup_broker(context: ContextRepo):\n    await broker.connect()\n\n    os = await broker.stream.create_object_store(\"bucket\")\n    context.set_global(\"OS\", os)\n

Tip

We placed this code in the @app.on_startup hook because @app.after_startup will be triggered AFTER your handlers start consuming messages. So, if you need to have access to any custom context objects, you should set them up in the @app.on_startup hook.

Also, we call await broker.connect() method manually to establish the connection to be able to create a storage.

Next, we are ready to use this object right in the our handlers.

Let's create an Annotated object to shorten Context object access:

from nats.js.object_store import ObjectStore as OS\nfrom typing_extensions import Annotated\n\nObjectStorage = Annotated[OS, Context(\"OS\")]\n

And just use it in a handler:

from io import BytesIO\n\nfrom faststream import Logger\n\n@broker.subscriber(\"subject\")\nasync def handler(msg: str, os: ObjectStorage, logger: Logger):\n    logger.info(msg)\n    obj = await os.get(\"file\")\n    assert obj.data == b\"File mock\"\n

Finally, let's test our code behavior by putting something into the Object storage and sending a message:

@app.after_startup\nasync def test_send(os: ObjectStorage):\n    await os.put(\"file\", BytesIO(b\"File mock\"))\n    await broker.publish(\"Hi!\", \"subject\")\n

Tip

BytesIO - is a Readable object used to emulate a file opened for reading.

Full listing
from io import BytesIO\n\nfrom nats.js.object_store import ObjectStore as OS\nfrom typing_extensions import Annotated\n\nfrom faststream import Logger\nfrom faststream import Context, FastStream\nfrom faststream.nats import NatsBroker\nfrom faststream.nats.annotations import ContextRepo\n\nObjectStorage = Annotated[OS, Context(\"OS\")]\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\"subject\")\nasync def handler(msg: str, os: ObjectStorage, logger: Logger):\n    logger.info(msg)\n    obj = await os.get(\"file\")\n    assert obj.data == b\"File mock\"\n\n\n@app.on_startup\nasync def setup_broker(context: ContextRepo):\n    await broker.connect()\n\n    os = await broker.stream.create_object_store(\"bucket\")\n    context.set_global(\"OS\", os)\n\n\n@app.after_startup\nasync def test_send(os: ObjectStorage):\n    await os.put(\"file\", BytesIO(b\"File mock\"))\n    await broker.publish(\"Hi!\", \"subject\")\n
","boost":10},{"location":"nats/jetstream/pull/","title":"Pull Subscriber","text":"","boost":10},{"location":"nats/jetstream/pull/#overview","title":"Overview","text":"

NATS JetStream supports two various way to consume messages: Push and Pull consumers.

The Push consumer is used by default to consume messages with the FastStream. It means that the NATS server delivers messages to your consumer as far as possible by itself. However, it also means that NATS should control all current consumer connections and increase server load.

Thus, the Pull consumer is the recommended way to consume JetStream messages by the NATS TEAM. Using it, you simply ask NATS for new messages at some interval. It may sound a little less convenient than automatic message delivery, but it provides several advantages, such as:

So, if you want to consume a large flow of messages without strict time limitations, the Pull consumer is the right choice for you.

","boost":10},{"location":"nats/jetstream/pull/#faststream-details","title":"FastStream Details","text":"

The Pull consumer is just a regular Stream consumer, but with the pull_sub argument, which controls consuming messages with batch size and block interval.

from faststream import FastStream, Logger\nfrom faststream.nats import NatsBroker, PullSub\n\nbroker = NatsBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\n    subject=\"test\",\n    stream=\"stream\",\n    pull_sub=PullSub(batch_size=10),\n)\nasync def handle(msg, logger: Logger):\n    logger.info(msg)\n

The batch size doesn't mean that your msg argument is a list of messages, but it means that you consume up to 10 messages for one request to NATS and call your handler for each message in an asyncio.gather pool.

Tip

If you want to consume list of messages, just set the batch=True in PullSub class.

So, your subject will be processed much faster, without blocking for each message processing. However, if your subject has fewer than 10 messages, your request to NATS will be blocked for timeout (5 seconds by default) while trying to collect the required number of messages. Therefor, you should choose batch_size and timeout accurately to optimize your consumer efficiency.

","boost":10},{"location":"nats/publishing/","title":"Publishing","text":"

FastStream NatsBroker supports all regular publishing usecases. You can use them without any changes.

However, if you wish to further customize the publishing logic, you should take a deeper look at specific NatsBroker parameters.

","boost":10},{"location":"nats/publishing/#nats-publishing","title":"NATS Publishing","text":"

NatsBroker also uses the unified publish method (from a publisher object) to send messages.

import asyncio\nfrom faststream.nats import NatsBroker\n\nasync def pub():\n    async with NatsBroker() as broker:\n        await broker.publish(\n            \"Hi!\",\n            subject=\"test\",\n        )\n\nasyncio.run(pub())\n
","boost":10},{"location":"nats/publishing/#basic-arguments","title":"Basic Arguments","text":"

The publish method accepts the following arguments:

","boost":10},{"location":"nats/publishing/#message-parameters","title":"Message Parameters","text":"","boost":10},{"location":"nats/publishing/#natsjs-parameters","title":"NatsJS Parameters","text":"","boost":10},{"location":"rabbit/","title":"Rabbit Routing","text":"

FastStream RabbitMQ support is implemented on top of aio-pika. You can always get access to objects of it, if you need to use some low-level methods, not represented in FastStream.

","boost":10},{"location":"rabbit/#advantages","title":"Advantages","text":"

The advantage of RabbitMQ is the ability to configure flexible and complex message routing scenarios.

RabbitMQ covers the whole range of routing: from one queue - one consumer, to a queue retrieved from several sources, including message prioritization.

Note

For more information about RabbitMQ, please visit the official documentation

It supports the ability to successfully process messages, mark them as processed with an error, remove them from the queue (it is also impossible to re-receive processed messages, unlike Kafka), lock it for the processing duration, and monitor its current status.

Having to keep track of the current status of all messages is a cause of the RabbitMQ performance issues. With really large message volumes, RabbitMQ starts to degrade. However, if this was a \"one-time influx\", then consumers will free the queue of messages and the \"health\" of RabbitMQ will be stable.

If your scenario is not based on processing millions of messages and also requires building complex routing logic, RabbitMQ will be the right choice.

","boost":10},{"location":"rabbit/#basic-concepts","title":"Basic Concepts","text":"

If you want to totally understand how RabbitMQ works, you should visit their official website. There you will find top-level comments about the basic concepts and usage examples.

","boost":10},{"location":"rabbit/#entities","title":"Entities","text":"

RabbitMQ works with three main entities:

","boost":10},{"location":"rabbit/#routing-rules","title":"Routing Rules","text":"

The rules for delivering messages to consumers depend on the type of exchange and binding parameters. All the main options will be discussed at examples.

In general, the message path looks so:

  1. Publisher sends a message to exchange, specify its routing_key and headers according to which routing will take place.
  2. Exchange, depending on the message parameters, determines which of the subscribed bindings to send the message to.
  3. Binding delivers the message to queue or another exchange (in this case it will send it further by its own rules).
  4. Queue, after receiving a message, sends it to one of subscribed consumers (PUSH API).

Tip

By default, all queues have a binding to the default exchange (Direct type) with a routing key corresponding to their name. In FastStream, queues are connected to this exchange, and messages are sent by default unless another exchange is explicitly specified.

Connecting the queue to any other exchange will still leave it subscribed to the `default exchange'. Be careful with this.

At this stage, the message gets into your application - and you start processing it.

","boost":10},{"location":"rabbit/#message-statuses","title":"Message Statuses","text":"

RabbitMQ requires confirmation of message processing: only after that, it will be removed from the queue.

Confirmation can be either positive (Acknowledgment - ack) if the message was successfully processed or negative (Negative Acknowledgment - nack) if the message was processed with an error.

At the same time, in case of an error, the message can also be extracted from the queue (reject); otherwise, after a negative confirmation, it will be requeued for processing again.

In most cases, FastStream performs all the necessary actions by itself. However, if you want to manage the message lifecycle directly, you can access the message object itself and call the appropriate methods directly. This can be useful if you want to implement an \"at most once\" policy and you need to confirm the consuming of the message before it is actually processed.

","boost":10},{"location":"rabbit/#faststream-specific","title":"FastStream Specific","text":"

FastStream omits the ability to create bindings directly, since in most cases, you do not need to subscribe one queue to several exchanges or subscribe exchanges to each other. On the contrary, this practice leads to over-complication of the message routing scheme, which makes it difficult to maintain and further develop the entire infrastructure of services.

FastStream suggests you adhere to the scheme exchange:queue as 1:N, which will greatly simplify the scheme of interaction between your services. It is better to create an additional queue for a new exchange than to subscribe to an existing one.

However, if you want to reduce the number of entities in your RabbitMQ, and thereby optimize its performance (or you know exactly what you are doing), FastStream leaves you the option to create bindings directly. In other cases, the connection parameters are an integral part of the entities RabbitQueue and RabbitExchange in FastStream.

","boost":10},{"location":"rabbit/ack/","title":"Consuming Acknowledgements","text":"

As you may know, RabbitMQ employs a rather extensive Acknowledgement policy.

In most cases, FastStream automatically acknowledges (acks) messages on your behalf. When your function executes correctly, including sending all responses, a message will be acknowledged (and rejected in case of an exception).

However, there are situations where you might want to use a different acknowledgement logic.

","boost":10},{"location":"rabbit/ack/#retries","title":"Retries","text":"

If you prefer to use a nack instead of a reject when there's an error in message processing, you can specify the retry flag in the @broker.subscriber(...) method, which is responsible for error handling logic.

By default, this flag is set to False, indicating that if an error occurs during message processing, the message can still be retrieved from the queue:

@broker.subscriber(\"test\", retry=False) # don't handle exceptions\nasync def base_handler(body: str):\n    ...\n

If this flag is set to True, the message will be nacked and placed back in the queue each time an error occurs. In this scenario, the message can be processed by another consumer (if there are several of them) or by the same one:

@broker.subscriber(\"test\", retry=True)  # try again indefinitely\nasync def base_handler(body: str):\n    ...\n

If the retry flag is set to an int, the message will be placed back in the queue, and the number of retries will be limited to this number:

@broker.subscriber(\"test\", retry=3)     # make up to 3 attempts\nasync def base_handler(body: str):\n    ...\n

Bug

At the moment, attempts are counted only by the current consumer. If the message goes to another consumer, it will have its own counter. Subsequently, this logic will be reworked.

Tip

For more complex error handling cases, you can use tenacity

","boost":10},{"location":"rabbit/ack/#manual-acknowledgement","title":"Manual acknowledgement","text":"

If you want to acknowledge a message manually, you can get access directy to the message object via the Context and call the method.

from faststream.rabbit.annotations import RabbitMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(body: str, msg: RabbitMessage):\n    await msg.ack()\n    # or\n    await msg.nack()\n    # or\n    await msg.reject()\n

FastStream will see that the message was already acknowledged and will do nothing at process end.

","boost":10},{"location":"rabbit/ack/#interrupt-process","title":"Interrupt Process","text":"

If you want to interrupt message processing at any call stack, you can raise faststream.exceptions.AckMessage

from faststream import FastStream\nfrom faststream.exceptions import AckMessage\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker(\"amqp://guest:guest@localhost:5672/\")\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test-queue\")\nasync def handle(body):\n    smth_processing(body)\n\n\ndef smth_processing(body):\n    if True:\n        raise AckMessage()\n\n\n@app.after_startup\nasync def test_publishing():\n    await broker.publish(\"Hello!\", \"test-queue\")\n

This way, FastStream interrupts the current message proccessing and acknowledges it immediately. Also, you can raise NackMessage and RejectMessage too.

Tip

If you want to disable FastStream Acknowledgement logic at all, you can use @broker.subscriber(..., no_ack=True) option. This way you should always process a message (ack/nack/terminate/etc) by yourself.

","boost":10},{"location":"rabbit/declare/","title":"RabbitMQ Queue/Exchange Declaration","text":"

FastStream declares and validates all exchanges and queues using publishers and subscribers RabbitMQ objects, but sometimes you need to declare them manually.

RabbitBroker provides a way to achieve this easily.

from faststream import FastStream\nfrom faststream.rabbit import (\n    ExchangeType,\n    RabbitBroker,\n    RabbitExchange,\n    RabbitQueue,\n)\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\n\n@app.after_startup\nasync def declare_smth():\n    await broker.declare_exchange(\n        RabbitExchange(\n            name=\"some-exchange\",\n            type=ExchangeType.FANOUT,\n        )\n    )\n\n    await broker.declare_queue(\n        RabbitQueue(\n            name=\"some-queue\",\n            durable=True,\n        )\n    )\n

These methods require just one argument (RabbitQueue/RabbitExchange) containing information about your RabbitMQ required objects. They declare/validate RabbitMQ objects and return low-level aio-pika robust objects to interact with.

Tip

Also, these methods are idempotent, so you can call them with the same arguments multiple times, but the objects will be created once; next time the method will return an already stored object. This way you can get access to any queue/exchange created automatically.

","boost":10},{"location":"rabbit/message/","title":"Access to Message Information","text":"

As you know, FastStream serializes a message body and provides you access to it through function arguments. But sometimes you need access to a message_id, headers, or other meta-information.

","boost":10},{"location":"rabbit/message/#message-access","title":"Message Access","text":"

You can get it in a simple way: just acces the message object in the Context.

This message contains the required information such as:

Also, it is a FastStream wrapper around a native broker library message (aio_pika.IncomingMessage in the RabbitMQ case) that you can access with raw_message.

from faststream.rabbit import RabbitMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    msg: RabbitMessage,\n):\n    print(msg.correlation_id)\n

Also, if you can't find the information you require, you can get access directly to the wrapped aio_pika.IncomingMessage, which contains complete message information.

from aio_pika import IncomingMessage\nfrom faststream.rabbit import RabbitMessage\n\n@broker.subscriber(\"test\")\nasync def base_handler(body: str, msg: RabbitMessage):\n    raw: IncomingMessage = msg.raw_message\n    print(raw)\n
","boost":10},{"location":"rabbit/message/#message-fields-access","title":"Message Fields Access","text":"

But in most cases, you don't need all message fields; you need to access some of them. You can use Context Fields access feature for this reason.

For example, you can access the correlation_id like this:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: str = Context(\"message.correlation_id\"),\n):\n    print(cor_id)\n

Or even directly from the raw message:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: str = Context(\"message.raw_message.correlation_id\"),\n):\n    print(cor_id)\n

But this code is too long to be reused everywhere. In this case, you can use a Python Annotated feature:

python 3.9+python 3.6+
from types import Annotated\nfrom faststream import Context\n\nCorrelationId = Annotated[str, Context(\"message.correlation_id\")]\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: CorrelationId,\n):\n    print(cor_id)\n
from typing_extensions import Annotated\nfrom faststream import Context\n\nCorrelationId = Annotated[str, Context(\"message.correlation_id\")]\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    cor_id: CorrelationId,\n):\n    print(cor_id)\n
","boost":10},{"location":"rabbit/message/#headers-access","title":"Headers Access","text":"

Sure, you can get access to a raw message and get the headers dict itself, but more often you just need a single header field. So, you can easily access it using the Context:

from faststream import Context\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Context(\"message.headers.user\"),\n):\n    ...\n

Using the special Header class is more convenient, as it also validates the header value using Pydantic. It works the same way as Context, but it is just a shorcut to Context with a default setup. So, you already know how to use it:

from faststream import Header\n\n@broker.subscriber(\"test\")\nasync def base_handler(\n    body: str,\n    user: str = Header(),\n):\n    ...\n
","boost":10},{"location":"rabbit/message/#topic-pattern-access","title":"Topic Pattern Access","text":"

As you know, Rabbit allows you to use a pattern like this \"logs.*\" with a Topic exchange. Getting access to the real * value is an often-used scenario and FastStream provide it to you with the Path object (which is a shortcut to Context(\"message.path.*\")).

To use it, you just need to replace your * with {variable-name} and use Path as a regular Context object:

from faststream import Path\nfrom faststream import RabbitQueue, RabbitExchane, ExchangeType\n\n@broker.subscriber(\n    RabbitQueue(\n        \"test-queue\",\n        routing_key=\"logs.{level}\",\n    ),\n    RabbitExchange(\n        \"test-exchange\",\n        type=ExchangeType.TOPIC,\n    )\n)\nasync def base_handler(\n    body: str,\n    level: str = Path(),\n):\n    ...\n
","boost":10},{"location":"rabbit/publishing/","title":"Publishing","text":"

FastStream RabbitBroker supports all regular publishing usecases. you can use them without any changes.

However, if you wish to further customize the publishing logic further, you should take a more deep-dive look at specific RabbitBroker parameters.

","boost":10},{"location":"rabbit/publishing/#rabbit-publishing","title":"Rabbit Publishing","text":"

RabbitBroker also uses the unified publish method (from a publisher object) to send messages.

However, in this case, an object of the aio_pika.Message class (if necessary) can be used as a message (in addition to python primitives and pydantic.BaseModel).

You can specify queue (used as a routing_key) and exchange (optionally) to send by their name.

import asyncio\nfrom faststream.rabbit import RabbitBroker\n\nasync def pub():\n    async with RabbitBroker() as broker:\n        await broker.publish(\n            \"Hi!\",\n            queue=\"test\",\n            exchange=\"test\"\n        )\n\nasyncio.run(pub())\n

If you don't specify any exchange, the message will be send to the default one.

Also, you are able to use special RabbitQueue and RabbitExchange objects as queue and exchange arguments:

from faststream.rabbit import RabbitExchange, RabbitQueue\n\nawait broker.publish(\n    \"Hi!\",\n    queue=RabbitQueue(\"test\"),\n    exchange=RabbitExchange(\"test\")\n)\n

If you specify exchange that doesn't exist, RabbitBroker will create a required one and then publish a message to it.

Tip

Be accurate with it: if you have already created an Exchange with specific parameters and try to send a message by exchange name to it, the broker will try to create it. So, Exchange parameters conflict will occur.

If you are trying to send a message to a specific Exchange, sending it with a defined RabbitExchange object is the preffered way.

","boost":10},{"location":"rabbit/publishing/#basic-arguments","title":"Basic Arguments","text":"

The publish method takes the following arguments:

","boost":10},{"location":"rabbit/publishing/#message-parameters","title":"Message Parameters","text":"

You can read more about all the available flags in the RabbitMQ documentation

","boost":10},{"location":"rabbit/publishing/#send-flags","title":"Send Flags","text":"

Arguments for sending a message:

","boost":10},{"location":"rabbit/rpc/","title":"RPC over RMQ","text":"","boost":10},{"location":"rabbit/rpc/#blocking-request","title":"Blocking Request","text":"

FastStream provides you with the ability to send a blocking RPC request over RabbitMQ in a very simple way.

It uses the Direct Reply-To RabbitMQ feature, so you don't need to create any queues to consume a response.

Just send a message like a regular one and get a response synchronously.

It is very close to common requests syntax:

msg = await broker.publish(\n    \"Hi!\",\n    queue=\"test\",\n    rpc=True,\n)\n

Also, you have two extra options to control this behavior:

","boost":10},{"location":"rabbit/rpc/#reply-to","title":"Reply-To","text":"

Also, if you want to create a permanent request-reply data flow, probably, you should create a permanent queue to consume responses.

So, if you have such one, you can specify it with the reply_to argument. This way, FastStream will send a response to this queue automatically.

@broker.subscriber(\"response-queue\")\nasync def consume_responses(msg):\n    ...\n\nmsg = await broker.publish(\n    \"Hi!\",\n    queue=\"test\",\n    reply_to=\"response-queue\",\n)\n
","boost":10},{"location":"rabbit/security/","title":"FastStream RabbitMQ Security","text":"

This chapter discusses the security options available in FastStream and how to use them.

","boost":10},{"location":"rabbit/security/#security-objects","title":"Security Objects","text":"

FastStream allows you to enhance the security of applications by using security objects when creating brokers. These security objects encapsulate security-related configurations and mechanisms. Security objects supported in FastStream for RabbitMQ are:

","boost":10},{"location":"rabbit/security/#1-basesecurity-object","title":"1. BaseSecurity Object","text":"

Purpose: The BaseSecurity object wraps ssl.SSLContext object and is used to enable SSL/TLS encryption for secure communication between FastStream services and external components such as message brokers.

Usage:

import ssl\n\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.security import BaseSecurity\n\nssl_context = ssl.create_default_context()\nsecurity = BaseSecurity(ssl_context=ssl_context)\n\nbroker = RabbitBroker(security=security)\n
","boost":10},{"location":"rabbit/security/#2-saslplaintext-object-with-ssltls","title":"2. SASLPlaintext Object with SSL/TLS","text":"

Purpose: The SASLPlaintext object is used for authentication in SASL (Simple Authentication and Security Layer) plaintext mode. It allows you to provide a username and password for authentication.

Usage:

import ssl\n\nfrom faststream.rabbit import RabbitBroker\nfrom faststream.security import SASLPlaintext\n\nssl_context = ssl.create_default_context()\nsecurity = SASLPlaintext(\n    ssl_context=ssl_context,\n    username=\"admin\",\n    password=\"password\", \n)\n\nbroker = RabbitBroker(security=security)\n
","boost":10},{"location":"rabbit/examples/","title":"Basic Subscriber","text":"

If you know nothing about RabbitMQ and how it works, you will still able to use FastStream RabbitBroker.

Just use the @broker.subscriber(...) method with a string as a routing key.

from faststream import FastStream\nfrom faststream.rabbit import RabbitBroker\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\"routing_key\")  # handle messages by routing key\nasync def handle(msg):\n    print(msg)\n\n\n@app.after_startup\nasync def test_publish():\n    await broker.publish(\n        \"message\",\n        \"routing_key\",  # publish message with routing key\n    )\n

This is the principle all FastStream brokers work by: you don't need to learn them in-depth if you want to just send a message.

","boost":10},{"location":"rabbit/examples/#rabbitmq-details","title":"RabbitMQ Details","text":"

If you are already familiar with RabbitMQ logic, you should also be acquainted with the inner workings of the example mentioned above.

In this case, FastStream either creates or validates a queue with a specified routing_key and binds it to the default RabbitMQ exchange.

If you want to specify a queue-exchange pair with additional arguments, FastStream provides you with the ability to do so. You can use special RabbitQueue and RabbitExchange objects to configure RabbitMQ queues, exchanges, and binding properties. For examples of using various types of exchanges, please refer to the following articles.

","boost":10},{"location":"rabbit/examples/direct/","title":"Direct Exchange","text":"

The Direct Exchange is the basic way to route messages in RabbitMQ. Its core is very simple: the exchange sends messages to those queues whose routing_key matches the routing_key of the message being sent.

Note

The Default Exchange, to which all queues in RabbitMQ are subscribed, has the Direct type by default.

","boost":10},{"location":"rabbit/examples/direct/#scaling","title":"Scaling","text":"

If several consumers are listening to the same queue, messages will be distributed to one of them (round-robin). This behavior is common for all types of exchange because it refers to the queue itself. The type of exchange affects which queues the message gets into.

Thus, RabbitMQ can independently balance the load on queue consumers. You can increase the processing speed of the message flow from the queue by launching additional instances of a consumer service. You don't need to make changes to the current infrastructure configuration: RabbitMQ will take care of how to distribute messages between your services.

","boost":10},{"location":"rabbit/examples/direct/#example","title":"Example","text":"

Tip

The Direct Exchange is the type used in FastStream by default. You can simply declare it as follows:

@broker.subscriber(\"test_queue\", \"test_exchange\")\nasync def handler():\n    ...\n

The argument auto_delete=True in this and subsequent examples is used only to clear the state of RabbitMQ after example runs.

from faststream import FastStream, Logger\nfrom faststream.rabbit import RabbitBroker, RabbitExchange, RabbitQueue\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\nexch = RabbitExchange(\"exchange\", auto_delete=True)\n\nqueue_1 = RabbitQueue(\"test-q-1\", auto_delete=True)\nqueue_2 = RabbitQueue(\"test-q-2\", auto_delete=True)\n\n\n@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 1\n    await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 2\n    await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 1\n    await broker.publish(queue=\"test-q-2\", exchange=exch)  # handlers: 3\n
","boost":10},{"location":"rabbit/examples/direct/#consumer-announcement","title":"Consumer Announcement","text":"

First, we announce our Direct exchange and several queues that will listen to it:

exch = RabbitExchange(\"exchange\", auto_delete=True)\n\nqueue_1 = RabbitQueue(\"test-q-1\", auto_delete=True)\nqueue_2 = RabbitQueue(\"test-q-2\", auto_delete=True)\n

Then we sign up several consumers using the advertised queues to the exchange we created:

@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n

Note

handler1 and handler2 are subscribed to the same exchange using the same queue: within a single service, this does not make sense, since messages will come to these handlers in turn. Here we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"rabbit/examples/direct/#message-distribution","title":"Message Distribution","text":"

Now, the distribution of messages between these consumers will look like this:

await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 1\n

Message 1 will be sent to handler1 because it listens to the \"exchange\" using a queue with the routing key \"test-q-1\".

await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 2\n

Message 2 will be sent to handler2 because it listens to the \"exchange\" using the same queue, but handler1 is busy.

await broker.publish(queue=\"test-q-1\", exchange=exch)  # handlers: 1\n

Message 3 will be sent to handler1 again because it is currently free.

await broker.publish(queue=\"test-q-2\", exchange=exch)  # handlers: 3\n

Message 4 will be sent to handler3 because it is the only one listening to the \"exchange\" using a queue with the routing key \"test-q-2\".

","boost":10},{"location":"rabbit/examples/fanout/","title":"Fanout Exchange","text":"

The Fanout Exchange is an even simpler, but slightly less popular way of routing in RabbitMQ. This type of exchange sends messages to all queues subscribed to it, ignoring any arguments of the message.

At the same time, if the queue listens to several consumers, messages will also be distributed among them.

","boost":10},{"location":"rabbit/examples/fanout/#example","title":"Example","text":"
from faststream import FastStream, Logger\nfrom faststream.rabbit import ExchangeType, RabbitBroker, RabbitExchange, RabbitQueue\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\nexch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.FANOUT)\n\nqueue_1 = RabbitQueue(\"test-q-1\", auto_delete=True)\nqueue_2 = RabbitQueue(\"test-q-2\", auto_delete=True)\n\n\n@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(exchange=exch)  # handlers: 1, 2, 3\n    await broker.publish(exchange=exch)  # handlers: 1, 2, 3\n    await broker.publish(exchange=exch)  # handlers: 1, 2, 3\n    await broker.publish(exchange=exch)  # handlers: 1, 2, 3\n
","boost":10},{"location":"rabbit/examples/fanout/#consumer-announcement","title":"Consumer Announcement","text":"

To begin with, we announced our Fanout exchange and several queues that will listen to it:

exch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.FANOUT)\n\nqueue_1 = RabbitQueue(\"test-q-1\", auto_delete=True)\nqueue_2 = RabbitQueue(\"test-q-2\", auto_delete=True)\n

Then we signed up several consumers using the advertised queues to the exchange we created:

@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n

Note

handler1 and handler2 are subscribed to the same exchange using the same queue: within a single service, this does not make sense, since messages will come to these handlers in turn. Here we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"rabbit/examples/fanout/#message-distribution","title":"Message Distribution","text":"

Now the all messages will be send to all subscribers due they are binded to the same FANOUT exchange:

await broker.publish(exchange=exch)  # handlers: 1, 2, 3\nawait broker.publish(exchange=exch)  # handlers: 1, 2, 3\nawait broker.publish(exchange=exch)  # handlers: 1, 2, 3\nawait broker.publish(exchange=exch)  # handlers: 1, 2, 3\n

Note

When sending messages to Fanout exchange, it makes no sense to specify the arguments queue or routing_key, because they will be ignored.

","boost":10},{"location":"rabbit/examples/headers/","title":"Header Exchange","text":"

The Header Exchange is the most complex and flexible way to route messages in RabbitMQ. This exchange type sends messages to queues according by matching the queue binding arguments with message headers.

At the same time, if several consumers are subscribed to the queue, messages will also be distributed among them.

","boost":10},{"location":"rabbit/examples/headers/#example","title":"Example","text":"
from faststream import FastStream, Logger\nfrom faststream.rabbit import ExchangeType, RabbitBroker, RabbitExchange, RabbitQueue\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\nexch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.HEADERS)\n\nqueue_1 = RabbitQueue(\n    \"test-queue-1\",\n    auto_delete=True,\n    bind_arguments={\"key\": 1},\n)\nqueue_2 = RabbitQueue(\n    \"test-queue-2\",\n    auto_delete=True,\n    bind_arguments={\"key\": 2, \"key2\": 2, \"x-match\": \"any\"},\n)\nqueue_3 = RabbitQueue(\n    \"test-queue-3\",\n    auto_delete=True,\n    bind_arguments={\"key\": 2, \"key2\": 2, \"x-match\": \"all\"},\n)\n\n\n@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n\n@broker.subscriber(queue_3, exch)\nasync def base_handler4(logger: Logger):\n    logger.info(\"base_handler4\")\n\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 1\n    await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 2\n    await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 1\n    await broker.publish(exchange=exch, headers={\"key\": 2})  # handlers: 3\n    await broker.publish(exchange=exch, headers={\"key2\": 2})  # handlers: 3\n    await broker.publish(\n        exchange=exch, headers={\"key\": 2, \"key2\": 2.0}\n    )  # handlers: 3, 4\n
","boost":10},{"location":"rabbit/examples/headers/#consumer-announcement","title":"Consumer Announcement","text":"

First, we announce our Header exchange and several queues that will listen to it:

exch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.HEADERS)\n\nqueue_1 = RabbitQueue(\n    \"test-queue-1\",\n    auto_delete=True,\n    bind_arguments={\"key\": 1},\n)\nqueue_2 = RabbitQueue(\n    \"test-queue-2\",\n    auto_delete=True,\n    bind_arguments={\"key\": 2, \"key2\": 2, \"x-match\": \"any\"},\n)\nqueue_3 = RabbitQueue(\n    \"test-queue-3\",\n    auto_delete=True,\n    bind_arguments={\"key\": 2, \"key2\": 2, \"x-match\": \"all\"},\n)\n

The x-match argument indicates whether the arguments should match the message headers in whole or in part.

Then we signed up several consumers using the advertised queues to the exchange we created:

@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n\n@broker.subscriber(queue_3, exch)\nasync def base_handler4(logger: Logger):\n    logger.info(\"base_handler4\")\n

Note

handler1 and handler2 are subscribed to the same exchange using the same queue: within a single service, this does not make sense, since messages will come to these handlers in turn. Here we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"rabbit/examples/headers/#message-distribution","title":"Message Distribution","text":"

Now the distribution of messages between these consumers will look like this:

await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 1\n

Message 1 will be sent to handler1 because it listens to a queue whose \"key\" header matches the \"key\" header of the message.

await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 2\n

Message 2 will be sent to handler2 because it listens to exchange using the same queue, but handler1 is busy.

await broker.publish(exchange=exch, headers={\"key\": 1})  # handlers: 1\n

Message 3 will be sent to handler1 again because it is currently free.

await broker.publish(exchange=exch, headers={\"key\": 2})  # handlers: 3\n

Message 4 will be sent to handler3 because it listens to a queue whose \"key\" header coincided with the \"key\" header of the message.

await broker.publish(exchange=exch, headers={\"key2\": 2})  # handlers: 3\n

Message 5 will be sent to handler3 because it listens to a queue whose header \"key2\" coincided with the header \"key2\" of the message.

await broker.publish(\n    exchange=exch, headers={\"key\": 2, \"key2\": 2.0}\n)  # handlers: 3, 4\n

Message 6 will be sent to handler3 and handler4 because the message headers completely match the queue keys.

Note

When sending messages to Header exchange, it makes no sense to specify the arguments queue or routing_key, because they will be ignored

Warning

For incredibly complex routes, you can use the option to bind an exchange to another exchange. In this case, all the same rules apply as for queues subscribed to exchange. The only difference is that the signed exchange can further distribute messages according to its own rules.

So, for example, you can combine Topic and Header exchange types.

","boost":10},{"location":"rabbit/examples/stream/","title":"RabbitMQ Streams","text":"

RabbitMQ has a Streams feature, which is closely related to Kafka topics.

The main difference from regular RabbitMQ queues is that the messages are not deleted after consuming.

And FastStream supports this feature as well!

from faststream import FastStream, Logger\nfrom faststream.rabbit import RabbitBroker, RabbitQueue\n\nbroker = RabbitBroker(max_consumers=10)\napp = FastStream(broker)\n\nqueue = RabbitQueue(\n    name=\"test-stream\",\n    durable=True,\n    arguments={\n        \"x-queue-type\": \"stream\",\n    },\n)\n\n\n@broker.subscriber(\n    queue,\n    consume_args={\"x-stream-offset\": \"first\"},\n)\nasync def handle(msg, logger: Logger):\n    logger.info(msg)\n\n\n@app.after_startup\nasync def test():\n    await broker.publish(\"Hi!\", queue)\n
","boost":10},{"location":"rabbit/examples/topic/","title":"Topic Exchange","text":"

The Topic Exchange is a powerful RabbitMQ routing tool. This type of exchange sends messages to the queue in accordance with the pattern specified when they are connected to exchange and the routing_key of the message itself.

At the same time, if several consumers are subscribed to the queue, messages will be distributed among them.

","boost":10},{"location":"rabbit/examples/topic/#example","title":"Example","text":"
from faststream import FastStream, Logger\nfrom faststream.rabbit import ExchangeType, RabbitBroker, RabbitExchange, RabbitQueue\n\nbroker = RabbitBroker()\napp = FastStream(broker)\n\nexch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.TOPIC)\n\nqueue_1 = RabbitQueue(\"test-queue-1\", auto_delete=True, routing_key=\"*.info\")\nqueue_2 = RabbitQueue(\"test-queue-2\", auto_delete=True, routing_key=\"*.debug\")\n\n\n@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n\n\n@app.after_startup\nasync def send_messages():\n    await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 1\n    await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 2\n    await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 1\n    await broker.publish(routing_key=\"logs.debug\", exchange=exch)  # handlers: 3\n
","boost":10},{"location":"rabbit/examples/topic/#consumer-announcement","title":"Consumer Announcement","text":"

First, we announce our Topic exchange and several queues that will listen to it:

exch = RabbitExchange(\"exchange\", auto_delete=True, type=ExchangeType.TOPIC)\n\nqueue_1 = RabbitQueue(\"test-queue-1\", auto_delete=True, routing_key=\"*.info\")\nqueue_2 = RabbitQueue(\"test-queue-2\", auto_delete=True, routing_key=\"*.debug\")\n

At the same time, in the routing_key of our queues, we specify the pattern of routing keys that will be processed by this queue.

Then we sign up several consumers using the advertised queues to the exchange we created:

@broker.subscriber(queue_1, exch)\nasync def base_handler1(logger: Logger):\n    logger.info(\"base_handler1\")\n\n\n@broker.subscriber(queue_1, exch)  # another service\nasync def base_handler2(logger: Logger):\n    logger.info(\"base_handler2\")\n\n\n@broker.subscriber(queue_2, exch)\nasync def base_handler3(logger: Logger):\n    logger.info(\"base_handler3\")\n

Note

handler1 and handler2 are subscribed to the same exchange using the same queue: within a single service, this does not make sense, since messages will come to these handlers in turn. Here we emulate the work of several consumers and load balancing between them.

","boost":10},{"location":"rabbit/examples/topic/#message-distribution","title":"Message Distribution","text":"

Now the distribution of messages between these consumers will look like this:

await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 1\n

Message 1 will be sent to handler1 because it listens to \"exchange\" using a queue with the routing key \"*.info\".

await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 2\n

Message 2 will be sent to handler2 because it listens to \"exchange\" using the same queue, but handler1 is busy.

await broker.publish(routing_key=\"logs.info\", exchange=exch)  # handlers: 1\n

Message 3 will be sent to handler1 again because it is currently free.

await broker.publish(routing_key=\"logs.debug\", exchange=exch)  # handlers: 3\n

Message 4 will be sent to handler3 because it is the only one listening to \"exchange\" using a queue with the routing key \"*.debug\".

","boost":10},{"location":"redis/","title":"Redis Broker","text":"","boost":10},{"location":"redis/#redis-overview","title":"Redis Overview","text":"","boost":10},{"location":"redis/#what-is-redis","title":"What is Redis?","text":"

Redis is an open-source, in-memory data structure store, used as a database, cache, and message broker. It supports various data structures such as strings, hashes, lists, sets, sorted sets, bitmaps, hyperloglogs, and geospatial indexes with radius queries. Redis has built-in replication, Lua scripting, LRU eviction, transactions, and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.

","boost":10},{"location":"redis/#key-redis-concepts","title":"Key Redis Concepts","text":"

Redis is not just a key-value store; it is a data structures server, supporting different kinds of values. This makes Redis flexible and suitable for a wide range of problems. It offers versatile approaches for message handling through Pub/Sub, List, and Stream structures.

","boost":10},{"location":"redis/#1-pubsub","title":"1. Pub/Sub","text":"

Redis Pub/Sub implements the Publish/Subscribe messaging paradigm where senders (publishers) are not programmed to send their messages to specific receivers (subscribers). Instead, published messages are characterized into channels, without knowledge of what (if any) subscribers there may be.

","boost":10},{"location":"redis/#2-list","title":"2. List","text":"

In contrast, Redis List capitalizes on a straightforward list data structure. Messages, pushed by producers, form a first-in, first-out (FIFO) queue. Consumers, in turn, retrieve messages from this ordered list, providing a simplified mechanism for sequential message processing.

","boost":10},{"location":"redis/#3-streams","title":"3. Streams","text":"

Redis Streams introduce a more advanced concept, embracing an append-only log-like structure. Messages, organized as entries, allow for nuanced features like consumer groups, enabling parallel processing, and acknowledgment for precise message handling. Streams excel in scenarios demanding scalability, persistence, and ordered message processing.

Ultimately, the choice between Pub/Sub, List, or Streams hinges on the specific needs of the application. Redis Pub/Sub suits real-time communication, List offers simplicity in ordered processing, while Streams cater to complex, scalable, and ordered message handling, each providing tailored solutions based on distinct use case requirements.

","boost":10},{"location":"redis/#redis-in-faststream","title":"Redis in FastStream","text":"","boost":10},{"location":"redis/#faststream-redisbroker","title":"FastStream RedisBroker","text":"

The FastStream RedisBroker is a key component of the FastStream framework that enables seamless integration with Redis. With the RedisBroker, developers can easily connect to Redis instances, publish messages to Redis channels, and subscribe to Redis channels within their FastStream applications.

","boost":10},{"location":"redis/#establishing-a-connection","title":"Establishing a Connection","text":"

To connect to Redis using the FastStream RedisBroker module, follow these steps:

  1. Initialize the RedisBroker instance: Start by initializing a RedisBroker instance with the necessary configuration, including Redis server address and port.

  2. Create your processing logic: Write a function that will consume the incoming messages from the subscribed channel and optionally publish a response to another channel.

  3. Decorate your processing function: To connect your processing function to the desired Redis channels, you need to decorate it with @broker.subscriber(...) and @broker.publisher(...) decorators. Now, after you start your application, your processing function will be called whenever a new message in the subscribed channel is available and produce the function return value to the channel defined in the publisher decorator.

Here's a simplified code example demonstrating how to establish a connection to Redis using FastStream's RedisBroker module:

from faststream import FastStream\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n@broker.subscriber(\"in-channel\")\n@broker.publisher(\"out-channel\")\nasync def handle_msg(user: str, user_id: int) -> str:\n    return f\"User: {user_id} - {user} registered\"\n

This minimal example illustrates how FastStream simplifies the process of connecting to Redis and performing basic message processing from the in-channel to the out-channel. Depending on your specific use case and requirements, you can further customize your Redis integration with FastStream to build efficient and responsive applications.

For more advanced configuration options and detailed usage instructions, please refer to the FastStream Redis documentation and the official Redis documentation.

","boost":10},{"location":"redis/message/","title":"Accessing Redis Message Information with FastStream","text":"

In FastStream, messages passed through a Redis broker are serialized and can be interacted with just like function parameters. However, you might occasionally need to access more than just the message content, such as metadata and other attributes.

","boost":10},{"location":"redis/message/#redis-message-access","title":"Redis Message Access","text":"

When dealing with Redis broker in FastStream, you can easily access message details by using the RedisMessage object which wraps the underlying message with additional context information. This object is specifically tailored for Redis and contains relevant message attributes:

For instance, if you need to retrieve headers from an incoming Redis message, here\u2019s how you might do it:

from faststream.redis import RedisMessage\n\n@broker.subscriber(\"test-stream\")\nasync def stream_handler(msg: str, message: RedisMessage):\n    print(message.headers)\n
","boost":10},{"location":"redis/message/#targeted-message-fields-access","title":"Targeted Message Fields Access","text":"

It's common to require only specific elements of the message rather than the entire data structure. For this purpose, FastStream allows you to access individual message fields by specifying the field you are interested in as an argument in your handler function.

For example, if you want to access the headers directly, you might do it as follows:

from faststream import Context\n\n@broker.subscriber(\"test-stream\")\nasync def stream_handler(\n    msg: str,\n    headers: AnyDict = Context(\"message.headers\"),\n):\n    print(headers)\n

The Context object lets you reference message attributes directly, making your handler functions neater and reducing the amount of boilerplate code needed.

","boost":10},{"location":"redis/rpc/","title":"Redis RPC with FastStream","text":"

FastStream RedisBroker provides the powerful capability to perform Remote Procedure Calls (RPC) using Redis. This feature enables you to send a message and await a response, effectively creating a synchronous request-response pattern over the inherently asynchronous Redis messaging system. Below is the guide to set up and utilize the Redis RPC publishing feature with FastStream.

Note

The RPC feature is implemented over Redis Pub/Sub indepenently of the original subscriber type.

","boost":10},{"location":"redis/rpc/#rpc-with-redis-overview","title":"RPC with Redis Overview","text":"

In a traditional publish/subscribe setup, the publishing party sends messages without expecting any direct response from the subscribers. However, with RPC, the publisher sends a message and waits for a response from the subscriber, which can then be used for subsequent operations or processing.

FastStream allows you to define RPC-style communication channels, lists, or streams by using the RedisBroker's publishing function with the rpc flag set to True.

","boost":10},{"location":"redis/rpc/#implementing-redis-rpc-in-faststream","title":"Implementing Redis RPC in FastStream","text":"

To implement Redis RPC with RedisBroker in FastStream, follow the steps below:

  1. Initiate your FastStream application with RedisBroker

    broker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n
  2. Define subscriber handlers for various Redis data types (e.g., channel, list, stream) that can process incoming messages and return responses.

    @broker.subscriber(channel=\"test-channel\")\nasync def handle_channel(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n\n\n@broker.subscriber(list=\"test-list\")\nasync def handle_list(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n\n\n@broker.subscriber(stream=\"test-stream\")\nasync def handle_stream(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n
  3. Send RPC messages through RedisBroker and await responses on the correct data type.

    After your application has started and the subscribers are ready to receive messages, you can publish messages with the rpc option enabled. Additionally, you can set an rpc_timeout to decide how long the publisher should wait for a response before timing out.

    @app.after_startup\nasync def t():\n    msg = \"Hi!\"\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        channel=\"test-channel\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        list=\"test-list\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        stream=\"test-stream\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n

In this example, we assert that the msg sent is the same as the response received from the subscriber, demonstrating an operational RPC pattern over three different Redis data types.

","boost":10},{"location":"redis/rpc/#full-example-of-redis-rpc-with-faststream","title":"Full Example of Redis RPC with FastStream","text":"

Combining all the code snippets above, here is the complete example of how to set up Redis RPC with FastStream RedisBroker:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(channel=\"test-channel\")\nasync def handle_channel(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n\n\n@broker.subscriber(list=\"test-list\")\nasync def handle_list(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n\n\n@broker.subscriber(stream=\"test-stream\")\nasync def handle_stream(msg: str, logger: Logger):\n    logger.info(msg)\n    return msg\n\n\n@app.after_startup\nasync def t():\n    msg = \"Hi!\"\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        channel=\"test-channel\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        list=\"test-list\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n\n    assert msg == await broker.publish(\n        \"Hi!\",\n        stream=\"test-stream\",\n        rpc=True,\n        rpc_timeout=3.0,\n    )\n

By embracing Redis RPC with FastStream, you can build sophisticated message-based architectures that require direct feedback from message processors. This feature is particularly suitable for cases where immediate processing is necessary or calling functions across different services is essential.

","boost":10},{"location":"redis/security/","title":"FastStream Redis Security","text":"

This chapter discusses the security options available in FastStream and how to use them.

","boost":10},{"location":"redis/security/#security-objects","title":"Security Objects","text":"

FastStream allows you to enhance the security of applications by using security objects when creating brokers. These security objects encapsulate security-related configurations and mechanisms. Security objects supported in FastStream for Redis are:

","boost":10},{"location":"redis/security/#1-basesecurity-object","title":"1. BaseSecurity Object","text":"

Purpose: The BaseSecurity object wraps ssl.SSLContext object and is used to enable SSL/TLS encryption for secure communication between FastStream services and external components such as message brokers.

Usage:

import ssl\n\nfrom faststream.redis import RedisBroker\nfrom faststream.security import BaseSecurity\n\nssl_context = ssl.create_default_context()\nsecurity = BaseSecurity(ssl_context=ssl_context)\n\nbroker = RedisBroker(security=security)\n
","boost":10},{"location":"redis/security/#2-saslplaintext-object-with-ssltls","title":"2. SASLPlaintext Object with SSL/TLS","text":"

Purpose: The SASLPlaintext object is used for authentication in SASL (Simple Authentication and Security Layer) plaintext mode. It allows you to provide a username and password for authentication.

Usage:

import ssl\n\nfrom faststream.redis import RedisBroker\nfrom faststream.security import SASLPlaintext\n\nssl_context = ssl.create_default_context()\nsecurity = SASLPlaintext(\n    ssl_context=ssl_context,\n    username=\"admin\",\n    password=\"password\", \n)\n\nbroker = RedisBroker(security=security)\n
","boost":10},{"location":"redis/list/","title":"Redis Lists","text":"

Redis Lists are a simple and flexible data structure that function as ordered collections of strings. They are similar to lists in programming languages, and Redis provides commands to perform a variety of operations such as adding, retrieving, and removing elements from either end of the list.

Redis Lists are particularly useful for scenarios such as implementing queues, effectively using the list as a FIFO (First-In-First-Out) structure.

","boost":10},{"location":"redis/list/batch/","title":"Redis List Batch Subscriber","text":"

If you want to consume data in batches from a Redis list, the @broker.subscriber(...) decorator makes it possible. By defining your consumed msg object as a list of messages and setting the batch parameter to True within the ListSub object, the subscriber will call your consuming function with a batch of messages. Let's walk through how to achieve this with the FastStream library.

","boost":10},{"location":"redis/list/batch/#using-the-subscriber-with-batching","title":"Using the Subscriber with Batching","text":"

To consume messages in batches from a Redis list, follow these steps:

","boost":10},{"location":"redis/list/batch/#step-1-define-your-subscriber","title":"Step 1: Define Your Subscriber","text":"

In your FastStream application, define the subscriber using the @broker.subscriber(...) decorator. Ensure that you pass a ListSub object with the batch parameter set to True. This configuration tells the subscriber to handle message consumption in batches from the specified Redis list.

@broker.subscriber(list=ListSub(\"test-list\", batch=True))\n
","boost":10},{"location":"redis/list/batch/#step-2-implement-your-consuming-function","title":"Step 2: Implement Your Consuming Function","text":"

Create a consuming function that accepts the list of messages. The @broker.subscriber(...) decorator will take care of collecting and grouping messages into batches.

@broker.subscriber(list=ListSub(\"test-list\", batch=True))\nasync def handle(msg: list[str], logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/list/batch/#example-of-consuming-in-batches","title":"Example of Consuming in Batches","text":"

Let's illustrate how to consume messages in batches from the \"test-list\" Redis list with a practical example:

from faststream import FastStream, Logger\nfrom faststream.redis import ListSub, RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(list=ListSub(\"test-list\", batch=True))\nasync def handle(msg: list[str], logger: Logger):\n    logger.info(msg)\n

In this example, the subscriber is configured to process messages in batches from the Redis list, and the consuming function is designed to handle these batches efficiently.

Consuming messages in batches is a valuable technique when you need to optimize the processing of high volumes of data in your Redis-based applications. It allows for more efficient resource utilization and can enhance the overall performance of your data processing tasks.

","boost":10},{"location":"redis/list/batch/#batch-publishing","title":"Batch publishing","text":"

Also, Redis List is the only data structure supporting publishing in batches with FastStream. To send multiple messages in a single request, you just need to:

","boost":10},{"location":"redis/list/publishing/","title":"Redis List Publishing with FastStream","text":"

Utilizing the FastStream library, you can effectively publish data to Redis lists, which act as queues in Redis-based messaging systems.

","boost":10},{"location":"redis/list/publishing/#understanding-redis-list-publishing","title":"Understanding Redis List Publishing","text":"

Just like with Redis streams, messages can be published to Redis lists. FastStream utilizes the @broker.publisher(...) decorator, along with a list's name, to push messages onto the list.

  1. Instantiate your RedisBroker

    broker = RedisBroker(\"localhost:6379\")\n
  2. Create your FastStream application with the instantiated RedisBroker

    app = FastStream(broker)\n
  3. Define a Pydantic model for your data

    class Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n
  4. Implement a data processing function for publishing to Redis lists

    Use the @broker.publisher(list=\"...\") decorator alongside the @broker.subscriber(list=\"...\") decorator to create a function that processes incoming messages and pushes the results to an output list in Redis.

    @broker.subscriber(list=\"input-list\")\n@broker.publisher(list=\"output-list\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n

In this pattern, the function stands as a subscriber to the \"input-list\" and publishes the processed data as a new message to the \"output-list\". By using decorators, you establish a pipeline that reads messages from one Redis list, applies some logic, and then pushes outputs to another list.

","boost":10},{"location":"redis/list/publishing/#full-example-of-redis-list-publishing","title":"Full Example of Redis List Publishing","text":"

Here's an example that demonstrates Redis list publishing in action using decorators with FastStream:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = RedisBroker(\"localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(list=\"input-list\")\n@broker.publisher(list=\"output-list\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n

The provided example illustrates the ease of setting up publishing mechanisms to interact with Redis lists. In this environment, messages are dequeued from the input list, processed, and enqueued onto the output list seamlessly, empowering developers to leverage Redis lists as messaging queues.

By following these simple steps, you can perform list-based publish/subscribe operations in a Redis environment using the FastStream library, capitalizing on Redis' fast, in-memory data structure store capabilities.

","boost":10},{"location":"redis/list/subscription/","title":"Redis List Basic Subscriber","text":"

To start consuming from a Redis list, simply decorate your consuming function with the @broker.subscriber(...) decorator, passing a string as the list key.

In the following example, we will create a simple FastStream app that will consume messages from a \"test-list\" Redis list.

The full app code looks like this:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(list=\"test-list\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/list/subscription/#import-faststream-and-redisbroker","title":"Import FastStream and RedisBroker","text":"

To use the @broker.subscriber(...) decorator, first, we need to import the base FastStream app and RedisBroker to create our broker.

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n
","boost":10},{"location":"redis/list/subscription/#create-a-redisbroker","title":"Create a RedisBroker","text":"

Next, we will create a RedisBroker object and wrap it into the FastStream object so that we can start our app using CLI later.

broker = RedisBroker()\napp = FastStream(broker)\n
","boost":10},{"location":"redis/list/subscription/#create-a-function-that-will-consume-messages-from-a-redis-list","title":"Create a Function that will Consume Messages from a Redis list","text":"

Let\u2019s create a consumer function that will consume messages from \"test-list\" Redis list and log them.

@broker.subscriber(list=\"test-list\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n

The function decorated with the @broker.subscriber(...) decorator will be called when a message is pushed to the Redis list.

The message will then be injected into the typed msg argument of the function, and its type will be used to parse the message.

In this example case, when the message is pushed to a \"test-list\" list, it will be received by the handle function, and the logger will log the message content.

","boost":10},{"location":"redis/pubsub/","title":"Redis Channels","text":"

Redis Pub/Sub Channels are a feature of Redis that enables messaging between clients through a publish/subscribe (pub/sub) pattern. A Redis channel is essentially a medium through which messages are transmitted. Different clients can subscribe to these channels to listen for messages, while other clients can publish messages to these channels.

When a message is published to a Redis channel, all subscribers to that channel receive the message instantly. This makes Redis channels suitable for a variety of real-time applications such as chat rooms, notifications, live updates, and many more use cases where messages must be broadcast promptly to multiple clients.

","boost":10},{"location":"redis/pubsub/#limitations","title":"Limitations","text":"

Redis Pub/Sub Channels, while powerful for real-time communication in scenarios like chat rooms and live updates, have certain limitations when compared to Redis List and Redis Streams.

In summary, while Redis Pub/Sub excels in simplicity and real-time broadcast scenarios, Redis List and Redis Streams provide additional features such as message persistence, ordered processing, and scalability, making them better suited for certain use cases with specific requirements. The choice between these Redis features depends on the nature of the application and its messaging needs.

","boost":10},{"location":"redis/pubsub/publishing/","title":"Publishing","text":"

The FastStream RedisBroker supports all standard publishing use cases similar to the KafkaBroker, allowing you to publish messages to Redis channels with ease.

Below you will find guidance on how to utilize the RedisBroker for publishing messages, including creating publisher objects and using decorators for streamlined publishing workflows.

","boost":10},{"location":"redis/pubsub/publishing/#basic-redis-channel-publishing","title":"Basic Redis Channel Publishing","text":"

The RedisBroker allows you to publish messages directly to Redis channels. You can use Python primitives and pydantic.BaseModel to define the content of the message.

To publish a message to a Redis channel, follow these steps:

  1. Create your RedisBroker instance

    broker = RedisBroker(\"redis://localhost:6379\")\n
  2. Publish a message using the publish method

    await broker.publish(msg, \"input_data\")\n

This is the most straightforward way to use the RedisBroker to publish messages to Redis channels.

","boost":10},{"location":"redis/pubsub/publishing/#creating-a-publisher-object","title":"Creating a publisher object","text":"

For a more structured approach and to include your publishers in the AsyncAPI documentation, it's recommended to create publisher objects. Here's how to do it:

  1. Create your RedisBroker instance

    broker = RedisBroker(\"redis://localhost:6379\")\n
  2. Create a publisher instance for a specific channel

    prepared_publisher = broker.publisher(\"input_data\")\n
  3. Publish a message using the publish method of the prepared publisher

    await prepared_publisher.publish(msg)\n

When you encapsulate your broker within a FastStream object, the publisher will be documented in your service's AsyncAPI documentation.

","boost":10},{"location":"redis/pubsub/publishing/#decorating-your-publishing-functions","title":"Decorating your publishing functions","text":"

Decorators in FastStream provide a convenient way to define the data flow within your application. The RedisBroker allows you to use decorators to publish messages to Redis channels, similar to the KafkaBroker.

By decorating a function with both @broker.subscriber(...) and @broker.publisher(...), you create a DataPipeline unit that processes incoming messages and publishes the results to another channel. The order of decorators does not matter, but they must be applied to a function that has already been decorated by a @broker.subscriber(...).

The decorated function should have a return type annotation to ensure the correct interpretation of the return value before it's published.

Here's an example of using decorators with RedisBroker:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\nto_output_data = broker.publisher(\"output_data\")\n\n\n@to_output_data\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
  1. Initialize the RedisBroker instance: Start by creating a RedisBroker instance.

    broker = RedisBroker(\"redis://localhost:6379\")\n
  2. Prepare your publisher object to be used as a decorator:

    to_output_data = broker.publisher(\"output_data\")\n
  3. Create your processing logic: Implement a function that will process incoming messages and produce a response to be published to another Redis channel.

    async def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
  4. Decorate your processing function: Apply the @broker.subscriber(...) and @broker.publisher(...) decorators to your function to define the input channel and the output channel, respectively. Once your application is running, this decorated function will be triggered whenever a new message arrives on the \"input_data\" channel, and it will publish the result to the \"output_data\" channel.

    @to_output_data\n@broker.subscriber(\"input_data\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
","boost":10},{"location":"redis/pubsub/subscription/","title":"Channel Subscription","text":"","boost":10},{"location":"redis/pubsub/subscription/#basic-channel-subscription","title":"Basic Channel Subscription","text":"

Redis Pub/Sub is the default subscriber type in FastStream, so you can simply create a regular @broker.subscriber(\"channel_name\") with a channel name and it creates a subscriber using Redis Pub/Sub.

In this example, we will build a FastStream application that listens to messages from the Redis channel named \"test\".

The complete application code is presented below:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/pubsub/subscription/#import-faststream-and-redisbroker","title":"Import FastStream and RedisBroker","text":"

To utilize the @broker.subscriber(...) decorator for Redis channel subscription, you must first import FastStream and RedisBroker.

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n
","boost":10},{"location":"redis/pubsub/subscription/#create-a-redisbroker-instance","title":"Create a RedisBroker Instance","text":"

Create a RedisBroker object and pass it to the FastStream object. This setup prepares the application for launch using the FastStream CLI.

broker = RedisBroker()\napp = FastStream(broker)\n
","boost":10},{"location":"redis/pubsub/subscription/#define-the-message-handler-function","title":"Define the Message Handler Function","text":"

Construct a function that will act as the consumer of messages from the \"test\" channel and use the logger to output the message content.

@broker.subscriber(\"test\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n

When a message is published to the Redis channel \"test\", it will trigger the invocation of the decorated function. The message will be passed to the function's msg parameter, while the logger will be available for logging purposes.

","boost":10},{"location":"redis/pubsub/subscription/#pattern-channel-subscription","title":"Pattern Channel Subscription","text":"

For subscribing to multiple Redis channels matching a pattern, use the @broker.subscriber(channel=PubSub(\"pattern\", pattern=True)) decorator, where the channel argument receives a PubSub object with the pattern and pattern flag set to True.

Here's how to create a FastStream application that subscribes to all channels matching the \"test.*\" pattern:

from faststream import FastStream, Logger\nfrom faststream.redis import PubSub, RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(channel=PubSub(\"test.*\", pattern=True))\nasync def handle_test(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/pubsub/subscription/#use-pubsub-for-pattern-matching","title":"Use PubSub for Pattern Matching","text":"

Import the PubSub class from faststream.redis along with other necessary modules.

from faststream import FastStream, Logger\nfrom faststream.redis import PubSub, RedisBroker\n
","boost":10},{"location":"redis/pubsub/subscription/#specify-the-pattern-for-channel-subscription","title":"Specify the Pattern for Channel Subscription","text":"

To define the pattern subscription, create a PubSub object with the desired pattern (\"test.*\" in this case) and indicate that it's a pattern subscription by setting pattern=True.

@broker.subscriber(channel=PubSub(\"test.*\", pattern=True))\n
","boost":10},{"location":"redis/pubsub/subscription/#create-the-pattern-message-handler-function","title":"Create the Pattern Message Handler Function","text":"

Decide on a function that will act as the subscriber of messages from channels matching the specified pattern. Logging the messages is handled similarly as with basic channel subscription.

@broker.subscriber(channel=PubSub(\"test.*\", pattern=True))\nasync def handle_test(msg: str, logger: Logger):\n    logger.info(msg)\n

With pattern channel subscription, when a message is published to a channel that matches the specified pattern (\"test.*\"), our handler function will be invoked. The message is delivered to the msg argument of the function, similar to how it works in basic channel subscriptions.

","boost":10},{"location":"redis/pubsub/subscription/#pattern-data-access","title":"Pattern data access","text":"

You can also use the Redis Pub/Sub pattern feature to encode some data directly in the channel name. With FastStream you can easily access this data using the following code:

from faststream import FastStream, Logger, Path\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(\"test.{data}\")\nasync def handle_test(\n    msg: str,\n    logger: Logger,\n    data: str = Path(),\n):\n    logger.info(f\"Channel `{data=}`, body `{msg=}`\")\n
","boost":10},{"location":"redis/streams/","title":"Redis Streams","text":"

Redis Streams are a data structure introduced in Redis 5.0 that offer a reliable and highly scalable way to handle streams of data. They are similar to logging systems like Apache Kafka, where data is stored in a log structure and can be consumed by multiple clients. Streams provide a sequence of ordered messages, and they are designed to handle a high volume of data by allowing partitioning and multiple consumers.

A Redis Stream is a collection of entries, each having an ID (which includes a timestamp) and a set of key-value pairs representing the message data. Clients can add to a stream by generating a new entry and can read from a stream to consume its messages.

Streams have unique features such as:

","boost":10},{"location":"redis/streams/ack/","title":"Stream Acknowledgement","text":"

When working with Redis streams in the FastStream library, it's important to manage message acknowledgements carefully to ensure that messages are not lost and that they have been processed as intended.

By default, when using the FastStream with a Redis stream, the library will automatically acknowledge (ack) that a message has been processed. This follows the at most once processing guarantee.

","boost":10},{"location":"redis/streams/ack/#manual-acknowledgement","title":"Manual Acknowledgement","text":"

In cases where you want explicit control over when a message is acknowledged, you can manually acknowledge a message by accessing the ack and nack methods provided:

from faststream.redis.annotations import RedisMessage, Redis\n\n# Setup broker and faststream app\n...\n\n@broker.subscriber(StreamSub(\"test-stream\", group=\"test-group\", consumer=\"1\"))\nasync def base_handler(body: dict, msg: RedisMessage, redis: Redis):\n    # Process the message\n    ...\n\n    # Manually acknowledge the message\n    await msg.ack(redis)\n    # or, if processing fails and you want to reprocess later\n    await msg.nack()\n

Using ack will mark the message as processed in the stream, while nack is useful for situations where you might need to reprocess a message due to a handling failure.

","boost":10},{"location":"redis/streams/ack/#interrupt-process","title":"Interrupt Process","text":"

If the need arises to instantly interrupt message processing at any point in the call stack and acknowledge the message, you can achieve this by raising the faststream.exceptions.AckMessage exception:

from faststream import FastStream\nfrom faststream.exceptions import AckMessage\nfrom faststream.redis import RedisBroker, StreamSub\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(stream=StreamSub(\"test-stream\", group=\"test-group\", consumer=\"1\"))\nasync def handle(body):\n    processing_logic(body)\n\n\ndef processing_logic(body):\n    if True:\n        raise AckMessage()\n\n\n@app.after_startup\nasync def test_publishing():\n    await broker.publish(\"Hello World!\", stream=\"test-stream\")\n

By raising AckMessage, FastStream will halt the current message processing routine and immediately acknowledge it. Analogously, raising NackMessage would prevent the message from being acknowledged and could lead to its subsequent reprocessing by the same or a different consumer.

Tip

If you want to disable FastStream Acknowledgement logic at all, you can use @broker.subscriber(..., no_ack=True) option. This way you should always process a message (ack/nack/terminate/etc) by yourself.

","boost":10},{"location":"redis/streams/batch/","title":"Redis Stream Batch Subscriber","text":"

If you want to consume data in batches from a Redis stream, the @broker.subscriber(...) decorator makes it possible. By defining your consumed msg object as a list of messages and setting the batch parameter to True within the StreamSub object, the subscriber will call your consuming function with a batch of messages. Let's walk through how to achieve this with the FastStream library.

","boost":10},{"location":"redis/streams/batch/#using-the-subscriber-with-batching","title":"Using the Subscriber with Batching","text":"

To consume messages in batches from a Redis stream, follow these steps:

","boost":10},{"location":"redis/streams/batch/#step-1-define-your-subscriber","title":"Step 1: Define Your Subscriber","text":"

In your FastStream application, define the subscriber using the @broker.subscriber(...) decorator. Ensure that you pass a StreamSub object with the batch parameter set to True. This configuration tells the subscriber to handle message consumption in batches from the specified Redis stream.

@broker.subscriber(stream=StreamSub(\"test-stream\", batch=True))\n
","boost":10},{"location":"redis/streams/batch/#step-2-implement-your-consuming-function","title":"Step 2: Implement Your Consuming Function","text":"

Create a consuming function that accepts the list of messages. The @broker.subscriber(...) decorator will take care of collecting and grouping messages into batches.

@broker.subscriber(stream=StreamSub(\"test-stream\", batch=True))\nasync def handle(msg: list[str], logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/streams/batch/#example-of-consuming-in-batches","title":"Example of Consuming in Batches","text":"

Let's illustrate how to consume messages in batches from the \"test-stream\" Redis stream with a practical example:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker, StreamSub\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(stream=StreamSub(\"test-stream\", batch=True))\nasync def handle(msg: list[str], logger: Logger):\n    logger.info(msg)\n

In this example, the subscriber is configured to process messages in batches from the Redis stream, and the consuming function is designed to handle these batches efficiently.

Consuming messages in batches is a valuable technique when you need to optimize the processing of high volumes of data in your Redis-based applications. It allows for more efficient resource utilization and can enhance the overall performance of your data processing tasks.

","boost":10},{"location":"redis/streams/groups/","title":"Redis Stream Consumer Groups","text":"

Consuming messages from a Redis stream can be accomplished by using a Consumer Group. This allows multiple consumers to divide the workload of processing messages in a stream and provides a form of message acknowledgment, ensuring that messages are not processed repeatedly.

Consumer Groups in Redis enable a group of clients to cooperatively consume different portions of the same stream of messages. When using group=\"...\" (which internally uses XREADGROUP), messages are distributed among different consumers in a group and are not delivered to any other consumer in that group again, unless they are not acknowledged (i.e., the client fails to process and does not call msg.ack() or XACK). This is in contrast to a normal consumer (also known as XREAD), where every consumer sees all the messages. XREAD is useful for broadcasting to multiple consumers, while XREADGROUP is better suited for workload distribution.

In the following example, we will create a simple FastStream app that utilizes a Redis stream with a Consumer Group. It will consume messages sent to the \"test-stream\" as part of the \"test-group\" consumer group.

The full app code is as follows:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker, StreamSub\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(stream=StreamSub(\"test-stream\", group=\"test-group\", consumer=\"1\"))\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n\n\n@app.after_startup\nasync def t():\n    await broker.publish(\"Hi!\", stream=\"test-stream\")\n
","boost":10},{"location":"redis/streams/groups/#import-faststream-and-redisbroker","title":"Import FastStream and RedisBroker","text":"

First, import the FastStream class and the RedisBroker from the faststream.redis module to define our broker.

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker, StreamSub\n
","boost":10},{"location":"redis/streams/groups/#create-a-redisbroker","title":"Create a RedisBroker","text":"

To establish a connection to Redis, instantiate a RedisBroker object and pass it to the FastStream app.

broker = RedisBroker()\napp = FastStream(broker)\n
","boost":10},{"location":"redis/streams/groups/#define-a-consumer-group-subscription","title":"Define a Consumer Group Subscription","text":"

Define a subscription to a Redis stream with a specific Consumer Group using the StreamSub object and the @broker.subscriber(...) decorator. Then, define a function that will be triggered when new messages are sent to the \"test-stream\" Redis stream. This function is decorated with @broker.subscriber(...) and will process the messages as part of the \"test-group\" consumer group.

@broker.subscriber(stream=StreamSub(\"test-stream\", group=\"test-group\", consumer=\"1\"))\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/streams/groups/#publishing-a-message","title":"Publishing a message","text":"

Publishing a message is the same as what's defined on Stream Publishing.

await broker.publish(\"Hi!\", stream=\"test-stream\")\n

By following the steps and code examples provided above, you can create a FastStream application that consumes messages from a Redis stream using a Consumer Group for distributed message processing.

","boost":10},{"location":"redis/streams/publishing/","title":"Redis Stream Publishing with FastStream","text":"","boost":10},{"location":"redis/streams/publishing/#publishing-data-to-redis-stream","title":"Publishing Data to Redis Stream","text":"

To publish messages to a Redis Stream, you implement a function that processes the incoming data and applies the @broker.publisher(...) decorator along with the Redis stream name to it. The function will then publish its return value to the specified stream.

  1. Create your RedisBroker instance

    broker = RedisBroker(\"redis://localhost:6379\")\n
  2. Initiate your FastStream application with the RedisBroker

    app = FastStream(broker)\n
  3. Define your data model

    class Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n
  4. Set up the function for data processing and publishing

    Using the @broker.publisher(...) decorator in conjunction with the @broker.subscriber(...) decorator allows seamless message processing and republishing to a different stream.

    @broker.subscriber(stream=\"input-stream\")\n@broker.publisher(stream=\"output-stream\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n

    By decorating a function with @broker.publisher(...), we tell FastStream to publish the function's returned data to the designated \"output stream\". The defined function also serves as a subscriber to the \"input-stream\", thereby setting up a straightforward data pipeline within Redis streams.

Here's the complete example that showcases the use of decorators for both subscribing and publishing to Redis streams:

from pydantic import BaseModel, Field, NonNegativeFloat\n\nfrom faststream import FastStream\nfrom faststream.redis import RedisBroker\n\n\nclass Data(BaseModel):\n    data: NonNegativeFloat = Field(\n        ..., examples=[0.5], description=\"Float data example\"\n    )\n\n\nbroker = RedisBroker(\"redis://localhost:6379\")\napp = FastStream(broker)\n\n\n@broker.subscriber(stream=\"input-stream\")\n@broker.publisher(stream=\"output-stream\")\nasync def on_input_data(msg: Data) -> Data:\n    return Data(data=msg.data + 1.0)\n
","boost":10},{"location":"redis/streams/subscription/","title":"Redis Stream Basic Subscriber","text":"

To start consuming from a Redis stream, simply decorate your consuming function with the @broker.subscriber(...) decorator, passing a string as the stream key.

In the following example, we will create a simple FastStream app that will consume messages from a \"test-stream\" Redis stream.

The full app code looks like this:

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n\nbroker = RedisBroker()\napp = FastStream(broker)\n\n\n@broker.subscriber(stream=\"test-stream\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n
","boost":10},{"location":"redis/streams/subscription/#import-faststream-and-redisbroker","title":"Import FastStream and RedisBroker","text":"

To use the @broker.subscriber(...) decorator, first, we need to import the base FastStream app and RedisBroker to create our broker.

from faststream import FastStream, Logger\nfrom faststream.redis import RedisBroker\n
","boost":10},{"location":"redis/streams/subscription/#create-a-redisbroker","title":"Create a RedisBroker","text":"

Next, we will create a RedisBroker object and wrap it into the FastStream object so that we can start our app using CLI later.

broker = RedisBroker()\napp = FastStream(broker)\n
","boost":10},{"location":"redis/streams/subscription/#create-a-function-that-will-consume-messages-from-a-redis-stream","title":"Create a Function that will Consume Messages from a Redis stream","text":"

Let\u2019s create a consumer function that will consume messages from \"test-stream\" Redis stream and log them.

@broker.subscriber(stream=\"test-stream\")\nasync def handle(msg: str, logger: Logger):\n    logger.info(msg)\n

The function decorated with the @broker.subscriber(...) decorator will be called when a message is produced to the Redis stream.

The message will then be injected into the typed msg argument of the function, and its type will be used to parse the message.

In this example case, when the message is sent to a \"test-stream\" stream, it will be received by the handle function, and the logger will log the message content.

","boost":10}]} \ No newline at end of file diff --git a/latest/sitemap.xml.gz b/latest/sitemap.xml.gz index 1729056846b2f75e04485cec93407ef4713aa689..ed66140119c59bc532398ce01262c5a1a26dfb57 100644 GIT binary patch delta 15 WcmbQEIY*OCzMF&NnBPXWX(9k7Tm--X delta 15 WcmbQEIY*OCzMF$1)p8@-G!XzJtprK{